1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===// 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::Legalize method. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ADT/SetVector.h" 15 #include "llvm/ADT/SmallPtrSet.h" 16 #include "llvm/ADT/SmallSet.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Triple.h" 19 #include "llvm/CodeGen/Analysis.h" 20 #include "llvm/CodeGen/MachineFunction.h" 21 #include "llvm/CodeGen/MachineJumpTableInfo.h" 22 #include "llvm/CodeGen/SelectionDAG.h" 23 #include "llvm/CodeGen/SelectionDAGNodes.h" 24 #include "llvm/IR/CallingConv.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/DebugInfo.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetFrameLowering.h" 36 #include "llvm/Target/TargetLowering.h" 37 #include "llvm/Target/TargetMachine.h" 38 #include "llvm/Target/TargetSubtargetInfo.h" 39 using namespace llvm; 40 41 #define DEBUG_TYPE "legalizedag" 42 43 namespace { 44 45 struct FloatSignAsInt; 46 47 //===----------------------------------------------------------------------===// 48 /// This takes an arbitrary SelectionDAG as input and 49 /// hacks on it until the target machine can handle it. This involves 50 /// eliminating value sizes the machine cannot handle (promoting small sizes to 51 /// large sizes or splitting up large values into small values) as well as 52 /// eliminating operations the machine cannot handle. 53 /// 54 /// This code also does a small amount of optimization and recognition of idioms 55 /// as part of its processing. For example, if a target does not support a 56 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this 57 /// will attempt merge setcc and brc instructions into brcc's. 58 /// 59 class SelectionDAGLegalize { 60 const TargetMachine &TM; 61 const TargetLowering &TLI; 62 SelectionDAG &DAG; 63 64 /// \brief The set of nodes which have already been legalized. We hold a 65 /// reference to it in order to update as necessary on node deletion. 66 SmallPtrSetImpl<SDNode *> &LegalizedNodes; 67 68 /// \brief A set of all the nodes updated during legalization. 69 SmallSetVector<SDNode *, 16> *UpdatedNodes; 70 71 EVT getSetCCResultType(EVT VT) const { 72 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 73 } 74 75 // Libcall insertion helpers. 76 77 public: 78 SelectionDAGLegalize(SelectionDAG &DAG, 79 SmallPtrSetImpl<SDNode *> &LegalizedNodes, 80 SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr) 81 : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG), 82 LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {} 83 84 /// \brief Legalizes the given operation. 85 void LegalizeOp(SDNode *Node); 86 87 private: 88 SDValue OptimizeFloatStore(StoreSDNode *ST); 89 90 void LegalizeLoadOps(SDNode *Node); 91 void LegalizeStoreOps(SDNode *Node); 92 93 /// Some targets cannot handle a variable 94 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it 95 /// is necessary to spill the vector being inserted into to memory, perform 96 /// the insert there, and then read the result back. 97 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx, 98 const SDLoc &dl); 99 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, 100 const SDLoc &dl); 101 102 /// Return a vector shuffle operation which 103 /// performs the same shuffe in terms of order or result bytes, but on a type 104 /// whose vector element type is narrower than the original shuffle type. 105 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3> 106 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl, 107 SDValue N1, SDValue N2, 108 ArrayRef<int> Mask) const; 109 110 bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC, 111 bool &NeedInvert, const SDLoc &dl); 112 113 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned); 114 SDValue ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, const SDValue *Ops, 115 unsigned NumOps, bool isSigned, const SDLoc &dl); 116 117 std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC, 118 SDNode *Node, bool isSigned); 119 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32, 120 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80, 121 RTLIB::Libcall Call_F128, 122 RTLIB::Libcall Call_PPCF128); 123 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned, 124 RTLIB::Libcall Call_I8, 125 RTLIB::Libcall Call_I16, 126 RTLIB::Libcall Call_I32, 127 RTLIB::Libcall Call_I64, 128 RTLIB::Libcall Call_I128); 129 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results); 130 void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results); 131 132 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, 133 const SDLoc &dl); 134 SDValue ExpandBUILD_VECTOR(SDNode *Node); 135 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node); 136 void ExpandDYNAMIC_STACKALLOC(SDNode *Node, 137 SmallVectorImpl<SDValue> &Results); 138 void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL, 139 SDValue Value) const; 140 SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL, 141 SDValue NewIntValue) const; 142 SDValue ExpandFCOPYSIGN(SDNode *Node) const; 143 SDValue ExpandFABS(SDNode *Node) const; 144 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT, 145 const SDLoc &dl); 146 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned, 147 const SDLoc &dl); 148 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned, 149 const SDLoc &dl); 150 151 SDValue ExpandBITREVERSE(SDValue Op, const SDLoc &dl); 152 SDValue ExpandBSWAP(SDValue Op, const SDLoc &dl); 153 SDValue ExpandBitCount(unsigned Opc, SDValue Op, const SDLoc &dl); 154 155 SDValue ExpandExtractFromVectorThroughStack(SDValue Op); 156 SDValue ExpandInsertToVectorThroughStack(SDValue Op); 157 SDValue ExpandVectorBuildThroughStack(SDNode* Node); 158 159 SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP); 160 SDValue ExpandConstant(ConstantSDNode *CP); 161 162 // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall 163 bool ExpandNode(SDNode *Node); 164 void ConvertNodeToLibcall(SDNode *Node); 165 void PromoteNode(SDNode *Node); 166 167 public: 168 // Node replacement helpers 169 void ReplacedNode(SDNode *N) { 170 LegalizedNodes.erase(N); 171 if (UpdatedNodes) 172 UpdatedNodes->insert(N); 173 } 174 void ReplaceNode(SDNode *Old, SDNode *New) { 175 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG); 176 dbgs() << " with: "; New->dump(&DAG)); 177 178 assert(Old->getNumValues() == New->getNumValues() && 179 "Replacing one node with another that produces a different number " 180 "of values!"); 181 DAG.ReplaceAllUsesWith(Old, New); 182 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) 183 DAG.TransferDbgValues(SDValue(Old, i), SDValue(New, i)); 184 if (UpdatedNodes) 185 UpdatedNodes->insert(New); 186 ReplacedNode(Old); 187 } 188 void ReplaceNode(SDValue Old, SDValue New) { 189 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG); 190 dbgs() << " with: "; New->dump(&DAG)); 191 192 DAG.ReplaceAllUsesWith(Old, New); 193 DAG.TransferDbgValues(Old, New); 194 if (UpdatedNodes) 195 UpdatedNodes->insert(New.getNode()); 196 ReplacedNode(Old.getNode()); 197 } 198 void ReplaceNode(SDNode *Old, const SDValue *New) { 199 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG)); 200 201 DAG.ReplaceAllUsesWith(Old, New); 202 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) { 203 DEBUG(dbgs() << (i == 0 ? " with: " 204 : " and: "); 205 New[i]->dump(&DAG)); 206 DAG.TransferDbgValues(SDValue(Old, i), New[i]); 207 if (UpdatedNodes) 208 UpdatedNodes->insert(New[i].getNode()); 209 } 210 ReplacedNode(Old); 211 } 212 }; 213 } 214 215 /// Return a vector shuffle operation which 216 /// performs the same shuffe in terms of order or result bytes, but on a type 217 /// whose vector element type is narrower than the original shuffle type. 218 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3> 219 SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType( 220 EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, 221 ArrayRef<int> Mask) const { 222 unsigned NumMaskElts = VT.getVectorNumElements(); 223 unsigned NumDestElts = NVT.getVectorNumElements(); 224 unsigned NumEltsGrowth = NumDestElts / NumMaskElts; 225 226 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!"); 227 228 if (NumEltsGrowth == 1) 229 return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]); 230 231 SmallVector<int, 8> NewMask; 232 for (unsigned i = 0; i != NumMaskElts; ++i) { 233 int Idx = Mask[i]; 234 for (unsigned j = 0; j != NumEltsGrowth; ++j) { 235 if (Idx < 0) 236 NewMask.push_back(-1); 237 else 238 NewMask.push_back(Idx * NumEltsGrowth + j); 239 } 240 } 241 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?"); 242 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?"); 243 return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]); 244 } 245 246 /// Expands the ConstantFP node to an integer constant or 247 /// a load from the constant pool. 248 SDValue 249 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) { 250 bool Extend = false; 251 SDLoc dl(CFP); 252 253 // If a FP immediate is precise when represented as a float and if the 254 // target can do an extending load from float to double, we put it into 255 // the constant pool as a float, even if it's is statically typed as a 256 // double. This shrinks FP constants and canonicalizes them for targets where 257 // an FP extending load is the same cost as a normal load (such as on the x87 258 // fp stack or PPC FP unit). 259 EVT VT = CFP->getValueType(0); 260 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue()); 261 if (!UseCP) { 262 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion"); 263 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl, 264 (VT == MVT::f64) ? MVT::i64 : MVT::i32); 265 } 266 267 EVT OrigVT = VT; 268 EVT SVT = VT; 269 while (SVT != MVT::f32 && SVT != MVT::f16) { 270 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1); 271 if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) && 272 // Only do this if the target has a native EXTLOAD instruction from 273 // smaller type. 274 TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) && 275 TLI.ShouldShrinkFPConstant(OrigVT)) { 276 Type *SType = SVT.getTypeForEVT(*DAG.getContext()); 277 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType)); 278 VT = SVT; 279 Extend = true; 280 } 281 } 282 283 SDValue CPIdx = 284 DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout())); 285 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 286 if (Extend) { 287 SDValue Result = DAG.getExtLoad( 288 ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx, 289 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT, 290 false, false, false, Alignment); 291 return Result; 292 } 293 SDValue Result = 294 DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx, 295 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 296 false, false, false, Alignment); 297 return Result; 298 } 299 300 /// Expands the Constant node to a load from the constant pool. 301 SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) { 302 SDLoc dl(CP); 303 EVT VT = CP->getValueType(0); 304 SDValue CPIdx = DAG.getConstantPool(CP->getConstantIntValue(), 305 TLI.getPointerTy(DAG.getDataLayout())); 306 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 307 SDValue Result = 308 DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 309 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 310 false, false, false, Alignment); 311 return Result; 312 } 313 314 /// Some target cannot handle a variable insertion index for the 315 /// INSERT_VECTOR_ELT instruction. In this case, it 316 /// is necessary to spill the vector being inserted into to memory, perform 317 /// the insert there, and then read the result back. 318 SDValue SelectionDAGLegalize::PerformInsertVectorEltInMemory(SDValue Vec, 319 SDValue Val, 320 SDValue Idx, 321 const SDLoc &dl) { 322 SDValue Tmp1 = Vec; 323 SDValue Tmp2 = Val; 324 SDValue Tmp3 = Idx; 325 326 // If the target doesn't support this, we have to spill the input vector 327 // to a temporary stack slot, update the element, then reload it. This is 328 // badness. We could also load the value into a vector register (either 329 // with a "move to register" or "extload into register" instruction, then 330 // permute it into place, if the idx is a constant and if the idx is 331 // supported by the target. 332 EVT VT = Tmp1.getValueType(); 333 EVT EltVT = VT.getVectorElementType(); 334 EVT IdxVT = Tmp3.getValueType(); 335 EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 336 SDValue StackPtr = DAG.CreateStackTemporary(VT); 337 338 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 339 340 // Store the vector. 341 SDValue Ch = DAG.getStore( 342 DAG.getEntryNode(), dl, Tmp1, StackPtr, 343 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI), false, 344 false, 0); 345 346 // Truncate or zero extend offset to target pointer type. 347 Tmp3 = DAG.getZExtOrTrunc(Tmp3, dl, PtrVT); 348 // Add the offset to the index. 349 unsigned EltSize = EltVT.getSizeInBits()/8; 350 Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3, 351 DAG.getConstant(EltSize, dl, IdxVT)); 352 SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr); 353 // Store the scalar value. 354 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT, 355 false, false, 0); 356 // Load the updated vector. 357 return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack( 358 DAG.getMachineFunction(), SPFI), 359 false, false, false, 0); 360 } 361 362 SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, 363 SDValue Idx, 364 const SDLoc &dl) { 365 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) { 366 // SCALAR_TO_VECTOR requires that the type of the value being inserted 367 // match the element type of the vector being created, except for 368 // integers in which case the inserted value can be over width. 369 EVT EltVT = Vec.getValueType().getVectorElementType(); 370 if (Val.getValueType() == EltVT || 371 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) { 372 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 373 Vec.getValueType(), Val); 374 375 unsigned NumElts = Vec.getValueType().getVectorNumElements(); 376 // We generate a shuffle of InVec and ScVec, so the shuffle mask 377 // should be 0,1,2,3,4,5... with the appropriate element replaced with 378 // elt 0 of the RHS. 379 SmallVector<int, 8> ShufOps; 380 for (unsigned i = 0; i != NumElts; ++i) 381 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts); 382 383 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, 384 &ShufOps[0]); 385 } 386 } 387 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl); 388 } 389 390 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) { 391 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 392 // FIXME: We shouldn't do this for TargetConstantFP's. 393 // FIXME: move this to the DAG Combiner! Note that we can't regress due 394 // to phase ordering between legalized code and the dag combiner. This 395 // probably means that we need to integrate dag combiner and legalizer 396 // together. 397 // We generally can't do this one for long doubles. 398 SDValue Chain = ST->getChain(); 399 SDValue Ptr = ST->getBasePtr(); 400 unsigned Alignment = ST->getAlignment(); 401 bool isVolatile = ST->isVolatile(); 402 bool isNonTemporal = ST->isNonTemporal(); 403 AAMDNodes AAInfo = ST->getAAInfo(); 404 SDLoc dl(ST); 405 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) { 406 if (CFP->getValueType(0) == MVT::f32 && 407 TLI.isTypeLegal(MVT::i32)) { 408 SDValue Con = DAG.getConstant(CFP->getValueAPF(). 409 bitcastToAPInt().zextOrTrunc(32), 410 SDLoc(CFP), MVT::i32); 411 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), 412 isVolatile, isNonTemporal, Alignment, AAInfo); 413 } 414 415 if (CFP->getValueType(0) == MVT::f64) { 416 // If this target supports 64-bit registers, do a single 64-bit store. 417 if (TLI.isTypeLegal(MVT::i64)) { 418 SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 419 zextOrTrunc(64), SDLoc(CFP), MVT::i64); 420 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), 421 isVolatile, isNonTemporal, Alignment, AAInfo); 422 } 423 424 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) { 425 // Otherwise, if the target supports 32-bit registers, use 2 32-bit 426 // stores. If the target supports neither 32- nor 64-bits, this 427 // xform is certainly not worth it. 428 const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt(); 429 SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32); 430 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32); 431 if (DAG.getDataLayout().isBigEndian()) 432 std::swap(Lo, Hi); 433 434 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), isVolatile, 435 isNonTemporal, Alignment, AAInfo); 436 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 437 DAG.getConstant(4, dl, Ptr.getValueType())); 438 Hi = DAG.getStore(Chain, dl, Hi, Ptr, 439 ST->getPointerInfo().getWithOffset(4), 440 isVolatile, isNonTemporal, MinAlign(Alignment, 4U), 441 AAInfo); 442 443 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi); 444 } 445 } 446 } 447 return SDValue(nullptr, 0); 448 } 449 450 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) { 451 StoreSDNode *ST = cast<StoreSDNode>(Node); 452 SDValue Chain = ST->getChain(); 453 SDValue Ptr = ST->getBasePtr(); 454 SDLoc dl(Node); 455 456 unsigned Alignment = ST->getAlignment(); 457 bool isVolatile = ST->isVolatile(); 458 bool isNonTemporal = ST->isNonTemporal(); 459 AAMDNodes AAInfo = ST->getAAInfo(); 460 461 if (!ST->isTruncatingStore()) { 462 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) { 463 ReplaceNode(ST, OptStore); 464 return; 465 } 466 467 { 468 SDValue Value = ST->getValue(); 469 MVT VT = Value.getSimpleValueType(); 470 switch (TLI.getOperationAction(ISD::STORE, VT)) { 471 default: llvm_unreachable("This action is not supported yet!"); 472 case TargetLowering::Legal: { 473 // If this is an unaligned store and the target doesn't support it, 474 // expand it. 475 EVT MemVT = ST->getMemoryVT(); 476 unsigned AS = ST->getAddressSpace(); 477 unsigned Align = ST->getAlignment(); 478 const DataLayout &DL = DAG.getDataLayout(); 479 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 480 SDValue Result = TLI.expandUnalignedStore(ST, DAG); 481 ReplaceNode(SDValue(ST, 0), Result); 482 } 483 break; 484 } 485 case TargetLowering::Custom: { 486 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG); 487 if (Res && Res != SDValue(Node, 0)) 488 ReplaceNode(SDValue(Node, 0), Res); 489 return; 490 } 491 case TargetLowering::Promote: { 492 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT); 493 assert(NVT.getSizeInBits() == VT.getSizeInBits() && 494 "Can only promote stores to same size type"); 495 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value); 496 SDValue Result = 497 DAG.getStore(Chain, dl, Value, Ptr, 498 ST->getPointerInfo(), isVolatile, 499 isNonTemporal, Alignment, AAInfo); 500 ReplaceNode(SDValue(Node, 0), Result); 501 break; 502 } 503 } 504 return; 505 } 506 } else { 507 SDValue Value = ST->getValue(); 508 509 EVT StVT = ST->getMemoryVT(); 510 unsigned StWidth = StVT.getSizeInBits(); 511 auto &DL = DAG.getDataLayout(); 512 513 if (StWidth != StVT.getStoreSizeInBits()) { 514 // Promote to a byte-sized store with upper bits zero if not 515 // storing an integral number of bytes. For example, promote 516 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1) 517 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), 518 StVT.getStoreSizeInBits()); 519 Value = DAG.getZeroExtendInReg(Value, dl, StVT); 520 SDValue Result = 521 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 522 NVT, isVolatile, isNonTemporal, Alignment, AAInfo); 523 ReplaceNode(SDValue(Node, 0), Result); 524 } else if (StWidth & (StWidth - 1)) { 525 // If not storing a power-of-2 number of bits, expand as two stores. 526 assert(!StVT.isVector() && "Unsupported truncstore!"); 527 unsigned RoundWidth = 1 << Log2_32(StWidth); 528 assert(RoundWidth < StWidth); 529 unsigned ExtraWidth = StWidth - RoundWidth; 530 assert(ExtraWidth < RoundWidth); 531 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) && 532 "Store size not an integral number of bytes!"); 533 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth); 534 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth); 535 SDValue Lo, Hi; 536 unsigned IncrementSize; 537 538 if (DL.isLittleEndian()) { 539 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16) 540 // Store the bottom RoundWidth bits. 541 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 542 RoundVT, 543 isVolatile, isNonTemporal, Alignment, 544 AAInfo); 545 546 // Store the remaining ExtraWidth bits. 547 IncrementSize = RoundWidth / 8; 548 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 549 DAG.getConstant(IncrementSize, dl, 550 Ptr.getValueType())); 551 Hi = DAG.getNode( 552 ISD::SRL, dl, Value.getValueType(), Value, 553 DAG.getConstant(RoundWidth, dl, 554 TLI.getShiftAmountTy(Value.getValueType(), DL))); 555 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, 556 ST->getPointerInfo().getWithOffset(IncrementSize), 557 ExtraVT, isVolatile, isNonTemporal, 558 MinAlign(Alignment, IncrementSize), AAInfo); 559 } else { 560 // Big endian - avoid unaligned stores. 561 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X 562 // Store the top RoundWidth bits. 563 Hi = DAG.getNode( 564 ISD::SRL, dl, Value.getValueType(), Value, 565 DAG.getConstant(ExtraWidth, dl, 566 TLI.getShiftAmountTy(Value.getValueType(), DL))); 567 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(), 568 RoundVT, isVolatile, isNonTemporal, Alignment, 569 AAInfo); 570 571 // Store the remaining ExtraWidth bits. 572 IncrementSize = RoundWidth / 8; 573 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 574 DAG.getConstant(IncrementSize, dl, 575 Ptr.getValueType())); 576 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, 577 ST->getPointerInfo().getWithOffset(IncrementSize), 578 ExtraVT, isVolatile, isNonTemporal, 579 MinAlign(Alignment, IncrementSize), AAInfo); 580 } 581 582 // The order of the stores doesn't matter. 583 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi); 584 ReplaceNode(SDValue(Node, 0), Result); 585 } else { 586 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) { 587 default: llvm_unreachable("This action is not supported yet!"); 588 case TargetLowering::Legal: { 589 EVT MemVT = ST->getMemoryVT(); 590 unsigned AS = ST->getAddressSpace(); 591 unsigned Align = ST->getAlignment(); 592 // If this is an unaligned store and the target doesn't support it, 593 // expand it. 594 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 595 SDValue Result = TLI.expandUnalignedStore(ST, DAG); 596 ReplaceNode(SDValue(ST, 0), Result); 597 } 598 break; 599 } 600 case TargetLowering::Custom: { 601 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG); 602 if (Res && Res != SDValue(Node, 0)) 603 ReplaceNode(SDValue(Node, 0), Res); 604 return; 605 } 606 case TargetLowering::Expand: 607 assert(!StVT.isVector() && 608 "Vector Stores are handled in LegalizeVectorOps"); 609 610 // TRUNCSTORE:i16 i32 -> STORE i16 611 assert(TLI.isTypeLegal(StVT) && 612 "Do not know how to expand this store!"); 613 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value); 614 SDValue Result = 615 DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 616 isVolatile, isNonTemporal, Alignment, AAInfo); 617 ReplaceNode(SDValue(Node, 0), Result); 618 break; 619 } 620 } 621 } 622 } 623 624 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) { 625 LoadSDNode *LD = cast<LoadSDNode>(Node); 626 SDValue Chain = LD->getChain(); // The chain. 627 SDValue Ptr = LD->getBasePtr(); // The base pointer. 628 SDValue Value; // The value returned by the load op. 629 SDLoc dl(Node); 630 631 ISD::LoadExtType ExtType = LD->getExtensionType(); 632 if (ExtType == ISD::NON_EXTLOAD) { 633 MVT VT = Node->getSimpleValueType(0); 634 SDValue RVal = SDValue(Node, 0); 635 SDValue RChain = SDValue(Node, 1); 636 637 switch (TLI.getOperationAction(Node->getOpcode(), VT)) { 638 default: llvm_unreachable("This action is not supported yet!"); 639 case TargetLowering::Legal: { 640 EVT MemVT = LD->getMemoryVT(); 641 unsigned AS = LD->getAddressSpace(); 642 unsigned Align = LD->getAlignment(); 643 const DataLayout &DL = DAG.getDataLayout(); 644 // If this is an unaligned load and the target doesn't support it, 645 // expand it. 646 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 647 std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG); 648 } 649 break; 650 } 651 case TargetLowering::Custom: { 652 if (SDValue Res = TLI.LowerOperation(RVal, DAG)) { 653 RVal = Res; 654 RChain = Res.getValue(1); 655 } 656 break; 657 } 658 case TargetLowering::Promote: { 659 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT); 660 assert(NVT.getSizeInBits() == VT.getSizeInBits() && 661 "Can only promote loads to same size type"); 662 663 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand()); 664 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res); 665 RChain = Res.getValue(1); 666 break; 667 } 668 } 669 if (RChain.getNode() != Node) { 670 assert(RVal.getNode() != Node && "Load must be completely replaced"); 671 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal); 672 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain); 673 if (UpdatedNodes) { 674 UpdatedNodes->insert(RVal.getNode()); 675 UpdatedNodes->insert(RChain.getNode()); 676 } 677 ReplacedNode(Node); 678 } 679 return; 680 } 681 682 EVT SrcVT = LD->getMemoryVT(); 683 unsigned SrcWidth = SrcVT.getSizeInBits(); 684 unsigned Alignment = LD->getAlignment(); 685 bool isVolatile = LD->isVolatile(); 686 bool isNonTemporal = LD->isNonTemporal(); 687 bool isInvariant = LD->isInvariant(); 688 AAMDNodes AAInfo = LD->getAAInfo(); 689 690 if (SrcWidth != SrcVT.getStoreSizeInBits() && 691 // Some targets pretend to have an i1 loading operation, and actually 692 // load an i8. This trick is correct for ZEXTLOAD because the top 7 693 // bits are guaranteed to be zero; it helps the optimizers understand 694 // that these bits are zero. It is also useful for EXTLOAD, since it 695 // tells the optimizers that those bits are undefined. It would be 696 // nice to have an effective generic way of getting these benefits... 697 // Until such a way is found, don't insist on promoting i1 here. 698 (SrcVT != MVT::i1 || 699 TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) == 700 TargetLowering::Promote)) { 701 // Promote to a byte-sized load if not loading an integral number of 702 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24. 703 unsigned NewWidth = SrcVT.getStoreSizeInBits(); 704 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth); 705 SDValue Ch; 706 707 // The extra bits are guaranteed to be zero, since we stored them that 708 // way. A zext load from NVT thus automatically gives zext from SrcVT. 709 710 ISD::LoadExtType NewExtType = 711 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD; 712 713 SDValue Result = 714 DAG.getExtLoad(NewExtType, dl, Node->getValueType(0), 715 Chain, Ptr, LD->getPointerInfo(), 716 NVT, isVolatile, isNonTemporal, isInvariant, Alignment, 717 AAInfo); 718 719 Ch = Result.getValue(1); // The chain. 720 721 if (ExtType == ISD::SEXTLOAD) 722 // Having the top bits zero doesn't help when sign extending. 723 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, 724 Result.getValueType(), 725 Result, DAG.getValueType(SrcVT)); 726 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType()) 727 // All the top bits are guaranteed to be zero - inform the optimizers. 728 Result = DAG.getNode(ISD::AssertZext, dl, 729 Result.getValueType(), Result, 730 DAG.getValueType(SrcVT)); 731 732 Value = Result; 733 Chain = Ch; 734 } else if (SrcWidth & (SrcWidth - 1)) { 735 // If not loading a power-of-2 number of bits, expand as two loads. 736 assert(!SrcVT.isVector() && "Unsupported extload!"); 737 unsigned RoundWidth = 1 << Log2_32(SrcWidth); 738 assert(RoundWidth < SrcWidth); 739 unsigned ExtraWidth = SrcWidth - RoundWidth; 740 assert(ExtraWidth < RoundWidth); 741 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) && 742 "Load size not an integral number of bytes!"); 743 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth); 744 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth); 745 SDValue Lo, Hi, Ch; 746 unsigned IncrementSize; 747 auto &DL = DAG.getDataLayout(); 748 749 if (DL.isLittleEndian()) { 750 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16) 751 // Load the bottom RoundWidth bits. 752 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), 753 Chain, Ptr, 754 LD->getPointerInfo(), RoundVT, isVolatile, 755 isNonTemporal, isInvariant, Alignment, AAInfo); 756 757 // Load the remaining ExtraWidth bits. 758 IncrementSize = RoundWidth / 8; 759 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 760 DAG.getConstant(IncrementSize, dl, 761 Ptr.getValueType())); 762 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr, 763 LD->getPointerInfo().getWithOffset(IncrementSize), 764 ExtraVT, isVolatile, isNonTemporal, isInvariant, 765 MinAlign(Alignment, IncrementSize), AAInfo); 766 767 // Build a factor node to remember that this load is independent of 768 // the other one. 769 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 770 Hi.getValue(1)); 771 772 // Move the top bits to the right place. 773 Hi = DAG.getNode( 774 ISD::SHL, dl, Hi.getValueType(), Hi, 775 DAG.getConstant(RoundWidth, dl, 776 TLI.getShiftAmountTy(Hi.getValueType(), DL))); 777 778 // Join the hi and lo parts. 779 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi); 780 } else { 781 // Big endian - avoid unaligned loads. 782 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8 783 // Load the top RoundWidth bits. 784 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr, 785 LD->getPointerInfo(), RoundVT, isVolatile, 786 isNonTemporal, isInvariant, Alignment, AAInfo); 787 788 // Load the remaining ExtraWidth bits. 789 IncrementSize = RoundWidth / 8; 790 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 791 DAG.getConstant(IncrementSize, dl, 792 Ptr.getValueType())); 793 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, 794 dl, Node->getValueType(0), Chain, Ptr, 795 LD->getPointerInfo().getWithOffset(IncrementSize), 796 ExtraVT, isVolatile, isNonTemporal, isInvariant, 797 MinAlign(Alignment, IncrementSize), AAInfo); 798 799 // Build a factor node to remember that this load is independent of 800 // the other one. 801 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 802 Hi.getValue(1)); 803 804 // Move the top bits to the right place. 805 Hi = DAG.getNode( 806 ISD::SHL, dl, Hi.getValueType(), Hi, 807 DAG.getConstant(ExtraWidth, dl, 808 TLI.getShiftAmountTy(Hi.getValueType(), DL))); 809 810 // Join the hi and lo parts. 811 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi); 812 } 813 814 Chain = Ch; 815 } else { 816 bool isCustom = false; 817 switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0), 818 SrcVT.getSimpleVT())) { 819 default: llvm_unreachable("This action is not supported yet!"); 820 case TargetLowering::Custom: 821 isCustom = true; 822 // FALLTHROUGH 823 case TargetLowering::Legal: { 824 Value = SDValue(Node, 0); 825 Chain = SDValue(Node, 1); 826 827 if (isCustom) { 828 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) { 829 Value = Res; 830 Chain = Res.getValue(1); 831 } 832 } else { 833 // If this is an unaligned load and the target doesn't support it, 834 // expand it. 835 EVT MemVT = LD->getMemoryVT(); 836 unsigned AS = LD->getAddressSpace(); 837 unsigned Align = LD->getAlignment(); 838 const DataLayout &DL = DAG.getDataLayout(); 839 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 840 std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG); 841 } 842 } 843 break; 844 } 845 case TargetLowering::Expand: 846 EVT DestVT = Node->getValueType(0); 847 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) { 848 // If the source type is not legal, see if there is a legal extload to 849 // an intermediate type that we can then extend further. 850 EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT()); 851 if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT? 852 TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) { 853 // If we are loading a legal type, this is a non-extload followed by a 854 // full extend. 855 ISD::LoadExtType MidExtType = 856 (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType; 857 858 SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr, 859 SrcVT, LD->getMemOperand()); 860 unsigned ExtendOp = 861 ISD::getExtForLoadExtType(SrcVT.isFloatingPoint(), ExtType); 862 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load); 863 Chain = Load.getValue(1); 864 break; 865 } 866 867 // Handle the special case of fp16 extloads. EXTLOAD doesn't have the 868 // normal undefined upper bits behavior to allow using an in-reg extend 869 // with the illegal FP type, so load as an integer and do the 870 // from-integer conversion. 871 if (SrcVT.getScalarType() == MVT::f16) { 872 EVT ISrcVT = SrcVT.changeTypeToInteger(); 873 EVT IDestVT = DestVT.changeTypeToInteger(); 874 EVT LoadVT = TLI.getRegisterType(IDestVT.getSimpleVT()); 875 876 SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, LoadVT, 877 Chain, Ptr, ISrcVT, 878 LD->getMemOperand()); 879 Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result); 880 Chain = Result.getValue(1); 881 break; 882 } 883 } 884 885 assert(!SrcVT.isVector() && 886 "Vector Loads are handled in LegalizeVectorOps"); 887 888 // FIXME: This does not work for vectors on most targets. Sign- 889 // and zero-extend operations are currently folded into extending 890 // loads, whether they are legal or not, and then we end up here 891 // without any support for legalizing them. 892 assert(ExtType != ISD::EXTLOAD && 893 "EXTLOAD should always be supported!"); 894 // Turn the unsupported load into an EXTLOAD followed by an 895 // explicit zero/sign extend inreg. 896 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl, 897 Node->getValueType(0), 898 Chain, Ptr, SrcVT, 899 LD->getMemOperand()); 900 SDValue ValRes; 901 if (ExtType == ISD::SEXTLOAD) 902 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, 903 Result.getValueType(), 904 Result, DAG.getValueType(SrcVT)); 905 else 906 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType()); 907 Value = ValRes; 908 Chain = Result.getValue(1); 909 break; 910 } 911 } 912 913 // Since loads produce two values, make sure to remember that we legalized 914 // both of them. 915 if (Chain.getNode() != Node) { 916 assert(Value.getNode() != Node && "Load must be completely replaced"); 917 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value); 918 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain); 919 if (UpdatedNodes) { 920 UpdatedNodes->insert(Value.getNode()); 921 UpdatedNodes->insert(Chain.getNode()); 922 } 923 ReplacedNode(Node); 924 } 925 } 926 927 /// Return a legal replacement for the given operation, with all legal operands. 928 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) { 929 DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG)); 930 931 if (Node->getOpcode() == ISD::TargetConstant) // Allow illegal target nodes. 932 return; 933 934 #ifndef NDEBUG 935 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) 936 assert((TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) == 937 TargetLowering::TypeLegal || 938 TLI.isTypeLegal(Node->getValueType(i))) && 939 "Unexpected illegal type!"); 940 941 for (const SDValue &Op : Node->op_values()) 942 assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) == 943 TargetLowering::TypeLegal || 944 TLI.isTypeLegal(Op.getValueType()) || 945 Op.getOpcode() == ISD::TargetConstant) && 946 "Unexpected illegal type!"); 947 #endif 948 949 // Figure out the correct action; the way to query this varies by opcode 950 TargetLowering::LegalizeAction Action = TargetLowering::Legal; 951 bool SimpleFinishLegalizing = true; 952 switch (Node->getOpcode()) { 953 case ISD::INTRINSIC_W_CHAIN: 954 case ISD::INTRINSIC_WO_CHAIN: 955 case ISD::INTRINSIC_VOID: 956 case ISD::STACKSAVE: 957 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other); 958 break; 959 case ISD::GET_DYNAMIC_AREA_OFFSET: 960 Action = TLI.getOperationAction(Node->getOpcode(), 961 Node->getValueType(0)); 962 break; 963 case ISD::VAARG: 964 Action = TLI.getOperationAction(Node->getOpcode(), 965 Node->getValueType(0)); 966 if (Action != TargetLowering::Promote) 967 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other); 968 break; 969 case ISD::FP_TO_FP16: 970 case ISD::SINT_TO_FP: 971 case ISD::UINT_TO_FP: 972 case ISD::EXTRACT_VECTOR_ELT: 973 Action = TLI.getOperationAction(Node->getOpcode(), 974 Node->getOperand(0).getValueType()); 975 break; 976 case ISD::FP_ROUND_INREG: 977 case ISD::SIGN_EXTEND_INREG: { 978 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT(); 979 Action = TLI.getOperationAction(Node->getOpcode(), InnerType); 980 break; 981 } 982 case ISD::ATOMIC_STORE: { 983 Action = TLI.getOperationAction(Node->getOpcode(), 984 Node->getOperand(2).getValueType()); 985 break; 986 } 987 case ISD::SELECT_CC: 988 case ISD::SETCC: 989 case ISD::BR_CC: { 990 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 : 991 Node->getOpcode() == ISD::SETCC ? 2 : 992 Node->getOpcode() == ISD::SETCCE ? 3 : 1; 993 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0; 994 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType(); 995 ISD::CondCode CCCode = 996 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get(); 997 Action = TLI.getCondCodeAction(CCCode, OpVT); 998 if (Action == TargetLowering::Legal) { 999 if (Node->getOpcode() == ISD::SELECT_CC) 1000 Action = TLI.getOperationAction(Node->getOpcode(), 1001 Node->getValueType(0)); 1002 else 1003 Action = TLI.getOperationAction(Node->getOpcode(), OpVT); 1004 } 1005 break; 1006 } 1007 case ISD::LOAD: 1008 case ISD::STORE: 1009 // FIXME: Model these properly. LOAD and STORE are complicated, and 1010 // STORE expects the unlegalized operand in some cases. 1011 SimpleFinishLegalizing = false; 1012 break; 1013 case ISD::CALLSEQ_START: 1014 case ISD::CALLSEQ_END: 1015 // FIXME: This shouldn't be necessary. These nodes have special properties 1016 // dealing with the recursive nature of legalization. Removing this 1017 // special case should be done as part of making LegalizeDAG non-recursive. 1018 SimpleFinishLegalizing = false; 1019 break; 1020 case ISD::EXTRACT_ELEMENT: 1021 case ISD::FLT_ROUNDS_: 1022 case ISD::FPOWI: 1023 case ISD::MERGE_VALUES: 1024 case ISD::EH_RETURN: 1025 case ISD::FRAME_TO_ARGS_OFFSET: 1026 case ISD::EH_SJLJ_SETJMP: 1027 case ISD::EH_SJLJ_LONGJMP: 1028 case ISD::EH_SJLJ_SETUP_DISPATCH: 1029 // These operations lie about being legal: when they claim to be legal, 1030 // they should actually be expanded. 1031 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1032 if (Action == TargetLowering::Legal) 1033 Action = TargetLowering::Expand; 1034 break; 1035 case ISD::INIT_TRAMPOLINE: 1036 case ISD::ADJUST_TRAMPOLINE: 1037 case ISD::FRAMEADDR: 1038 case ISD::RETURNADDR: 1039 // These operations lie about being legal: when they claim to be legal, 1040 // they should actually be custom-lowered. 1041 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1042 if (Action == TargetLowering::Legal) 1043 Action = TargetLowering::Custom; 1044 break; 1045 case ISD::READCYCLECOUNTER: 1046 // READCYCLECOUNTER returns an i64, even if type legalization might have 1047 // expanded that to several smaller types. 1048 Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64); 1049 break; 1050 case ISD::READ_REGISTER: 1051 case ISD::WRITE_REGISTER: 1052 // Named register is legal in the DAG, but blocked by register name 1053 // selection if not implemented by target (to chose the correct register) 1054 // They'll be converted to Copy(To/From)Reg. 1055 Action = TargetLowering::Legal; 1056 break; 1057 case ISD::DEBUGTRAP: 1058 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1059 if (Action == TargetLowering::Expand) { 1060 // replace ISD::DEBUGTRAP with ISD::TRAP 1061 SDValue NewVal; 1062 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(), 1063 Node->getOperand(0)); 1064 ReplaceNode(Node, NewVal.getNode()); 1065 LegalizeOp(NewVal.getNode()); 1066 return; 1067 } 1068 break; 1069 1070 default: 1071 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) { 1072 Action = TargetLowering::Legal; 1073 } else { 1074 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1075 } 1076 break; 1077 } 1078 1079 if (SimpleFinishLegalizing) { 1080 SDNode *NewNode = Node; 1081 switch (Node->getOpcode()) { 1082 default: break; 1083 case ISD::SHL: 1084 case ISD::SRL: 1085 case ISD::SRA: 1086 case ISD::ROTL: 1087 case ISD::ROTR: 1088 // Legalizing shifts/rotates requires adjusting the shift amount 1089 // to the appropriate width. 1090 if (!Node->getOperand(1).getValueType().isVector()) { 1091 SDValue SAO = 1092 DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(), 1093 Node->getOperand(1)); 1094 HandleSDNode Handle(SAO); 1095 LegalizeOp(SAO.getNode()); 1096 NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0), 1097 Handle.getValue()); 1098 } 1099 break; 1100 case ISD::SRL_PARTS: 1101 case ISD::SRA_PARTS: 1102 case ISD::SHL_PARTS: 1103 // Legalizing shifts/rotates requires adjusting the shift amount 1104 // to the appropriate width. 1105 if (!Node->getOperand(2).getValueType().isVector()) { 1106 SDValue SAO = 1107 DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(), 1108 Node->getOperand(2)); 1109 HandleSDNode Handle(SAO); 1110 LegalizeOp(SAO.getNode()); 1111 NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0), 1112 Node->getOperand(1), 1113 Handle.getValue()); 1114 } 1115 break; 1116 } 1117 1118 if (NewNode != Node) { 1119 ReplaceNode(Node, NewNode); 1120 Node = NewNode; 1121 } 1122 switch (Action) { 1123 case TargetLowering::Legal: 1124 return; 1125 case TargetLowering::Custom: { 1126 // FIXME: The handling for custom lowering with multiple results is 1127 // a complete mess. 1128 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) { 1129 if (!(Res.getNode() != Node || Res.getResNo() != 0)) 1130 return; 1131 1132 if (Node->getNumValues() == 1) { 1133 // We can just directly replace this node with the lowered value. 1134 ReplaceNode(SDValue(Node, 0), Res); 1135 return; 1136 } 1137 1138 SmallVector<SDValue, 8> ResultVals; 1139 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) 1140 ResultVals.push_back(Res.getValue(i)); 1141 ReplaceNode(Node, ResultVals.data()); 1142 return; 1143 } 1144 } 1145 // FALL THROUGH 1146 case TargetLowering::Expand: 1147 if (ExpandNode(Node)) 1148 return; 1149 // FALL THROUGH 1150 case TargetLowering::LibCall: 1151 ConvertNodeToLibcall(Node); 1152 return; 1153 case TargetLowering::Promote: 1154 PromoteNode(Node); 1155 return; 1156 } 1157 } 1158 1159 switch (Node->getOpcode()) { 1160 default: 1161 #ifndef NDEBUG 1162 dbgs() << "NODE: "; 1163 Node->dump( &DAG); 1164 dbgs() << "\n"; 1165 #endif 1166 llvm_unreachable("Do not know how to legalize this operator!"); 1167 1168 case ISD::CALLSEQ_START: 1169 case ISD::CALLSEQ_END: 1170 break; 1171 case ISD::LOAD: { 1172 return LegalizeLoadOps(Node); 1173 } 1174 case ISD::STORE: { 1175 return LegalizeStoreOps(Node); 1176 } 1177 } 1178 } 1179 1180 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) { 1181 SDValue Vec = Op.getOperand(0); 1182 SDValue Idx = Op.getOperand(1); 1183 SDLoc dl(Op); 1184 1185 // Before we generate a new store to a temporary stack slot, see if there is 1186 // already one that we can use. There often is because when we scalarize 1187 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole 1188 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in 1189 // the vector. If all are expanded here, we don't want one store per vector 1190 // element. 1191 1192 // Caches for hasPredecessorHelper 1193 SmallPtrSet<const SDNode *, 32> Visited; 1194 SmallVector<const SDNode *, 16> Worklist; 1195 Worklist.push_back(Idx.getNode()); 1196 SDValue StackPtr, Ch; 1197 for (SDNode::use_iterator UI = Vec.getNode()->use_begin(), 1198 UE = Vec.getNode()->use_end(); UI != UE; ++UI) { 1199 SDNode *User = *UI; 1200 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) { 1201 if (ST->isIndexed() || ST->isTruncatingStore() || 1202 ST->getValue() != Vec) 1203 continue; 1204 1205 // Make sure that nothing else could have stored into the destination of 1206 // this store. 1207 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode())) 1208 continue; 1209 1210 // If the index is dependent on the store we will introduce a cycle when 1211 // creating the load (the load uses the index, and by replacing the chain 1212 // we will make the index dependent on the load). 1213 if (SDNode::hasPredecessorHelper(ST, Visited, Worklist)) 1214 continue; 1215 1216 StackPtr = ST->getBasePtr(); 1217 Ch = SDValue(ST, 0); 1218 break; 1219 } 1220 } 1221 1222 if (!Ch.getNode()) { 1223 // Store the value to a temporary stack slot, then LOAD the returned part. 1224 StackPtr = DAG.CreateStackTemporary(Vec.getValueType()); 1225 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, 1226 MachinePointerInfo(), false, false, 0); 1227 } 1228 1229 // Add the offset to the index. 1230 unsigned EltSize = 1231 Vec.getValueType().getVectorElementType().getSizeInBits()/8; 1232 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx, 1233 DAG.getConstant(EltSize, SDLoc(Vec), Idx.getValueType())); 1234 1235 Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy(DAG.getDataLayout())); 1236 StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr); 1237 1238 SDValue NewLoad; 1239 1240 if (Op.getValueType().isVector()) 1241 NewLoad = DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, 1242 MachinePointerInfo(), false, false, false, 0); 1243 else 1244 NewLoad = DAG.getExtLoad( 1245 ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr, MachinePointerInfo(), 1246 Vec.getValueType().getVectorElementType(), false, false, false, 0); 1247 1248 // Replace the chain going out of the store, by the one out of the load. 1249 DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1)); 1250 1251 // We introduced a cycle though, so update the loads operands, making sure 1252 // to use the original store's chain as an incoming chain. 1253 SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(), 1254 NewLoad->op_end()); 1255 NewLoadOperands[0] = Ch; 1256 NewLoad = 1257 SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0); 1258 return NewLoad; 1259 } 1260 1261 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) { 1262 assert(Op.getValueType().isVector() && "Non-vector insert subvector!"); 1263 1264 SDValue Vec = Op.getOperand(0); 1265 SDValue Part = Op.getOperand(1); 1266 SDValue Idx = Op.getOperand(2); 1267 SDLoc dl(Op); 1268 1269 // Store the value to a temporary stack slot, then LOAD the returned part. 1270 1271 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType()); 1272 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 1273 MachinePointerInfo PtrInfo = 1274 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 1275 1276 // First store the whole vector. 1277 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo, 1278 false, false, 0); 1279 1280 // Then store the inserted part. 1281 1282 // Add the offset to the index. 1283 unsigned EltSize = 1284 Vec.getValueType().getVectorElementType().getSizeInBits()/8; 1285 1286 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx, 1287 DAG.getConstant(EltSize, SDLoc(Vec), Idx.getValueType())); 1288 Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy(DAG.getDataLayout())); 1289 1290 SDValue SubStackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, 1291 StackPtr); 1292 1293 // Store the subvector. 1294 Ch = DAG.getStore(Ch, dl, Part, SubStackPtr, 1295 MachinePointerInfo(), false, false, 0); 1296 1297 // Finally, load the updated vector. 1298 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo, 1299 false, false, false, 0); 1300 } 1301 1302 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) { 1303 // We can't handle this case efficiently. Allocate a sufficiently 1304 // aligned object on the stack, store each element into it, then load 1305 // the result as a vector. 1306 // Create the stack frame object. 1307 EVT VT = Node->getValueType(0); 1308 EVT EltVT = VT.getVectorElementType(); 1309 SDLoc dl(Node); 1310 SDValue FIPtr = DAG.CreateStackTemporary(VT); 1311 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex(); 1312 MachinePointerInfo PtrInfo = 1313 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 1314 1315 // Emit a store of each element to the stack slot. 1316 SmallVector<SDValue, 8> Stores; 1317 unsigned TypeByteSize = EltVT.getSizeInBits() / 8; 1318 // Store (in the right endianness) the elements to memory. 1319 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) { 1320 // Ignore undef elements. 1321 if (Node->getOperand(i).isUndef()) continue; 1322 1323 unsigned Offset = TypeByteSize*i; 1324 1325 SDValue Idx = DAG.getConstant(Offset, dl, FIPtr.getValueType()); 1326 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx); 1327 1328 // If the destination vector element type is narrower than the source 1329 // element type, only store the bits necessary. 1330 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) { 1331 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl, 1332 Node->getOperand(i), Idx, 1333 PtrInfo.getWithOffset(Offset), 1334 EltVT, false, false, 0)); 1335 } else 1336 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, 1337 Node->getOperand(i), Idx, 1338 PtrInfo.getWithOffset(Offset), 1339 false, false, 0)); 1340 } 1341 1342 SDValue StoreChain; 1343 if (!Stores.empty()) // Not all undef elements? 1344 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 1345 else 1346 StoreChain = DAG.getEntryNode(); 1347 1348 // Result is a load from the stack slot. 1349 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo, 1350 false, false, false, 0); 1351 } 1352 1353 namespace { 1354 /// Keeps track of state when getting the sign of a floating-point value as an 1355 /// integer. 1356 struct FloatSignAsInt { 1357 EVT FloatVT; 1358 SDValue Chain; 1359 SDValue FloatPtr; 1360 SDValue IntPtr; 1361 MachinePointerInfo IntPointerInfo; 1362 MachinePointerInfo FloatPointerInfo; 1363 SDValue IntValue; 1364 APInt SignMask; 1365 uint8_t SignBit; 1366 }; 1367 } 1368 1369 /// Bitcast a floating-point value to an integer value. Only bitcast the part 1370 /// containing the sign bit if the target has no integer value capable of 1371 /// holding all bits of the floating-point value. 1372 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State, 1373 const SDLoc &DL, 1374 SDValue Value) const { 1375 EVT FloatVT = Value.getValueType(); 1376 unsigned NumBits = FloatVT.getSizeInBits(); 1377 State.FloatVT = FloatVT; 1378 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 1379 // Convert to an integer of the same size. 1380 if (TLI.isTypeLegal(IVT)) { 1381 State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value); 1382 State.SignMask = APInt::getSignBit(NumBits); 1383 State.SignBit = NumBits - 1; 1384 return; 1385 } 1386 1387 auto &DataLayout = DAG.getDataLayout(); 1388 // Store the float to memory, then load the sign part out as an integer. 1389 MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8); 1390 // First create a temporary that is aligned for both the load and store. 1391 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy); 1392 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 1393 // Then store the float to it. 1394 State.FloatPtr = StackPtr; 1395 MachineFunction &MF = DAG.getMachineFunction(); 1396 State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI); 1397 State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr, 1398 State.FloatPointerInfo, false, false, 0); 1399 1400 SDValue IntPtr; 1401 if (DataLayout.isBigEndian()) { 1402 assert(FloatVT.isByteSized() && "Unsupported floating point type!"); 1403 // Load out a legal integer with the same sign bit as the float. 1404 IntPtr = StackPtr; 1405 State.IntPointerInfo = State.FloatPointerInfo; 1406 } else { 1407 // Advance the pointer so that the loaded byte will contain the sign bit. 1408 unsigned ByteOffset = (FloatVT.getSizeInBits() / 8) - 1; 1409 IntPtr = DAG.getNode(ISD::ADD, DL, StackPtr.getValueType(), StackPtr, 1410 DAG.getConstant(ByteOffset, DL, StackPtr.getValueType())); 1411 State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI, 1412 ByteOffset); 1413 } 1414 1415 State.IntPtr = IntPtr; 1416 State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, 1417 IntPtr, State.IntPointerInfo, MVT::i8, 1418 false, false, false, 0); 1419 State.SignMask = APInt::getOneBitSet(LoadTy.getSizeInBits(), 7); 1420 State.SignBit = 7; 1421 } 1422 1423 /// Replace the integer value produced by getSignAsIntValue() with a new value 1424 /// and cast the result back to a floating-point type. 1425 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State, 1426 const SDLoc &DL, 1427 SDValue NewIntValue) const { 1428 if (!State.Chain) 1429 return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue); 1430 1431 // Override the part containing the sign bit in the value stored on the stack. 1432 SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr, 1433 State.IntPointerInfo, MVT::i8, false, false, 1434 0); 1435 return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr, 1436 State.FloatPointerInfo, false, false, false, 0); 1437 } 1438 1439 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const { 1440 SDLoc DL(Node); 1441 SDValue Mag = Node->getOperand(0); 1442 SDValue Sign = Node->getOperand(1); 1443 1444 // Get sign bit into an integer value. 1445 FloatSignAsInt SignAsInt; 1446 getSignAsIntValue(SignAsInt, DL, Sign); 1447 1448 EVT IntVT = SignAsInt.IntValue.getValueType(); 1449 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT); 1450 SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue, 1451 SignMask); 1452 1453 // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X) 1454 EVT FloatVT = Mag.getValueType(); 1455 if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) && 1456 TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) { 1457 SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag); 1458 SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue); 1459 SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit, 1460 DAG.getConstant(0, DL, IntVT), ISD::SETNE); 1461 return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue); 1462 } 1463 1464 // Transform Mag value to integer, and clear the sign bit. 1465 FloatSignAsInt MagAsInt; 1466 getSignAsIntValue(MagAsInt, DL, Mag); 1467 EVT MagVT = MagAsInt.IntValue.getValueType(); 1468 SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT); 1469 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue, 1470 ClearSignMask); 1471 1472 // Get the signbit at the right position for MagAsInt. 1473 int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit; 1474 if (SignBit.getValueSizeInBits() > ClearedSign.getValueSizeInBits()) { 1475 if (ShiftAmount > 0) { 1476 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, IntVT); 1477 SignBit = DAG.getNode(ISD::SRL, DL, IntVT, SignBit, ShiftCnst); 1478 } else if (ShiftAmount < 0) { 1479 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, IntVT); 1480 SignBit = DAG.getNode(ISD::SHL, DL, IntVT, SignBit, ShiftCnst); 1481 } 1482 SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit); 1483 } else if (SignBit.getValueSizeInBits() < ClearedSign.getValueSizeInBits()) { 1484 SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit); 1485 if (ShiftAmount > 0) { 1486 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, MagVT); 1487 SignBit = DAG.getNode(ISD::SRL, DL, MagVT, SignBit, ShiftCnst); 1488 } else if (ShiftAmount < 0) { 1489 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, MagVT); 1490 SignBit = DAG.getNode(ISD::SHL, DL, MagVT, SignBit, ShiftCnst); 1491 } 1492 } 1493 1494 // Store the part with the modified sign and convert back to float. 1495 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit); 1496 return modifySignAsInt(MagAsInt, DL, CopiedSign); 1497 } 1498 1499 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const { 1500 SDLoc DL(Node); 1501 SDValue Value = Node->getOperand(0); 1502 1503 // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal. 1504 EVT FloatVT = Value.getValueType(); 1505 if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) { 1506 SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT); 1507 return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero); 1508 } 1509 1510 // Transform value to integer, clear the sign bit and transform back. 1511 FloatSignAsInt ValueAsInt; 1512 getSignAsIntValue(ValueAsInt, DL, Value); 1513 EVT IntVT = ValueAsInt.IntValue.getValueType(); 1514 SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT); 1515 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue, 1516 ClearSignMask); 1517 return modifySignAsInt(ValueAsInt, DL, ClearedSign); 1518 } 1519 1520 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node, 1521 SmallVectorImpl<SDValue> &Results) { 1522 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore(); 1523 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and" 1524 " not tell us which reg is the stack pointer!"); 1525 SDLoc dl(Node); 1526 EVT VT = Node->getValueType(0); 1527 SDValue Tmp1 = SDValue(Node, 0); 1528 SDValue Tmp2 = SDValue(Node, 1); 1529 SDValue Tmp3 = Node->getOperand(2); 1530 SDValue Chain = Tmp1.getOperand(0); 1531 1532 // Chain the dynamic stack allocation so that it doesn't modify the stack 1533 // pointer when other instructions are using the stack. 1534 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl); 1535 1536 SDValue Size = Tmp2.getOperand(1); 1537 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 1538 Chain = SP.getValue(1); 1539 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue(); 1540 unsigned StackAlign = 1541 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 1542 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value 1543 if (Align > StackAlign) 1544 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 1545 DAG.getConstant(-(uint64_t)Align, dl, VT)); 1546 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 1547 1548 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 1549 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 1550 1551 Results.push_back(Tmp1); 1552 Results.push_back(Tmp2); 1553 } 1554 1555 /// Legalize a SETCC with given LHS and RHS and condition code CC on the current 1556 /// target. 1557 /// 1558 /// If the SETCC has been legalized using AND / OR, then the legalized node 1559 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert 1560 /// will be set to false. 1561 /// 1562 /// If the SETCC has been legalized by using getSetCCSwappedOperands(), 1563 /// then the values of LHS and RHS will be swapped, CC will be set to the 1564 /// new condition, and NeedInvert will be set to false. 1565 /// 1566 /// If the SETCC has been legalized using the inverse condcode, then LHS and 1567 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert 1568 /// will be set to true. The caller must invert the result of the SETCC with 1569 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect 1570 /// of a true/false result. 1571 /// 1572 /// \returns true if the SetCC has been legalized, false if it hasn't. 1573 bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT, SDValue &LHS, 1574 SDValue &RHS, SDValue &CC, 1575 bool &NeedInvert, 1576 const SDLoc &dl) { 1577 MVT OpVT = LHS.getSimpleValueType(); 1578 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 1579 NeedInvert = false; 1580 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 1581 default: llvm_unreachable("Unknown condition code action!"); 1582 case TargetLowering::Legal: 1583 // Nothing to do. 1584 break; 1585 case TargetLowering::Expand: { 1586 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 1587 if (TLI.isCondCodeLegal(InvCC, OpVT)) { 1588 std::swap(LHS, RHS); 1589 CC = DAG.getCondCode(InvCC); 1590 return true; 1591 } 1592 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 1593 unsigned Opc = 0; 1594 switch (CCCode) { 1595 default: llvm_unreachable("Don't know how to expand this condition!"); 1596 case ISD::SETO: 1597 assert(TLI.getCondCodeAction(ISD::SETOEQ, OpVT) 1598 == TargetLowering::Legal 1599 && "If SETO is expanded, SETOEQ must be legal!"); 1600 CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break; 1601 case ISD::SETUO: 1602 assert(TLI.getCondCodeAction(ISD::SETUNE, OpVT) 1603 == TargetLowering::Legal 1604 && "If SETUO is expanded, SETUNE must be legal!"); 1605 CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break; 1606 case ISD::SETOEQ: 1607 case ISD::SETOGT: 1608 case ISD::SETOGE: 1609 case ISD::SETOLT: 1610 case ISD::SETOLE: 1611 case ISD::SETONE: 1612 case ISD::SETUEQ: 1613 case ISD::SETUNE: 1614 case ISD::SETUGT: 1615 case ISD::SETUGE: 1616 case ISD::SETULT: 1617 case ISD::SETULE: 1618 // If we are floating point, assign and break, otherwise fall through. 1619 if (!OpVT.isInteger()) { 1620 // We can use the 4th bit to tell if we are the unordered 1621 // or ordered version of the opcode. 1622 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 1623 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 1624 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 1625 break; 1626 } 1627 // Fallthrough if we are unsigned integer. 1628 case ISD::SETLE: 1629 case ISD::SETGT: 1630 case ISD::SETGE: 1631 case ISD::SETLT: 1632 // We only support using the inverted operation, which is computed above 1633 // and not a different manner of supporting expanding these cases. 1634 llvm_unreachable("Don't know how to expand this condition!"); 1635 case ISD::SETNE: 1636 case ISD::SETEQ: 1637 // Try inverting the result of the inverse condition. 1638 InvCC = CCCode == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ; 1639 if (TLI.isCondCodeLegal(InvCC, OpVT)) { 1640 CC = DAG.getCondCode(InvCC); 1641 NeedInvert = true; 1642 return true; 1643 } 1644 // If inverting the condition didn't work then we have no means to expand 1645 // the condition. 1646 llvm_unreachable("Don't know how to expand this condition!"); 1647 } 1648 1649 SDValue SetCC1, SetCC2; 1650 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 1651 // If we aren't the ordered or unorder operation, 1652 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 1653 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1); 1654 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2); 1655 } else { 1656 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 1657 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1); 1658 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2); 1659 } 1660 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 1661 RHS = SDValue(); 1662 CC = SDValue(); 1663 return true; 1664 } 1665 } 1666 return false; 1667 } 1668 1669 /// Emit a store/load combination to the stack. This stores 1670 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does 1671 /// a load from the stack slot to DestVT, extending it if needed. 1672 /// The resultant code need not be legal. 1673 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT, 1674 EVT DestVT, const SDLoc &dl) { 1675 // Create the stack frame object. 1676 unsigned SrcAlign = DAG.getDataLayout().getPrefTypeAlignment( 1677 SrcOp.getValueType().getTypeForEVT(*DAG.getContext())); 1678 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign); 1679 1680 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr); 1681 int SPFI = StackPtrFI->getIndex(); 1682 MachinePointerInfo PtrInfo = 1683 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 1684 1685 unsigned SrcSize = SrcOp.getValueType().getSizeInBits(); 1686 unsigned SlotSize = SlotVT.getSizeInBits(); 1687 unsigned DestSize = DestVT.getSizeInBits(); 1688 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext()); 1689 unsigned DestAlign = DAG.getDataLayout().getPrefTypeAlignment(DestType); 1690 1691 // Emit a store to the stack slot. Use a truncstore if the input value is 1692 // later than DestVT. 1693 SDValue Store; 1694 1695 if (SrcSize > SlotSize) 1696 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr, 1697 PtrInfo, SlotVT, false, false, SrcAlign); 1698 else { 1699 assert(SrcSize == SlotSize && "Invalid store"); 1700 Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr, 1701 PtrInfo, false, false, SrcAlign); 1702 } 1703 1704 // Result is a load from the stack slot. 1705 if (SlotSize == DestSize) 1706 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, 1707 false, false, false, DestAlign); 1708 1709 assert(SlotSize < DestSize && "Unknown extension!"); 1710 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, 1711 PtrInfo, SlotVT, false, false, false, DestAlign); 1712 } 1713 1714 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) { 1715 SDLoc dl(Node); 1716 // Create a vector sized/aligned stack slot, store the value to element #0, 1717 // then load the whole vector back out. 1718 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0)); 1719 1720 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr); 1721 int SPFI = StackPtrFI->getIndex(); 1722 1723 SDValue Ch = DAG.getTruncStore( 1724 DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr, 1725 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI), 1726 Node->getValueType(0).getVectorElementType(), false, false, 0); 1727 return DAG.getLoad( 1728 Node->getValueType(0), dl, Ch, StackPtr, 1729 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI), false, 1730 false, false, 0); 1731 } 1732 1733 static bool 1734 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG, 1735 const TargetLowering &TLI, SDValue &Res) { 1736 unsigned NumElems = Node->getNumOperands(); 1737 SDLoc dl(Node); 1738 EVT VT = Node->getValueType(0); 1739 1740 // Try to group the scalars into pairs, shuffle the pairs together, then 1741 // shuffle the pairs of pairs together, etc. until the vector has 1742 // been built. This will work only if all of the necessary shuffle masks 1743 // are legal. 1744 1745 // We do this in two phases; first to check the legality of the shuffles, 1746 // and next, assuming that all shuffles are legal, to create the new nodes. 1747 for (int Phase = 0; Phase < 2; ++Phase) { 1748 SmallVector<std::pair<SDValue, SmallVector<int, 16> >, 16> IntermedVals, 1749 NewIntermedVals; 1750 for (unsigned i = 0; i < NumElems; ++i) { 1751 SDValue V = Node->getOperand(i); 1752 if (V.isUndef()) 1753 continue; 1754 1755 SDValue Vec; 1756 if (Phase) 1757 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V); 1758 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i))); 1759 } 1760 1761 while (IntermedVals.size() > 2) { 1762 NewIntermedVals.clear(); 1763 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) { 1764 // This vector and the next vector are shuffled together (simply to 1765 // append the one to the other). 1766 SmallVector<int, 16> ShuffleVec(NumElems, -1); 1767 1768 SmallVector<int, 16> FinalIndices; 1769 FinalIndices.reserve(IntermedVals[i].second.size() + 1770 IntermedVals[i+1].second.size()); 1771 1772 int k = 0; 1773 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f; 1774 ++j, ++k) { 1775 ShuffleVec[k] = j; 1776 FinalIndices.push_back(IntermedVals[i].second[j]); 1777 } 1778 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f; 1779 ++j, ++k) { 1780 ShuffleVec[k] = NumElems + j; 1781 FinalIndices.push_back(IntermedVals[i+1].second[j]); 1782 } 1783 1784 SDValue Shuffle; 1785 if (Phase) 1786 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first, 1787 IntermedVals[i+1].first, 1788 ShuffleVec.data()); 1789 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT)) 1790 return false; 1791 NewIntermedVals.push_back( 1792 std::make_pair(Shuffle, std::move(FinalIndices))); 1793 } 1794 1795 // If we had an odd number of defined values, then append the last 1796 // element to the array of new vectors. 1797 if ((IntermedVals.size() & 1) != 0) 1798 NewIntermedVals.push_back(IntermedVals.back()); 1799 1800 IntermedVals.swap(NewIntermedVals); 1801 } 1802 1803 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 && 1804 "Invalid number of intermediate vectors"); 1805 SDValue Vec1 = IntermedVals[0].first; 1806 SDValue Vec2; 1807 if (IntermedVals.size() > 1) 1808 Vec2 = IntermedVals[1].first; 1809 else if (Phase) 1810 Vec2 = DAG.getUNDEF(VT); 1811 1812 SmallVector<int, 16> ShuffleVec(NumElems, -1); 1813 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i) 1814 ShuffleVec[IntermedVals[0].second[i]] = i; 1815 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i) 1816 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i; 1817 1818 if (Phase) 1819 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data()); 1820 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT)) 1821 return false; 1822 } 1823 1824 return true; 1825 } 1826 1827 /// Expand a BUILD_VECTOR node on targets that don't 1828 /// support the operation, but do support the resultant vector type. 1829 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) { 1830 unsigned NumElems = Node->getNumOperands(); 1831 SDValue Value1, Value2; 1832 SDLoc dl(Node); 1833 EVT VT = Node->getValueType(0); 1834 EVT OpVT = Node->getOperand(0).getValueType(); 1835 EVT EltVT = VT.getVectorElementType(); 1836 1837 // If the only non-undef value is the low element, turn this into a 1838 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X. 1839 bool isOnlyLowElement = true; 1840 bool MoreThanTwoValues = false; 1841 bool isConstant = true; 1842 for (unsigned i = 0; i < NumElems; ++i) { 1843 SDValue V = Node->getOperand(i); 1844 if (V.isUndef()) 1845 continue; 1846 if (i > 0) 1847 isOnlyLowElement = false; 1848 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 1849 isConstant = false; 1850 1851 if (!Value1.getNode()) { 1852 Value1 = V; 1853 } else if (!Value2.getNode()) { 1854 if (V != Value1) 1855 Value2 = V; 1856 } else if (V != Value1 && V != Value2) { 1857 MoreThanTwoValues = true; 1858 } 1859 } 1860 1861 if (!Value1.getNode()) 1862 return DAG.getUNDEF(VT); 1863 1864 if (isOnlyLowElement) 1865 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0)); 1866 1867 // If all elements are constants, create a load from the constant pool. 1868 if (isConstant) { 1869 SmallVector<Constant*, 16> CV; 1870 for (unsigned i = 0, e = NumElems; i != e; ++i) { 1871 if (ConstantFPSDNode *V = 1872 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) { 1873 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue())); 1874 } else if (ConstantSDNode *V = 1875 dyn_cast<ConstantSDNode>(Node->getOperand(i))) { 1876 if (OpVT==EltVT) 1877 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue())); 1878 else { 1879 // If OpVT and EltVT don't match, EltVT is not legal and the 1880 // element values have been promoted/truncated earlier. Undo this; 1881 // we don't want a v16i8 to become a v16i32 for example. 1882 const ConstantInt *CI = V->getConstantIntValue(); 1883 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()), 1884 CI->getZExtValue())); 1885 } 1886 } else { 1887 assert(Node->getOperand(i).isUndef()); 1888 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext()); 1889 CV.push_back(UndefValue::get(OpNTy)); 1890 } 1891 } 1892 Constant *CP = ConstantVector::get(CV); 1893 SDValue CPIdx = 1894 DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout())); 1895 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 1896 return DAG.getLoad( 1897 VT, dl, DAG.getEntryNode(), CPIdx, 1898 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 1899 false, false, Alignment); 1900 } 1901 1902 SmallSet<SDValue, 16> DefinedValues; 1903 for (unsigned i = 0; i < NumElems; ++i) { 1904 if (Node->getOperand(i).isUndef()) 1905 continue; 1906 DefinedValues.insert(Node->getOperand(i)); 1907 } 1908 1909 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) { 1910 if (!MoreThanTwoValues) { 1911 SmallVector<int, 8> ShuffleVec(NumElems, -1); 1912 for (unsigned i = 0; i < NumElems; ++i) { 1913 SDValue V = Node->getOperand(i); 1914 if (V.isUndef()) 1915 continue; 1916 ShuffleVec[i] = V == Value1 ? 0 : NumElems; 1917 } 1918 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) { 1919 // Get the splatted value into the low element of a vector register. 1920 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1); 1921 SDValue Vec2; 1922 if (Value2.getNode()) 1923 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2); 1924 else 1925 Vec2 = DAG.getUNDEF(VT); 1926 1927 // Return shuffle(LowValVec, undef, <0,0,0,0>) 1928 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data()); 1929 } 1930 } else { 1931 SDValue Res; 1932 if (ExpandBVWithShuffles(Node, DAG, TLI, Res)) 1933 return Res; 1934 } 1935 } 1936 1937 // Otherwise, we can't handle this case efficiently. 1938 return ExpandVectorBuildThroughStack(Node); 1939 } 1940 1941 // Expand a node into a call to a libcall. If the result value 1942 // does not fit into a register, return the lo part and set the hi part to the 1943 // by-reg argument. If it does fit into a single register, return the result 1944 // and leave the Hi part unset. 1945 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, 1946 bool isSigned) { 1947 TargetLowering::ArgListTy Args; 1948 TargetLowering::ArgListEntry Entry; 1949 for (const SDValue &Op : Node->op_values()) { 1950 EVT ArgVT = Op.getValueType(); 1951 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 1952 Entry.Node = Op; 1953 Entry.Ty = ArgTy; 1954 Entry.isSExt = isSigned; 1955 Entry.isZExt = !isSigned; 1956 Args.push_back(Entry); 1957 } 1958 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 1959 TLI.getPointerTy(DAG.getDataLayout())); 1960 1961 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext()); 1962 1963 // By default, the input chain to this libcall is the entry node of the 1964 // function. If the libcall is going to be emitted as a tail call then 1965 // TLI.isUsedByReturnOnly will change it to the right chain if the return 1966 // node which is being folded has a non-entry input chain. 1967 SDValue InChain = DAG.getEntryNode(); 1968 1969 // isTailCall may be true since the callee does not reference caller stack 1970 // frame. Check if it's in the right position and that the return types match. 1971 SDValue TCChain = InChain; 1972 const Function *F = DAG.getMachineFunction().getFunction(); 1973 bool isTailCall = 1974 TLI.isInTailCallPosition(DAG, Node, TCChain) && 1975 (RetTy == F->getReturnType() || F->getReturnType()->isVoidTy()); 1976 if (isTailCall) 1977 InChain = TCChain; 1978 1979 TargetLowering::CallLoweringInfo CLI(DAG); 1980 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain) 1981 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 1982 .setTailCall(isTailCall).setSExtResult(isSigned).setZExtResult(!isSigned); 1983 1984 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 1985 1986 if (!CallInfo.second.getNode()) 1987 // It's a tailcall, return the chain (which is the DAG root). 1988 return DAG.getRoot(); 1989 1990 return CallInfo.first; 1991 } 1992 1993 /// Generate a libcall taking the given operands as arguments 1994 /// and returning a result of type RetVT. 1995 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, 1996 const SDValue *Ops, unsigned NumOps, 1997 bool isSigned, const SDLoc &dl) { 1998 TargetLowering::ArgListTy Args; 1999 Args.reserve(NumOps); 2000 2001 TargetLowering::ArgListEntry Entry; 2002 for (unsigned i = 0; i != NumOps; ++i) { 2003 Entry.Node = Ops[i]; 2004 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 2005 Entry.isSExt = isSigned; 2006 Entry.isZExt = !isSigned; 2007 Args.push_back(Entry); 2008 } 2009 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2010 TLI.getPointerTy(DAG.getDataLayout())); 2011 2012 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2013 2014 TargetLowering::CallLoweringInfo CLI(DAG); 2015 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()) 2016 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 2017 .setSExtResult(isSigned).setZExtResult(!isSigned); 2018 2019 std::pair<SDValue,SDValue> CallInfo = TLI.LowerCallTo(CLI); 2020 2021 return CallInfo.first; 2022 } 2023 2024 // Expand a node into a call to a libcall. Similar to 2025 // ExpandLibCall except that the first operand is the in-chain. 2026 std::pair<SDValue, SDValue> 2027 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC, 2028 SDNode *Node, 2029 bool isSigned) { 2030 SDValue InChain = Node->getOperand(0); 2031 2032 TargetLowering::ArgListTy Args; 2033 TargetLowering::ArgListEntry Entry; 2034 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) { 2035 EVT ArgVT = Node->getOperand(i).getValueType(); 2036 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2037 Entry.Node = Node->getOperand(i); 2038 Entry.Ty = ArgTy; 2039 Entry.isSExt = isSigned; 2040 Entry.isZExt = !isSigned; 2041 Args.push_back(Entry); 2042 } 2043 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2044 TLI.getPointerTy(DAG.getDataLayout())); 2045 2046 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext()); 2047 2048 TargetLowering::CallLoweringInfo CLI(DAG); 2049 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain) 2050 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 2051 .setSExtResult(isSigned).setZExtResult(!isSigned); 2052 2053 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2054 2055 return CallInfo; 2056 } 2057 2058 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node, 2059 RTLIB::Libcall Call_F32, 2060 RTLIB::Libcall Call_F64, 2061 RTLIB::Libcall Call_F80, 2062 RTLIB::Libcall Call_F128, 2063 RTLIB::Libcall Call_PPCF128) { 2064 RTLIB::Libcall LC; 2065 switch (Node->getSimpleValueType(0).SimpleTy) { 2066 default: llvm_unreachable("Unexpected request for libcall!"); 2067 case MVT::f32: LC = Call_F32; break; 2068 case MVT::f64: LC = Call_F64; break; 2069 case MVT::f80: LC = Call_F80; break; 2070 case MVT::f128: LC = Call_F128; break; 2071 case MVT::ppcf128: LC = Call_PPCF128; break; 2072 } 2073 return ExpandLibCall(LC, Node, false); 2074 } 2075 2076 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned, 2077 RTLIB::Libcall Call_I8, 2078 RTLIB::Libcall Call_I16, 2079 RTLIB::Libcall Call_I32, 2080 RTLIB::Libcall Call_I64, 2081 RTLIB::Libcall Call_I128) { 2082 RTLIB::Libcall LC; 2083 switch (Node->getSimpleValueType(0).SimpleTy) { 2084 default: llvm_unreachable("Unexpected request for libcall!"); 2085 case MVT::i8: LC = Call_I8; break; 2086 case MVT::i16: LC = Call_I16; break; 2087 case MVT::i32: LC = Call_I32; break; 2088 case MVT::i64: LC = Call_I64; break; 2089 case MVT::i128: LC = Call_I128; break; 2090 } 2091 return ExpandLibCall(LC, Node, isSigned); 2092 } 2093 2094 /// Issue libcalls to __{u}divmod to compute div / rem pairs. 2095 void 2096 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node, 2097 SmallVectorImpl<SDValue> &Results) { 2098 unsigned Opcode = Node->getOpcode(); 2099 bool isSigned = Opcode == ISD::SDIVREM; 2100 2101 RTLIB::Libcall LC; 2102 switch (Node->getSimpleValueType(0).SimpleTy) { 2103 default: llvm_unreachable("Unexpected request for libcall!"); 2104 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2105 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2106 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2107 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2108 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2109 } 2110 2111 // The input chain to this libcall is the entry node of the function. 2112 // Legalizing the call will automatically add the previous call to the 2113 // dependence. 2114 SDValue InChain = DAG.getEntryNode(); 2115 2116 EVT RetVT = Node->getValueType(0); 2117 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2118 2119 TargetLowering::ArgListTy Args; 2120 TargetLowering::ArgListEntry Entry; 2121 for (const SDValue &Op : Node->op_values()) { 2122 EVT ArgVT = Op.getValueType(); 2123 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2124 Entry.Node = Op; 2125 Entry.Ty = ArgTy; 2126 Entry.isSExt = isSigned; 2127 Entry.isZExt = !isSigned; 2128 Args.push_back(Entry); 2129 } 2130 2131 // Also pass the return address of the remainder. 2132 SDValue FIPtr = DAG.CreateStackTemporary(RetVT); 2133 Entry.Node = FIPtr; 2134 Entry.Ty = RetTy->getPointerTo(); 2135 Entry.isSExt = isSigned; 2136 Entry.isZExt = !isSigned; 2137 Args.push_back(Entry); 2138 2139 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2140 TLI.getPointerTy(DAG.getDataLayout())); 2141 2142 SDLoc dl(Node); 2143 TargetLowering::CallLoweringInfo CLI(DAG); 2144 CLI.setDebugLoc(dl).setChain(InChain) 2145 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 2146 .setSExtResult(isSigned).setZExtResult(!isSigned); 2147 2148 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2149 2150 // Remainder is loaded back from the stack frame. 2151 SDValue Rem = DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, 2152 MachinePointerInfo(), false, false, false, 0); 2153 Results.push_back(CallInfo.first); 2154 Results.push_back(Rem); 2155 } 2156 2157 /// Return true if sincos libcall is available. 2158 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) { 2159 RTLIB::Libcall LC; 2160 switch (Node->getSimpleValueType(0).SimpleTy) { 2161 default: llvm_unreachable("Unexpected request for libcall!"); 2162 case MVT::f32: LC = RTLIB::SINCOS_F32; break; 2163 case MVT::f64: LC = RTLIB::SINCOS_F64; break; 2164 case MVT::f80: LC = RTLIB::SINCOS_F80; break; 2165 case MVT::f128: LC = RTLIB::SINCOS_F128; break; 2166 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; 2167 } 2168 return TLI.getLibcallName(LC) != nullptr; 2169 } 2170 2171 /// Return true if sincos libcall is available and can be used to combine sin 2172 /// and cos. 2173 static bool canCombineSinCosLibcall(SDNode *Node, const TargetLowering &TLI, 2174 const TargetMachine &TM) { 2175 if (!isSinCosLibcallAvailable(Node, TLI)) 2176 return false; 2177 // GNU sin/cos functions set errno while sincos does not. Therefore 2178 // combining sin and cos is only safe if unsafe-fpmath is enabled. 2179 bool isGNU = Triple(TM.getTargetTriple()).getEnvironment() == Triple::GNU; 2180 if (isGNU && !TM.Options.UnsafeFPMath) 2181 return false; 2182 return true; 2183 } 2184 2185 /// Only issue sincos libcall if both sin and cos are needed. 2186 static bool useSinCos(SDNode *Node) { 2187 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN 2188 ? ISD::FCOS : ISD::FSIN; 2189 2190 SDValue Op0 = Node->getOperand(0); 2191 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2192 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2193 SDNode *User = *UI; 2194 if (User == Node) 2195 continue; 2196 // The other user might have been turned into sincos already. 2197 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS) 2198 return true; 2199 } 2200 return false; 2201 } 2202 2203 /// Issue libcalls to sincos to compute sin / cos pairs. 2204 void 2205 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node, 2206 SmallVectorImpl<SDValue> &Results) { 2207 RTLIB::Libcall LC; 2208 switch (Node->getSimpleValueType(0).SimpleTy) { 2209 default: llvm_unreachable("Unexpected request for libcall!"); 2210 case MVT::f32: LC = RTLIB::SINCOS_F32; break; 2211 case MVT::f64: LC = RTLIB::SINCOS_F64; break; 2212 case MVT::f80: LC = RTLIB::SINCOS_F80; break; 2213 case MVT::f128: LC = RTLIB::SINCOS_F128; break; 2214 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; 2215 } 2216 2217 // The input chain to this libcall is the entry node of the function. 2218 // Legalizing the call will automatically add the previous call to the 2219 // dependence. 2220 SDValue InChain = DAG.getEntryNode(); 2221 2222 EVT RetVT = Node->getValueType(0); 2223 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2224 2225 TargetLowering::ArgListTy Args; 2226 TargetLowering::ArgListEntry Entry; 2227 2228 // Pass the argument. 2229 Entry.Node = Node->getOperand(0); 2230 Entry.Ty = RetTy; 2231 Entry.isSExt = false; 2232 Entry.isZExt = false; 2233 Args.push_back(Entry); 2234 2235 // Pass the return address of sin. 2236 SDValue SinPtr = DAG.CreateStackTemporary(RetVT); 2237 Entry.Node = SinPtr; 2238 Entry.Ty = RetTy->getPointerTo(); 2239 Entry.isSExt = false; 2240 Entry.isZExt = false; 2241 Args.push_back(Entry); 2242 2243 // Also pass the return address of the cos. 2244 SDValue CosPtr = DAG.CreateStackTemporary(RetVT); 2245 Entry.Node = CosPtr; 2246 Entry.Ty = RetTy->getPointerTo(); 2247 Entry.isSExt = false; 2248 Entry.isZExt = false; 2249 Args.push_back(Entry); 2250 2251 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2252 TLI.getPointerTy(DAG.getDataLayout())); 2253 2254 SDLoc dl(Node); 2255 TargetLowering::CallLoweringInfo CLI(DAG); 2256 CLI.setDebugLoc(dl).setChain(InChain) 2257 .setCallee(TLI.getLibcallCallingConv(LC), 2258 Type::getVoidTy(*DAG.getContext()), Callee, std::move(Args), 0); 2259 2260 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2261 2262 Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, 2263 MachinePointerInfo(), false, false, false, 0)); 2264 Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, 2265 MachinePointerInfo(), false, false, false, 0)); 2266 } 2267 2268 /// This function is responsible for legalizing a 2269 /// INT_TO_FP operation of the specified operand when the target requests that 2270 /// we expand it. At this point, we know that the result and operand types are 2271 /// legal for the target. 2272 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned, SDValue Op0, 2273 EVT DestVT, 2274 const SDLoc &dl) { 2275 // TODO: Should any fast-math-flags be set for the created nodes? 2276 2277 if (Op0.getValueType() == MVT::i32 && TLI.isTypeLegal(MVT::f64)) { 2278 // simple 32-bit [signed|unsigned] integer to float/double expansion 2279 2280 // Get the stack frame index of a 8 byte buffer. 2281 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64); 2282 2283 // word offset constant for Hi/Lo address computation 2284 SDValue WordOff = DAG.getConstant(sizeof(int), dl, 2285 StackSlot.getValueType()); 2286 // set up Hi and Lo (into buffer) address based on endian 2287 SDValue Hi = StackSlot; 2288 SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(), 2289 StackSlot, WordOff); 2290 if (DAG.getDataLayout().isLittleEndian()) 2291 std::swap(Hi, Lo); 2292 2293 // if signed map to unsigned space 2294 SDValue Op0Mapped; 2295 if (isSigned) { 2296 // constant used to invert sign bit (signed to unsigned mapping) 2297 SDValue SignBit = DAG.getConstant(0x80000000u, dl, MVT::i32); 2298 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit); 2299 } else { 2300 Op0Mapped = Op0; 2301 } 2302 // store the lo of the constructed double - based on integer input 2303 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, 2304 Op0Mapped, Lo, MachinePointerInfo(), 2305 false, false, 0); 2306 // initial hi portion of constructed double 2307 SDValue InitialHi = DAG.getConstant(0x43300000u, dl, MVT::i32); 2308 // store the hi of the constructed double - biased exponent 2309 SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi, 2310 MachinePointerInfo(), 2311 false, false, 0); 2312 // load the constructed double 2313 SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot, 2314 MachinePointerInfo(), false, false, false, 0); 2315 // FP constant to bias correct the final result 2316 SDValue Bias = DAG.getConstantFP(isSigned ? 2317 BitsToDouble(0x4330000080000000ULL) : 2318 BitsToDouble(0x4330000000000000ULL), 2319 dl, MVT::f64); 2320 // subtract the bias 2321 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias); 2322 // final result 2323 SDValue Result; 2324 // handle final rounding 2325 if (DestVT == MVT::f64) { 2326 // do nothing 2327 Result = Sub; 2328 } else if (DestVT.bitsLT(MVT::f64)) { 2329 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 2330 DAG.getIntPtrConstant(0, dl)); 2331 } else if (DestVT.bitsGT(MVT::f64)) { 2332 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 2333 } 2334 return Result; 2335 } 2336 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet"); 2337 // Code below here assumes !isSigned without checking again. 2338 2339 // Implementation of unsigned i64 to f64 following the algorithm in 2340 // __floatundidf in compiler_rt. This implementation has the advantage 2341 // of performing rounding correctly, both in the default rounding mode 2342 // and in all alternate rounding modes. 2343 // TODO: Generalize this for use with other types. 2344 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) { 2345 SDValue TwoP52 = 2346 DAG.getConstant(UINT64_C(0x4330000000000000), dl, MVT::i64); 2347 SDValue TwoP84PlusTwoP52 = 2348 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), dl, 2349 MVT::f64); 2350 SDValue TwoP84 = 2351 DAG.getConstant(UINT64_C(0x4530000000000000), dl, MVT::i64); 2352 2353 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32); 2354 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, 2355 DAG.getConstant(32, dl, MVT::i64)); 2356 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52); 2357 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84); 2358 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr); 2359 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr); 2360 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt, 2361 TwoP84PlusTwoP52); 2362 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub); 2363 } 2364 2365 // Implementation of unsigned i64 to f32. 2366 // TODO: Generalize this for use with other types. 2367 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) { 2368 // For unsigned conversions, convert them to signed conversions using the 2369 // algorithm from the x86_64 __floatundidf in compiler_rt. 2370 if (!isSigned) { 2371 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0); 2372 2373 SDValue ShiftConst = DAG.getConstant( 2374 1, dl, TLI.getShiftAmountTy(Op0.getValueType(), DAG.getDataLayout())); 2375 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst); 2376 SDValue AndConst = DAG.getConstant(1, dl, MVT::i64); 2377 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst); 2378 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr); 2379 2380 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or); 2381 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt); 2382 2383 // TODO: This really should be implemented using a branch rather than a 2384 // select. We happen to get lucky and machinesink does the right 2385 // thing most of the time. This would be a good candidate for a 2386 //pseudo-op, or, even better, for whole-function isel. 2387 SDValue SignBitTest = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), 2388 Op0, DAG.getConstant(0, dl, MVT::i64), ISD::SETLT); 2389 return DAG.getSelect(dl, MVT::f32, SignBitTest, Slow, Fast); 2390 } 2391 2392 // Otherwise, implement the fully general conversion. 2393 2394 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, 2395 DAG.getConstant(UINT64_C(0xfffffffffffff800), dl, MVT::i64)); 2396 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, 2397 DAG.getConstant(UINT64_C(0x800), dl, MVT::i64)); 2398 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, 2399 DAG.getConstant(UINT64_C(0x7ff), dl, MVT::i64)); 2400 SDValue Ne = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), And2, 2401 DAG.getConstant(UINT64_C(0), dl, MVT::i64), 2402 ISD::SETNE); 2403 SDValue Sel = DAG.getSelect(dl, MVT::i64, Ne, Or, Op0); 2404 SDValue Ge = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), Op0, 2405 DAG.getConstant(UINT64_C(0x0020000000000000), dl, 2406 MVT::i64), 2407 ISD::SETUGE); 2408 SDValue Sel2 = DAG.getSelect(dl, MVT::i64, Ge, Sel, Op0); 2409 EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType(), DAG.getDataLayout()); 2410 2411 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2, 2412 DAG.getConstant(32, dl, SHVT)); 2413 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh); 2414 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc); 2415 SDValue TwoP32 = 2416 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), dl, 2417 MVT::f64); 2418 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt); 2419 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2); 2420 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo); 2421 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2); 2422 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd, 2423 DAG.getIntPtrConstant(0, dl)); 2424 } 2425 2426 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0); 2427 2428 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(Op0.getValueType()), 2429 Op0, 2430 DAG.getConstant(0, dl, Op0.getValueType()), 2431 ISD::SETLT); 2432 SDValue Zero = DAG.getIntPtrConstant(0, dl), 2433 Four = DAG.getIntPtrConstant(4, dl); 2434 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(), 2435 SignSet, Four, Zero); 2436 2437 // If the sign bit of the integer is set, the large number will be treated 2438 // as a negative number. To counteract this, the dynamic code adds an 2439 // offset depending on the data type. 2440 uint64_t FF; 2441 switch (Op0.getSimpleValueType().SimpleTy) { 2442 default: llvm_unreachable("Unsupported integer type!"); 2443 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float) 2444 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float) 2445 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float) 2446 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float) 2447 } 2448 if (DAG.getDataLayout().isLittleEndian()) 2449 FF <<= 32; 2450 Constant *FudgeFactor = ConstantInt::get( 2451 Type::getInt64Ty(*DAG.getContext()), FF); 2452 2453 SDValue CPIdx = 2454 DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout())); 2455 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 2456 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset); 2457 Alignment = std::min(Alignment, 4u); 2458 SDValue FudgeInReg; 2459 if (DestVT == MVT::f32) 2460 FudgeInReg = DAG.getLoad( 2461 MVT::f32, dl, DAG.getEntryNode(), CPIdx, 2462 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false, 2463 false, false, Alignment); 2464 else { 2465 SDValue Load = DAG.getExtLoad( 2466 ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx, 2467 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32, 2468 false, false, false, Alignment); 2469 HandleSDNode Handle(Load); 2470 LegalizeOp(Load.getNode()); 2471 FudgeInReg = Handle.getValue(); 2472 } 2473 2474 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg); 2475 } 2476 2477 /// This function is responsible for legalizing a 2478 /// *INT_TO_FP operation of the specified operand when the target requests that 2479 /// we promote it. At this point, we know that the result and operand types are 2480 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP 2481 /// operation that takes a larger input. 2482 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, 2483 bool isSigned, 2484 const SDLoc &dl) { 2485 // First step, figure out the appropriate *INT_TO_FP operation to use. 2486 EVT NewInTy = LegalOp.getValueType(); 2487 2488 unsigned OpToUse = 0; 2489 2490 // Scan for the appropriate larger type to use. 2491 while (1) { 2492 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1); 2493 assert(NewInTy.isInteger() && "Ran out of possibilities!"); 2494 2495 // If the target supports SINT_TO_FP of this type, use it. 2496 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) { 2497 OpToUse = ISD::SINT_TO_FP; 2498 break; 2499 } 2500 if (isSigned) continue; 2501 2502 // If the target supports UINT_TO_FP of this type, use it. 2503 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) { 2504 OpToUse = ISD::UINT_TO_FP; 2505 break; 2506 } 2507 2508 // Otherwise, try a larger type. 2509 } 2510 2511 // Okay, we found the operation and type to use. Zero extend our input to the 2512 // desired type then run the operation on it. 2513 return DAG.getNode(OpToUse, dl, DestVT, 2514 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 2515 dl, NewInTy, LegalOp)); 2516 } 2517 2518 /// This function is responsible for legalizing a 2519 /// FP_TO_*INT operation of the specified operand when the target requests that 2520 /// we promote it. At this point, we know that the result and operand types are 2521 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT 2522 /// operation that returns a larger result. 2523 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, 2524 bool isSigned, 2525 const SDLoc &dl) { 2526 // First step, figure out the appropriate FP_TO*INT operation to use. 2527 EVT NewOutTy = DestVT; 2528 2529 unsigned OpToUse = 0; 2530 2531 // Scan for the appropriate larger type to use. 2532 while (1) { 2533 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1); 2534 assert(NewOutTy.isInteger() && "Ran out of possibilities!"); 2535 2536 // A larger signed type can hold all unsigned values of the requested type, 2537 // so using FP_TO_SINT is valid 2538 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) { 2539 OpToUse = ISD::FP_TO_SINT; 2540 break; 2541 } 2542 2543 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT. 2544 if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) { 2545 OpToUse = ISD::FP_TO_UINT; 2546 break; 2547 } 2548 2549 // Otherwise, try a larger type. 2550 } 2551 2552 2553 // Okay, we found the operation and type to use. 2554 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp); 2555 2556 // Truncate the result of the extended FP_TO_*INT operation to the desired 2557 // size. 2558 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation); 2559 } 2560 2561 /// Open code the operations for BITREVERSE. 2562 SDValue SelectionDAGLegalize::ExpandBITREVERSE(SDValue Op, const SDLoc &dl) { 2563 EVT VT = Op.getValueType(); 2564 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2565 unsigned Sz = VT.getScalarSizeInBits(); 2566 2567 SDValue Tmp, Tmp2; 2568 Tmp = DAG.getConstant(0, dl, VT); 2569 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 2570 if (I < J) 2571 Tmp2 = 2572 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 2573 else 2574 Tmp2 = 2575 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 2576 2577 APInt Shift(Sz, 1); 2578 Shift = Shift.shl(J); 2579 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 2580 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 2581 } 2582 2583 return Tmp; 2584 } 2585 2586 /// Open code the operations for BSWAP of the specified operation. 2587 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, const SDLoc &dl) { 2588 EVT VT = Op.getValueType(); 2589 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2590 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 2591 switch (VT.getSimpleVT().SimpleTy) { 2592 default: llvm_unreachable("Unhandled Expand type in BSWAP!"); 2593 case MVT::i16: 2594 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2595 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2596 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 2597 case MVT::i32: 2598 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2599 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2600 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2601 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2602 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 2603 DAG.getConstant(0xFF0000, dl, VT)); 2604 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 2605 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 2606 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 2607 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 2608 case MVT::i64: 2609 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 2610 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 2611 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2612 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2613 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2614 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2615 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 2616 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 2617 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 2618 DAG.getConstant(255ULL<<48, dl, VT)); 2619 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 2620 DAG.getConstant(255ULL<<40, dl, VT)); 2621 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 2622 DAG.getConstant(255ULL<<32, dl, VT)); 2623 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 2624 DAG.getConstant(255ULL<<24, dl, VT)); 2625 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 2626 DAG.getConstant(255ULL<<16, dl, VT)); 2627 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 2628 DAG.getConstant(255ULL<<8 , dl, VT)); 2629 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 2630 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 2631 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 2632 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 2633 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 2634 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 2635 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 2636 } 2637 } 2638 2639 /// Expand the specified bitcount instruction into operations. 2640 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op, 2641 const SDLoc &dl) { 2642 switch (Opc) { 2643 default: llvm_unreachable("Cannot expand this yet!"); 2644 case ISD::CTPOP: { 2645 EVT VT = Op.getValueType(); 2646 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2647 unsigned Len = VT.getSizeInBits(); 2648 2649 assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 && 2650 "CTPOP not implemented for this type."); 2651 2652 // This is the "best" algorithm from 2653 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 2654 2655 SDValue Mask55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), 2656 dl, VT); 2657 SDValue Mask33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), 2658 dl, VT); 2659 SDValue Mask0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), 2660 dl, VT); 2661 SDValue Mask01 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), 2662 dl, VT); 2663 2664 // v = v - ((v >> 1) & 0x55555555...) 2665 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 2666 DAG.getNode(ISD::AND, dl, VT, 2667 DAG.getNode(ISD::SRL, dl, VT, Op, 2668 DAG.getConstant(1, dl, ShVT)), 2669 Mask55)); 2670 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 2671 Op = DAG.getNode(ISD::ADD, dl, VT, 2672 DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 2673 DAG.getNode(ISD::AND, dl, VT, 2674 DAG.getNode(ISD::SRL, dl, VT, Op, 2675 DAG.getConstant(2, dl, ShVT)), 2676 Mask33)); 2677 // v = (v + (v >> 4)) & 0x0F0F0F0F... 2678 Op = DAG.getNode(ISD::AND, dl, VT, 2679 DAG.getNode(ISD::ADD, dl, VT, Op, 2680 DAG.getNode(ISD::SRL, dl, VT, Op, 2681 DAG.getConstant(4, dl, ShVT))), 2682 Mask0F); 2683 // v = (v * 0x01010101...) >> (Len - 8) 2684 Op = DAG.getNode(ISD::SRL, dl, VT, 2685 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 2686 DAG.getConstant(Len - 8, dl, ShVT)); 2687 2688 return Op; 2689 } 2690 case ISD::CTLZ_ZERO_UNDEF: 2691 // This trivially expands to CTLZ. 2692 return DAG.getNode(ISD::CTLZ, dl, Op.getValueType(), Op); 2693 case ISD::CTLZ: { 2694 EVT VT = Op.getValueType(); 2695 unsigned len = VT.getSizeInBits(); 2696 2697 if (TLI.isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 2698 EVT SetCCVT = getSetCCResultType(VT); 2699 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 2700 SDValue Zero = DAG.getConstant(0, dl, VT); 2701 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 2702 return DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 2703 DAG.getConstant(len, dl, VT), CTLZ); 2704 } 2705 2706 // for now, we do this: 2707 // x = x | (x >> 1); 2708 // x = x | (x >> 2); 2709 // ... 2710 // x = x | (x >>16); 2711 // x = x | (x >>32); // for 64-bit input 2712 // return popcount(~x); 2713 // 2714 // Ref: "Hacker's Delight" by Henry Warren 2715 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2716 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) { 2717 SDValue Tmp3 = DAG.getConstant(1ULL << i, dl, ShVT); 2718 Op = DAG.getNode(ISD::OR, dl, VT, Op, 2719 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3)); 2720 } 2721 Op = DAG.getNOT(dl, Op, VT); 2722 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 2723 } 2724 case ISD::CTTZ_ZERO_UNDEF: 2725 // This trivially expands to CTTZ. 2726 return DAG.getNode(ISD::CTTZ, dl, Op.getValueType(), Op); 2727 case ISD::CTTZ: { 2728 // for now, we use: { return popcount(~x & (x - 1)); } 2729 // unless the target has ctlz but not ctpop, in which case we use: 2730 // { return 32 - nlz(~x & (x-1)); } 2731 // Ref: "Hacker's Delight" by Henry Warren 2732 EVT VT = Op.getValueType(); 2733 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT, 2734 DAG.getNOT(dl, Op, VT), 2735 DAG.getNode(ISD::SUB, dl, VT, Op, 2736 DAG.getConstant(1, dl, VT))); 2737 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 2738 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) && 2739 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT)) 2740 return DAG.getNode(ISD::SUB, dl, VT, 2741 DAG.getConstant(VT.getSizeInBits(), dl, VT), 2742 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3)); 2743 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3); 2744 } 2745 } 2746 } 2747 2748 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) { 2749 SmallVector<SDValue, 8> Results; 2750 SDLoc dl(Node); 2751 SDValue Tmp1, Tmp2, Tmp3, Tmp4; 2752 bool NeedInvert; 2753 switch (Node->getOpcode()) { 2754 case ISD::CTPOP: 2755 case ISD::CTLZ: 2756 case ISD::CTLZ_ZERO_UNDEF: 2757 case ISD::CTTZ: 2758 case ISD::CTTZ_ZERO_UNDEF: 2759 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl); 2760 Results.push_back(Tmp1); 2761 break; 2762 case ISD::BITREVERSE: 2763 Results.push_back(ExpandBITREVERSE(Node->getOperand(0), dl)); 2764 break; 2765 case ISD::BSWAP: 2766 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl)); 2767 break; 2768 case ISD::FRAMEADDR: 2769 case ISD::RETURNADDR: 2770 case ISD::FRAME_TO_ARGS_OFFSET: 2771 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0))); 2772 break; 2773 case ISD::FLT_ROUNDS_: 2774 Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0))); 2775 break; 2776 case ISD::EH_RETURN: 2777 case ISD::EH_LABEL: 2778 case ISD::PREFETCH: 2779 case ISD::VAEND: 2780 case ISD::EH_SJLJ_LONGJMP: 2781 // If the target didn't expand these, there's nothing to do, so just 2782 // preserve the chain and be done. 2783 Results.push_back(Node->getOperand(0)); 2784 break; 2785 case ISD::READCYCLECOUNTER: 2786 // If the target didn't expand this, just return 'zero' and preserve the 2787 // chain. 2788 Results.append(Node->getNumValues() - 1, 2789 DAG.getConstant(0, dl, Node->getValueType(0))); 2790 Results.push_back(Node->getOperand(0)); 2791 break; 2792 case ISD::EH_SJLJ_SETJMP: 2793 // If the target didn't expand this, just return 'zero' and preserve the 2794 // chain. 2795 Results.push_back(DAG.getConstant(0, dl, MVT::i32)); 2796 Results.push_back(Node->getOperand(0)); 2797 break; 2798 case ISD::ATOMIC_LOAD: { 2799 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP. 2800 SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0)); 2801 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 2802 SDValue Swap = DAG.getAtomicCmpSwap( 2803 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs, 2804 Node->getOperand(0), Node->getOperand(1), Zero, Zero, 2805 cast<AtomicSDNode>(Node)->getMemOperand(), 2806 cast<AtomicSDNode>(Node)->getOrdering(), 2807 cast<AtomicSDNode>(Node)->getOrdering(), 2808 cast<AtomicSDNode>(Node)->getSynchScope()); 2809 Results.push_back(Swap.getValue(0)); 2810 Results.push_back(Swap.getValue(1)); 2811 break; 2812 } 2813 case ISD::ATOMIC_STORE: { 2814 // There is no libcall for atomic store; fake it with ATOMIC_SWAP. 2815 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 2816 cast<AtomicSDNode>(Node)->getMemoryVT(), 2817 Node->getOperand(0), 2818 Node->getOperand(1), Node->getOperand(2), 2819 cast<AtomicSDNode>(Node)->getMemOperand(), 2820 cast<AtomicSDNode>(Node)->getOrdering(), 2821 cast<AtomicSDNode>(Node)->getSynchScope()); 2822 Results.push_back(Swap.getValue(1)); 2823 break; 2824 } 2825 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: { 2826 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and 2827 // splits out the success value as a comparison. Expanding the resulting 2828 // ATOMIC_CMP_SWAP will produce a libcall. 2829 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 2830 SDValue Res = DAG.getAtomicCmpSwap( 2831 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs, 2832 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2), 2833 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand(), 2834 cast<AtomicSDNode>(Node)->getSuccessOrdering(), 2835 cast<AtomicSDNode>(Node)->getFailureOrdering(), 2836 cast<AtomicSDNode>(Node)->getSynchScope()); 2837 2838 SDValue ExtRes = Res; 2839 SDValue LHS = Res; 2840 SDValue RHS = Node->getOperand(1); 2841 2842 EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT(); 2843 EVT OuterType = Node->getValueType(0); 2844 switch (TLI.getExtendForAtomicOps()) { 2845 case ISD::SIGN_EXTEND: 2846 LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res, 2847 DAG.getValueType(AtomicType)); 2848 RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType, 2849 Node->getOperand(2), DAG.getValueType(AtomicType)); 2850 ExtRes = LHS; 2851 break; 2852 case ISD::ZERO_EXTEND: 2853 LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res, 2854 DAG.getValueType(AtomicType)); 2855 RHS = DAG.getNode(ISD::ZERO_EXTEND, dl, OuterType, Node->getOperand(2)); 2856 ExtRes = LHS; 2857 break; 2858 case ISD::ANY_EXTEND: 2859 LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType); 2860 RHS = DAG.getNode(ISD::ZERO_EXTEND, dl, OuterType, Node->getOperand(2)); 2861 break; 2862 default: 2863 llvm_unreachable("Invalid atomic op extension"); 2864 } 2865 2866 SDValue Success = 2867 DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ); 2868 2869 Results.push_back(ExtRes.getValue(0)); 2870 Results.push_back(Success); 2871 Results.push_back(Res.getValue(1)); 2872 break; 2873 } 2874 case ISD::DYNAMIC_STACKALLOC: 2875 ExpandDYNAMIC_STACKALLOC(Node, Results); 2876 break; 2877 case ISD::MERGE_VALUES: 2878 for (unsigned i = 0; i < Node->getNumValues(); i++) 2879 Results.push_back(Node->getOperand(i)); 2880 break; 2881 case ISD::UNDEF: { 2882 EVT VT = Node->getValueType(0); 2883 if (VT.isInteger()) 2884 Results.push_back(DAG.getConstant(0, dl, VT)); 2885 else { 2886 assert(VT.isFloatingPoint() && "Unknown value type!"); 2887 Results.push_back(DAG.getConstantFP(0, dl, VT)); 2888 } 2889 break; 2890 } 2891 case ISD::FP_ROUND: 2892 case ISD::BITCAST: 2893 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0), 2894 Node->getValueType(0), dl); 2895 Results.push_back(Tmp1); 2896 break; 2897 case ISD::FP_EXTEND: 2898 Tmp1 = EmitStackConvert(Node->getOperand(0), 2899 Node->getOperand(0).getValueType(), 2900 Node->getValueType(0), dl); 2901 Results.push_back(Tmp1); 2902 break; 2903 case ISD::SIGN_EXTEND_INREG: { 2904 // NOTE: we could fall back on load/store here too for targets without 2905 // SAR. However, it is doubtful that any exist. 2906 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 2907 EVT VT = Node->getValueType(0); 2908 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2909 if (VT.isVector()) 2910 ShiftAmountTy = VT; 2911 unsigned BitsDiff = VT.getScalarType().getSizeInBits() - 2912 ExtraVT.getScalarType().getSizeInBits(); 2913 SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy); 2914 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0), 2915 Node->getOperand(0), ShiftCst); 2916 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst); 2917 Results.push_back(Tmp1); 2918 break; 2919 } 2920 case ISD::FP_ROUND_INREG: { 2921 // The only way we can lower this is to turn it into a TRUNCSTORE, 2922 // EXTLOAD pair, targeting a temporary location (a stack slot). 2923 2924 // NOTE: there is a choice here between constantly creating new stack 2925 // slots and always reusing the same one. We currently always create 2926 // new ones, as reuse may inhibit scheduling. 2927 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 2928 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT, 2929 Node->getValueType(0), dl); 2930 Results.push_back(Tmp1); 2931 break; 2932 } 2933 case ISD::SINT_TO_FP: 2934 case ISD::UINT_TO_FP: 2935 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP, 2936 Node->getOperand(0), Node->getValueType(0), dl); 2937 Results.push_back(Tmp1); 2938 break; 2939 case ISD::FP_TO_SINT: 2940 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) 2941 Results.push_back(Tmp1); 2942 break; 2943 case ISD::FP_TO_UINT: { 2944 SDValue True, False; 2945 EVT VT = Node->getOperand(0).getValueType(); 2946 EVT NVT = Node->getValueType(0); 2947 APFloat apf(DAG.EVTToAPFloatSemantics(VT), 2948 APInt::getNullValue(VT.getSizeInBits())); 2949 APInt x = APInt::getSignBit(NVT.getSizeInBits()); 2950 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven); 2951 Tmp1 = DAG.getConstantFP(apf, dl, VT); 2952 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(VT), 2953 Node->getOperand(0), 2954 Tmp1, ISD::SETLT); 2955 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0)); 2956 // TODO: Should any fast-math-flags be set for the FSUB? 2957 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, 2958 DAG.getNode(ISD::FSUB, dl, VT, 2959 Node->getOperand(0), Tmp1)); 2960 False = DAG.getNode(ISD::XOR, dl, NVT, False, 2961 DAG.getConstant(x, dl, NVT)); 2962 Tmp1 = DAG.getSelect(dl, NVT, Tmp2, True, False); 2963 Results.push_back(Tmp1); 2964 break; 2965 } 2966 case ISD::VAARG: 2967 Results.push_back(DAG.expandVAArg(Node)); 2968 Results.push_back(Results[0].getValue(1)); 2969 break; 2970 case ISD::VACOPY: 2971 Results.push_back(DAG.expandVACopy(Node)); 2972 break; 2973 case ISD::EXTRACT_VECTOR_ELT: 2974 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1) 2975 // This must be an access of the only element. Return it. 2976 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), 2977 Node->getOperand(0)); 2978 else 2979 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0)); 2980 Results.push_back(Tmp1); 2981 break; 2982 case ISD::EXTRACT_SUBVECTOR: 2983 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0))); 2984 break; 2985 case ISD::INSERT_SUBVECTOR: 2986 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0))); 2987 break; 2988 case ISD::CONCAT_VECTORS: { 2989 Results.push_back(ExpandVectorBuildThroughStack(Node)); 2990 break; 2991 } 2992 case ISD::SCALAR_TO_VECTOR: 2993 Results.push_back(ExpandSCALAR_TO_VECTOR(Node)); 2994 break; 2995 case ISD::INSERT_VECTOR_ELT: 2996 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0), 2997 Node->getOperand(1), 2998 Node->getOperand(2), dl)); 2999 break; 3000 case ISD::VECTOR_SHUFFLE: { 3001 SmallVector<int, 32> NewMask; 3002 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask(); 3003 3004 EVT VT = Node->getValueType(0); 3005 EVT EltVT = VT.getVectorElementType(); 3006 SDValue Op0 = Node->getOperand(0); 3007 SDValue Op1 = Node->getOperand(1); 3008 if (!TLI.isTypeLegal(EltVT)) { 3009 3010 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT); 3011 3012 // BUILD_VECTOR operands are allowed to be wider than the element type. 3013 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept 3014 // it. 3015 if (NewEltVT.bitsLT(EltVT)) { 3016 3017 // Convert shuffle node. 3018 // If original node was v4i64 and the new EltVT is i32, 3019 // cast operands to v8i32 and re-build the mask. 3020 3021 // Calculate new VT, the size of the new VT should be equal to original. 3022 EVT NewVT = 3023 EVT::getVectorVT(*DAG.getContext(), NewEltVT, 3024 VT.getSizeInBits() / NewEltVT.getSizeInBits()); 3025 assert(NewVT.bitsEq(VT)); 3026 3027 // cast operands to new VT 3028 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0); 3029 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1); 3030 3031 // Convert the shuffle mask 3032 unsigned int factor = 3033 NewVT.getVectorNumElements()/VT.getVectorNumElements(); 3034 3035 // EltVT gets smaller 3036 assert(factor > 0); 3037 3038 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 3039 if (Mask[i] < 0) { 3040 for (unsigned fi = 0; fi < factor; ++fi) 3041 NewMask.push_back(Mask[i]); 3042 } 3043 else { 3044 for (unsigned fi = 0; fi < factor; ++fi) 3045 NewMask.push_back(Mask[i]*factor+fi); 3046 } 3047 } 3048 Mask = NewMask; 3049 VT = NewVT; 3050 } 3051 EltVT = NewEltVT; 3052 } 3053 unsigned NumElems = VT.getVectorNumElements(); 3054 SmallVector<SDValue, 16> Ops; 3055 for (unsigned i = 0; i != NumElems; ++i) { 3056 if (Mask[i] < 0) { 3057 Ops.push_back(DAG.getUNDEF(EltVT)); 3058 continue; 3059 } 3060 unsigned Idx = Mask[i]; 3061 if (Idx < NumElems) 3062 Ops.push_back(DAG.getNode( 3063 ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 3064 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())))); 3065 else 3066 Ops.push_back(DAG.getNode( 3067 ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1, 3068 DAG.getConstant(Idx - NumElems, dl, 3069 TLI.getVectorIdxTy(DAG.getDataLayout())))); 3070 } 3071 3072 Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 3073 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type. 3074 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1); 3075 Results.push_back(Tmp1); 3076 break; 3077 } 3078 case ISD::EXTRACT_ELEMENT: { 3079 EVT OpTy = Node->getOperand(0).getValueType(); 3080 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) { 3081 // 1 -> Hi 3082 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0), 3083 DAG.getConstant(OpTy.getSizeInBits() / 2, dl, 3084 TLI.getShiftAmountTy( 3085 Node->getOperand(0).getValueType(), 3086 DAG.getDataLayout()))); 3087 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1); 3088 } else { 3089 // 0 -> Lo 3090 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), 3091 Node->getOperand(0)); 3092 } 3093 Results.push_back(Tmp1); 3094 break; 3095 } 3096 case ISD::STACKSAVE: 3097 // Expand to CopyFromReg if the target set 3098 // StackPointerRegisterToSaveRestore. 3099 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) { 3100 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP, 3101 Node->getValueType(0))); 3102 Results.push_back(Results[0].getValue(1)); 3103 } else { 3104 Results.push_back(DAG.getUNDEF(Node->getValueType(0))); 3105 Results.push_back(Node->getOperand(0)); 3106 } 3107 break; 3108 case ISD::STACKRESTORE: 3109 // Expand to CopyToReg if the target set 3110 // StackPointerRegisterToSaveRestore. 3111 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) { 3112 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP, 3113 Node->getOperand(1))); 3114 } else { 3115 Results.push_back(Node->getOperand(0)); 3116 } 3117 break; 3118 case ISD::GET_DYNAMIC_AREA_OFFSET: 3119 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0))); 3120 Results.push_back(Results[0].getValue(0)); 3121 break; 3122 case ISD::FCOPYSIGN: 3123 Results.push_back(ExpandFCOPYSIGN(Node)); 3124 break; 3125 case ISD::FNEG: 3126 // Expand Y = FNEG(X) -> Y = SUB -0.0, X 3127 Tmp1 = DAG.getConstantFP(-0.0, dl, Node->getValueType(0)); 3128 // TODO: If FNEG has fast-math-flags, propagate them to the FSUB. 3129 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1, 3130 Node->getOperand(0)); 3131 Results.push_back(Tmp1); 3132 break; 3133 case ISD::FABS: 3134 Results.push_back(ExpandFABS(Node)); 3135 break; 3136 case ISD::SMIN: 3137 case ISD::SMAX: 3138 case ISD::UMIN: 3139 case ISD::UMAX: { 3140 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 3141 ISD::CondCode Pred; 3142 switch (Node->getOpcode()) { 3143 default: llvm_unreachable("How did we get here?"); 3144 case ISD::SMAX: Pred = ISD::SETGT; break; 3145 case ISD::SMIN: Pred = ISD::SETLT; break; 3146 case ISD::UMAX: Pred = ISD::SETUGT; break; 3147 case ISD::UMIN: Pred = ISD::SETULT; break; 3148 } 3149 Tmp1 = Node->getOperand(0); 3150 Tmp2 = Node->getOperand(1); 3151 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred); 3152 Results.push_back(Tmp1); 3153 break; 3154 } 3155 3156 case ISD::FSIN: 3157 case ISD::FCOS: { 3158 EVT VT = Node->getValueType(0); 3159 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin / 3160 // fcos which share the same operand and both are used. 3161 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) || 3162 canCombineSinCosLibcall(Node, TLI, TM)) 3163 && useSinCos(Node)) { 3164 SDVTList VTs = DAG.getVTList(VT, VT); 3165 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0)); 3166 if (Node->getOpcode() == ISD::FCOS) 3167 Tmp1 = Tmp1.getValue(1); 3168 Results.push_back(Tmp1); 3169 } 3170 break; 3171 } 3172 case ISD::FMAD: 3173 llvm_unreachable("Illegal fmad should never be formed"); 3174 3175 case ISD::FP16_TO_FP: 3176 if (Node->getValueType(0) != MVT::f32) { 3177 // We can extend to types bigger than f32 in two steps without changing 3178 // the result. Since "f16 -> f32" is much more commonly available, give 3179 // CodeGen the option of emitting that before resorting to a libcall. 3180 SDValue Res = 3181 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0)); 3182 Results.push_back( 3183 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res)); 3184 } 3185 break; 3186 case ISD::FP_TO_FP16: 3187 if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) { 3188 SDValue Op = Node->getOperand(0); 3189 MVT SVT = Op.getSimpleValueType(); 3190 if ((SVT == MVT::f64 || SVT == MVT::f80) && 3191 TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) { 3192 // Under fastmath, we can expand this node into a fround followed by 3193 // a float-half conversion. 3194 SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op, 3195 DAG.getIntPtrConstant(0, dl)); 3196 Results.push_back( 3197 DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal)); 3198 } 3199 } 3200 break; 3201 case ISD::ConstantFP: { 3202 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node); 3203 // Check to see if this FP immediate is already legal. 3204 // If this is a legal constant, turn it into a TargetConstantFP node. 3205 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0))) 3206 Results.push_back(ExpandConstantFP(CFP, true)); 3207 break; 3208 } 3209 case ISD::Constant: { 3210 ConstantSDNode *CP = cast<ConstantSDNode>(Node); 3211 Results.push_back(ExpandConstant(CP)); 3212 break; 3213 } 3214 case ISD::FSUB: { 3215 EVT VT = Node->getValueType(0); 3216 if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) && 3217 TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) { 3218 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(Node)->Flags; 3219 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1)); 3220 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags); 3221 Results.push_back(Tmp1); 3222 } 3223 break; 3224 } 3225 case ISD::SUB: { 3226 EVT VT = Node->getValueType(0); 3227 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 3228 TLI.isOperationLegalOrCustom(ISD::XOR, VT) && 3229 "Don't know how to expand this subtraction!"); 3230 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1), 3231 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 3232 VT)); 3233 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT)); 3234 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1)); 3235 break; 3236 } 3237 case ISD::UREM: 3238 case ISD::SREM: { 3239 EVT VT = Node->getValueType(0); 3240 bool isSigned = Node->getOpcode() == ISD::SREM; 3241 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 3242 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3243 Tmp2 = Node->getOperand(0); 3244 Tmp3 = Node->getOperand(1); 3245 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) { 3246 SDVTList VTs = DAG.getVTList(VT, VT); 3247 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1); 3248 Results.push_back(Tmp1); 3249 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) { 3250 // X % Y -> X-X/Y*Y 3251 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3); 3252 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3); 3253 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1); 3254 Results.push_back(Tmp1); 3255 } 3256 break; 3257 } 3258 case ISD::UDIV: 3259 case ISD::SDIV: { 3260 bool isSigned = Node->getOpcode() == ISD::SDIV; 3261 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3262 EVT VT = Node->getValueType(0); 3263 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) { 3264 SDVTList VTs = DAG.getVTList(VT, VT); 3265 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0), 3266 Node->getOperand(1)); 3267 Results.push_back(Tmp1); 3268 } 3269 break; 3270 } 3271 case ISD::MULHU: 3272 case ISD::MULHS: { 3273 unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : 3274 ISD::SMUL_LOHI; 3275 EVT VT = Node->getValueType(0); 3276 SDVTList VTs = DAG.getVTList(VT, VT); 3277 assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) && 3278 "If this wasn't legal, it shouldn't have been created!"); 3279 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0), 3280 Node->getOperand(1)); 3281 Results.push_back(Tmp1.getValue(1)); 3282 break; 3283 } 3284 case ISD::MUL: { 3285 EVT VT = Node->getValueType(0); 3286 SDVTList VTs = DAG.getVTList(VT, VT); 3287 // See if multiply or divide can be lowered using two-result operations. 3288 // We just need the low half of the multiply; try both the signed 3289 // and unsigned forms. If the target supports both SMUL_LOHI and 3290 // UMUL_LOHI, form a preference by checking which forms of plain 3291 // MULH it supports. 3292 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT); 3293 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT); 3294 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT); 3295 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT); 3296 unsigned OpToUse = 0; 3297 if (HasSMUL_LOHI && !HasMULHS) { 3298 OpToUse = ISD::SMUL_LOHI; 3299 } else if (HasUMUL_LOHI && !HasMULHU) { 3300 OpToUse = ISD::UMUL_LOHI; 3301 } else if (HasSMUL_LOHI) { 3302 OpToUse = ISD::SMUL_LOHI; 3303 } else if (HasUMUL_LOHI) { 3304 OpToUse = ISD::UMUL_LOHI; 3305 } 3306 if (OpToUse) { 3307 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0), 3308 Node->getOperand(1))); 3309 break; 3310 } 3311 3312 SDValue Lo, Hi; 3313 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext()); 3314 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) && 3315 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) && 3316 TLI.isOperationLegalOrCustom(ISD::SHL, VT) && 3317 TLI.isOperationLegalOrCustom(ISD::OR, VT) && 3318 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG)) { 3319 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 3320 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi); 3321 SDValue Shift = 3322 DAG.getConstant(HalfType.getSizeInBits(), dl, 3323 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout())); 3324 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3325 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi)); 3326 } 3327 break; 3328 } 3329 case ISD::SADDO: 3330 case ISD::SSUBO: { 3331 SDValue LHS = Node->getOperand(0); 3332 SDValue RHS = Node->getOperand(1); 3333 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ? 3334 ISD::ADD : ISD::SUB, dl, LHS.getValueType(), 3335 LHS, RHS); 3336 Results.push_back(Sum); 3337 EVT ResultType = Node->getValueType(1); 3338 EVT OType = getSetCCResultType(Node->getValueType(0)); 3339 3340 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 3341 3342 // LHSSign -> LHS >= 0 3343 // RHSSign -> RHS >= 0 3344 // SumSign -> Sum >= 0 3345 // 3346 // Add: 3347 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign) 3348 // Sub: 3349 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign) 3350 // 3351 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE); 3352 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE); 3353 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign, 3354 Node->getOpcode() == ISD::SADDO ? 3355 ISD::SETEQ : ISD::SETNE); 3356 3357 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE); 3358 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE); 3359 3360 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE); 3361 Results.push_back(DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType)); 3362 break; 3363 } 3364 case ISD::UADDO: 3365 case ISD::USUBO: { 3366 SDValue LHS = Node->getOperand(0); 3367 SDValue RHS = Node->getOperand(1); 3368 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ? 3369 ISD::ADD : ISD::SUB, dl, LHS.getValueType(), 3370 LHS, RHS); 3371 Results.push_back(Sum); 3372 3373 EVT ResultType = Node->getValueType(1); 3374 EVT SetCCType = getSetCCResultType(Node->getValueType(0)); 3375 ISD::CondCode CC 3376 = Node->getOpcode() == ISD::UADDO ? ISD::SETULT : ISD::SETUGT; 3377 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC); 3378 3379 Results.push_back(DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType)); 3380 break; 3381 } 3382 case ISD::UMULO: 3383 case ISD::SMULO: { 3384 EVT VT = Node->getValueType(0); 3385 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2); 3386 SDValue LHS = Node->getOperand(0); 3387 SDValue RHS = Node->getOperand(1); 3388 SDValue BottomHalf; 3389 SDValue TopHalf; 3390 static const unsigned Ops[2][3] = 3391 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 3392 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 3393 bool isSigned = Node->getOpcode() == ISD::SMULO; 3394 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 3395 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 3396 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 3397 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 3398 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 3399 RHS); 3400 TopHalf = BottomHalf.getValue(1); 3401 } else if (TLI.isTypeLegal(WideVT)) { 3402 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 3403 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 3404 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 3405 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1, 3406 DAG.getIntPtrConstant(0, dl)); 3407 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1, 3408 DAG.getIntPtrConstant(1, dl)); 3409 } else { 3410 // We can fall back to a libcall with an illegal type for the MUL if we 3411 // have a libcall big enough. 3412 // Also, we can fall back to a division in some cases, but that's a big 3413 // performance hit in the general case. 3414 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 3415 if (WideVT == MVT::i16) 3416 LC = RTLIB::MUL_I16; 3417 else if (WideVT == MVT::i32) 3418 LC = RTLIB::MUL_I32; 3419 else if (WideVT == MVT::i64) 3420 LC = RTLIB::MUL_I64; 3421 else if (WideVT == MVT::i128) 3422 LC = RTLIB::MUL_I128; 3423 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 3424 3425 // The high part is obtained by SRA'ing all but one of the bits of low 3426 // part. 3427 unsigned LoSize = VT.getSizeInBits(); 3428 SDValue HiLHS = 3429 DAG.getNode(ISD::SRA, dl, VT, RHS, 3430 DAG.getConstant(LoSize - 1, dl, 3431 TLI.getPointerTy(DAG.getDataLayout()))); 3432 SDValue HiRHS = 3433 DAG.getNode(ISD::SRA, dl, VT, LHS, 3434 DAG.getConstant(LoSize - 1, dl, 3435 TLI.getPointerTy(DAG.getDataLayout()))); 3436 3437 // Here we're passing the 2 arguments explicitly as 4 arguments that are 3438 // pre-lowered to the correct types. This all depends upon WideVT not 3439 // being a legal type for the architecture and thus has to be split to 3440 // two arguments. 3441 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 3442 SDValue Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl); 3443 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret, 3444 DAG.getIntPtrConstant(0, dl)); 3445 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret, 3446 DAG.getIntPtrConstant(1, dl)); 3447 // Ret is a node with an illegal type. Because such things are not 3448 // generally permitted during this phase of legalization, make sure the 3449 // node has no more uses. The above EXTRACT_ELEMENT nodes should have been 3450 // folded. 3451 assert(Ret->use_empty() && 3452 "Unexpected uses of illegally type from expanded lib call."); 3453 } 3454 3455 if (isSigned) { 3456 Tmp1 = DAG.getConstant( 3457 VT.getSizeInBits() - 1, dl, 3458 TLI.getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 3459 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1); 3460 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, Tmp1, 3461 ISD::SETNE); 3462 } else { 3463 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, 3464 DAG.getConstant(0, dl, VT), ISD::SETNE); 3465 } 3466 Results.push_back(BottomHalf); 3467 Results.push_back(TopHalf); 3468 break; 3469 } 3470 case ISD::BUILD_PAIR: { 3471 EVT PairTy = Node->getValueType(0); 3472 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0)); 3473 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1)); 3474 Tmp2 = DAG.getNode( 3475 ISD::SHL, dl, PairTy, Tmp2, 3476 DAG.getConstant(PairTy.getSizeInBits() / 2, dl, 3477 TLI.getShiftAmountTy(PairTy, DAG.getDataLayout()))); 3478 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2)); 3479 break; 3480 } 3481 case ISD::SELECT: 3482 Tmp1 = Node->getOperand(0); 3483 Tmp2 = Node->getOperand(1); 3484 Tmp3 = Node->getOperand(2); 3485 if (Tmp1.getOpcode() == ISD::SETCC) { 3486 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1), 3487 Tmp2, Tmp3, 3488 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get()); 3489 } else { 3490 Tmp1 = DAG.getSelectCC(dl, Tmp1, 3491 DAG.getConstant(0, dl, Tmp1.getValueType()), 3492 Tmp2, Tmp3, ISD::SETNE); 3493 } 3494 Results.push_back(Tmp1); 3495 break; 3496 case ISD::BR_JT: { 3497 SDValue Chain = Node->getOperand(0); 3498 SDValue Table = Node->getOperand(1); 3499 SDValue Index = Node->getOperand(2); 3500 3501 EVT PTy = TLI.getPointerTy(DAG.getDataLayout()); 3502 3503 const DataLayout &TD = DAG.getDataLayout(); 3504 unsigned EntrySize = 3505 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD); 3506 3507 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index, 3508 DAG.getConstant(EntrySize, dl, Index.getValueType())); 3509 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(), 3510 Index, Table); 3511 3512 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8); 3513 SDValue LD = DAG.getExtLoad( 3514 ISD::SEXTLOAD, dl, PTy, Chain, Addr, 3515 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT, 3516 false, false, false, 0); 3517 Addr = LD; 3518 if (TM.getRelocationModel() == Reloc::PIC_) { 3519 // For PIC, the sequence is: 3520 // BRIND(load(Jumptable + index) + RelocBase) 3521 // RelocBase can be JumpTable, GOT or some sort of global base. 3522 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, 3523 TLI.getPICJumpTableRelocBase(Table, DAG)); 3524 } 3525 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr); 3526 Results.push_back(Tmp1); 3527 break; 3528 } 3529 case ISD::BRCOND: 3530 // Expand brcond's setcc into its constituent parts and create a BR_CC 3531 // Node. 3532 Tmp1 = Node->getOperand(0); 3533 Tmp2 = Node->getOperand(1); 3534 if (Tmp2.getOpcode() == ISD::SETCC) { 3535 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, 3536 Tmp1, Tmp2.getOperand(2), 3537 Tmp2.getOperand(0), Tmp2.getOperand(1), 3538 Node->getOperand(2)); 3539 } else { 3540 // We test only the i1 bit. Skip the AND if UNDEF. 3541 Tmp3 = (Tmp2.isUndef()) ? Tmp2 : 3542 DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2, 3543 DAG.getConstant(1, dl, Tmp2.getValueType())); 3544 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1, 3545 DAG.getCondCode(ISD::SETNE), Tmp3, 3546 DAG.getConstant(0, dl, Tmp3.getValueType()), 3547 Node->getOperand(2)); 3548 } 3549 Results.push_back(Tmp1); 3550 break; 3551 case ISD::SETCC: { 3552 Tmp1 = Node->getOperand(0); 3553 Tmp2 = Node->getOperand(1); 3554 Tmp3 = Node->getOperand(2); 3555 bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, 3556 Tmp3, NeedInvert, dl); 3557 3558 if (Legalized) { 3559 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the 3560 // condition code, create a new SETCC node. 3561 if (Tmp3.getNode()) 3562 Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), 3563 Tmp1, Tmp2, Tmp3); 3564 3565 // If we expanded the SETCC by inverting the condition code, then wrap 3566 // the existing SETCC in a NOT to restore the intended condition. 3567 if (NeedInvert) 3568 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0)); 3569 3570 Results.push_back(Tmp1); 3571 break; 3572 } 3573 3574 // Otherwise, SETCC for the given comparison type must be completely 3575 // illegal; expand it into a SELECT_CC. 3576 EVT VT = Node->getValueType(0); 3577 int TrueValue; 3578 switch (TLI.getBooleanContents(Tmp1->getValueType(0))) { 3579 case TargetLowering::ZeroOrOneBooleanContent: 3580 case TargetLowering::UndefinedBooleanContent: 3581 TrueValue = 1; 3582 break; 3583 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3584 TrueValue = -1; 3585 break; 3586 } 3587 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2, 3588 DAG.getConstant(TrueValue, dl, VT), 3589 DAG.getConstant(0, dl, VT), 3590 Tmp3); 3591 Results.push_back(Tmp1); 3592 break; 3593 } 3594 case ISD::SELECT_CC: { 3595 Tmp1 = Node->getOperand(0); // LHS 3596 Tmp2 = Node->getOperand(1); // RHS 3597 Tmp3 = Node->getOperand(2); // True 3598 Tmp4 = Node->getOperand(3); // False 3599 EVT VT = Node->getValueType(0); 3600 SDValue CC = Node->getOperand(4); 3601 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get(); 3602 3603 if (TLI.isCondCodeLegal(CCOp, Tmp1.getSimpleValueType())) { 3604 // If the condition code is legal, then we need to expand this 3605 // node using SETCC and SELECT. 3606 EVT CmpVT = Tmp1.getValueType(); 3607 assert(!TLI.isOperationExpand(ISD::SELECT, VT) && 3608 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be " 3609 "expanded."); 3610 EVT CCVT = 3611 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT); 3612 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC); 3613 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4)); 3614 break; 3615 } 3616 3617 // SELECT_CC is legal, so the condition code must not be. 3618 bool Legalized = false; 3619 // Try to legalize by inverting the condition. This is for targets that 3620 // might support an ordered version of a condition, but not the unordered 3621 // version (or vice versa). 3622 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp, 3623 Tmp1.getValueType().isInteger()); 3624 if (TLI.isCondCodeLegal(InvCC, Tmp1.getSimpleValueType())) { 3625 // Use the new condition code and swap true and false 3626 Legalized = true; 3627 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC); 3628 } else { 3629 // If The inverse is not legal, then try to swap the arguments using 3630 // the inverse condition code. 3631 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC); 3632 if (TLI.isCondCodeLegal(SwapInvCC, Tmp1.getSimpleValueType())) { 3633 // The swapped inverse condition is legal, so swap true and false, 3634 // lhs and rhs. 3635 Legalized = true; 3636 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC); 3637 } 3638 } 3639 3640 if (!Legalized) { 3641 Legalized = LegalizeSetCCCondCode( 3642 getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert, 3643 dl); 3644 3645 assert(Legalized && "Can't legalize SELECT_CC with legal condition!"); 3646 3647 // If we expanded the SETCC by inverting the condition code, then swap 3648 // the True/False operands to match. 3649 if (NeedInvert) 3650 std::swap(Tmp3, Tmp4); 3651 3652 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the 3653 // condition code, create a new SELECT_CC node. 3654 if (CC.getNode()) { 3655 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), 3656 Tmp1, Tmp2, Tmp3, Tmp4, CC); 3657 } else { 3658 Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType()); 3659 CC = DAG.getCondCode(ISD::SETNE); 3660 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, 3661 Tmp2, Tmp3, Tmp4, CC); 3662 } 3663 } 3664 Results.push_back(Tmp1); 3665 break; 3666 } 3667 case ISD::BR_CC: { 3668 Tmp1 = Node->getOperand(0); // Chain 3669 Tmp2 = Node->getOperand(2); // LHS 3670 Tmp3 = Node->getOperand(3); // RHS 3671 Tmp4 = Node->getOperand(1); // CC 3672 3673 bool Legalized = LegalizeSetCCCondCode(getSetCCResultType( 3674 Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl); 3675 (void)Legalized; 3676 assert(Legalized && "Can't legalize BR_CC with legal condition!"); 3677 3678 // If we expanded the SETCC by inverting the condition code, then wrap 3679 // the existing SETCC in a NOT to restore the intended condition. 3680 if (NeedInvert) 3681 Tmp4 = DAG.getNOT(dl, Tmp4, Tmp4->getValueType(0)); 3682 3683 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC 3684 // node. 3685 if (Tmp4.getNode()) { 3686 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, 3687 Tmp4, Tmp2, Tmp3, Node->getOperand(4)); 3688 } else { 3689 Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType()); 3690 Tmp4 = DAG.getCondCode(ISD::SETNE); 3691 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, 3692 Tmp2, Tmp3, Node->getOperand(4)); 3693 } 3694 Results.push_back(Tmp1); 3695 break; 3696 } 3697 case ISD::BUILD_VECTOR: 3698 Results.push_back(ExpandBUILD_VECTOR(Node)); 3699 break; 3700 case ISD::SRA: 3701 case ISD::SRL: 3702 case ISD::SHL: { 3703 // Scalarize vector SRA/SRL/SHL. 3704 EVT VT = Node->getValueType(0); 3705 assert(VT.isVector() && "Unable to legalize non-vector shift"); 3706 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal"); 3707 unsigned NumElem = VT.getVectorNumElements(); 3708 3709 SmallVector<SDValue, 8> Scalars; 3710 for (unsigned Idx = 0; Idx < NumElem; Idx++) { 3711 SDValue Ex = DAG.getNode( 3712 ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(0), 3713 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3714 SDValue Sh = DAG.getNode( 3715 ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(1), 3716 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3717 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl, 3718 VT.getScalarType(), Ex, Sh)); 3719 } 3720 SDValue Result = 3721 DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0), Scalars); 3722 ReplaceNode(SDValue(Node, 0), Result); 3723 break; 3724 } 3725 case ISD::GLOBAL_OFFSET_TABLE: 3726 case ISD::GlobalAddress: 3727 case ISD::GlobalTLSAddress: 3728 case ISD::ExternalSymbol: 3729 case ISD::ConstantPool: 3730 case ISD::JumpTable: 3731 case ISD::INTRINSIC_W_CHAIN: 3732 case ISD::INTRINSIC_WO_CHAIN: 3733 case ISD::INTRINSIC_VOID: 3734 // FIXME: Custom lowering for these operations shouldn't return null! 3735 break; 3736 } 3737 3738 // Replace the original node with the legalized result. 3739 if (Results.empty()) 3740 return false; 3741 3742 ReplaceNode(Node, Results.data()); 3743 return true; 3744 } 3745 3746 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) { 3747 SmallVector<SDValue, 8> Results; 3748 SDLoc dl(Node); 3749 SDValue Tmp1, Tmp2, Tmp3, Tmp4; 3750 unsigned Opc = Node->getOpcode(); 3751 switch (Opc) { 3752 case ISD::ATOMIC_FENCE: { 3753 // If the target didn't lower this, lower it to '__sync_synchronize()' call 3754 // FIXME: handle "fence singlethread" more efficiently. 3755 TargetLowering::ArgListTy Args; 3756 3757 TargetLowering::CallLoweringInfo CLI(DAG); 3758 CLI.setDebugLoc(dl) 3759 .setChain(Node->getOperand(0)) 3760 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3761 DAG.getExternalSymbol("__sync_synchronize", 3762 TLI.getPointerTy(DAG.getDataLayout())), 3763 std::move(Args), 0); 3764 3765 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 3766 3767 Results.push_back(CallResult.second); 3768 break; 3769 } 3770 // By default, atomic intrinsics are marked Legal and lowered. Targets 3771 // which don't support them directly, however, may want libcalls, in which 3772 // case they mark them Expand, and we get here. 3773 case ISD::ATOMIC_SWAP: 3774 case ISD::ATOMIC_LOAD_ADD: 3775 case ISD::ATOMIC_LOAD_SUB: 3776 case ISD::ATOMIC_LOAD_AND: 3777 case ISD::ATOMIC_LOAD_OR: 3778 case ISD::ATOMIC_LOAD_XOR: 3779 case ISD::ATOMIC_LOAD_NAND: 3780 case ISD::ATOMIC_LOAD_MIN: 3781 case ISD::ATOMIC_LOAD_MAX: 3782 case ISD::ATOMIC_LOAD_UMIN: 3783 case ISD::ATOMIC_LOAD_UMAX: 3784 case ISD::ATOMIC_CMP_SWAP: { 3785 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT(); 3786 RTLIB::Libcall LC = RTLIB::getSYNC(Opc, VT); 3787 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!"); 3788 3789 std::pair<SDValue, SDValue> Tmp = ExpandChainLibCall(LC, Node, false); 3790 Results.push_back(Tmp.first); 3791 Results.push_back(Tmp.second); 3792 break; 3793 } 3794 case ISD::TRAP: { 3795 // If this operation is not supported, lower it to 'abort()' call 3796 TargetLowering::ArgListTy Args; 3797 TargetLowering::CallLoweringInfo CLI(DAG); 3798 CLI.setDebugLoc(dl) 3799 .setChain(Node->getOperand(0)) 3800 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3801 DAG.getExternalSymbol("abort", 3802 TLI.getPointerTy(DAG.getDataLayout())), 3803 std::move(Args), 0); 3804 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 3805 3806 Results.push_back(CallResult.second); 3807 break; 3808 } 3809 case ISD::FMINNUM: 3810 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64, 3811 RTLIB::FMIN_F80, RTLIB::FMIN_F128, 3812 RTLIB::FMIN_PPCF128)); 3813 break; 3814 case ISD::FMAXNUM: 3815 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64, 3816 RTLIB::FMAX_F80, RTLIB::FMAX_F128, 3817 RTLIB::FMAX_PPCF128)); 3818 break; 3819 case ISD::FSQRT: 3820 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64, 3821 RTLIB::SQRT_F80, RTLIB::SQRT_F128, 3822 RTLIB::SQRT_PPCF128)); 3823 break; 3824 case ISD::FSIN: 3825 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64, 3826 RTLIB::SIN_F80, RTLIB::SIN_F128, 3827 RTLIB::SIN_PPCF128)); 3828 break; 3829 case ISD::FCOS: 3830 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64, 3831 RTLIB::COS_F80, RTLIB::COS_F128, 3832 RTLIB::COS_PPCF128)); 3833 break; 3834 case ISD::FSINCOS: 3835 // Expand into sincos libcall. 3836 ExpandSinCosLibCall(Node, Results); 3837 break; 3838 case ISD::FLOG: 3839 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64, 3840 RTLIB::LOG_F80, RTLIB::LOG_F128, 3841 RTLIB::LOG_PPCF128)); 3842 break; 3843 case ISD::FLOG2: 3844 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64, 3845 RTLIB::LOG2_F80, RTLIB::LOG2_F128, 3846 RTLIB::LOG2_PPCF128)); 3847 break; 3848 case ISD::FLOG10: 3849 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64, 3850 RTLIB::LOG10_F80, RTLIB::LOG10_F128, 3851 RTLIB::LOG10_PPCF128)); 3852 break; 3853 case ISD::FEXP: 3854 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64, 3855 RTLIB::EXP_F80, RTLIB::EXP_F128, 3856 RTLIB::EXP_PPCF128)); 3857 break; 3858 case ISD::FEXP2: 3859 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64, 3860 RTLIB::EXP2_F80, RTLIB::EXP2_F128, 3861 RTLIB::EXP2_PPCF128)); 3862 break; 3863 case ISD::FTRUNC: 3864 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64, 3865 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128, 3866 RTLIB::TRUNC_PPCF128)); 3867 break; 3868 case ISD::FFLOOR: 3869 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64, 3870 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128, 3871 RTLIB::FLOOR_PPCF128)); 3872 break; 3873 case ISD::FCEIL: 3874 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64, 3875 RTLIB::CEIL_F80, RTLIB::CEIL_F128, 3876 RTLIB::CEIL_PPCF128)); 3877 break; 3878 case ISD::FRINT: 3879 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64, 3880 RTLIB::RINT_F80, RTLIB::RINT_F128, 3881 RTLIB::RINT_PPCF128)); 3882 break; 3883 case ISD::FNEARBYINT: 3884 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32, 3885 RTLIB::NEARBYINT_F64, 3886 RTLIB::NEARBYINT_F80, 3887 RTLIB::NEARBYINT_F128, 3888 RTLIB::NEARBYINT_PPCF128)); 3889 break; 3890 case ISD::FROUND: 3891 Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32, 3892 RTLIB::ROUND_F64, 3893 RTLIB::ROUND_F80, 3894 RTLIB::ROUND_F128, 3895 RTLIB::ROUND_PPCF128)); 3896 break; 3897 case ISD::FPOWI: 3898 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64, 3899 RTLIB::POWI_F80, RTLIB::POWI_F128, 3900 RTLIB::POWI_PPCF128)); 3901 break; 3902 case ISD::FPOW: 3903 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64, 3904 RTLIB::POW_F80, RTLIB::POW_F128, 3905 RTLIB::POW_PPCF128)); 3906 break; 3907 case ISD::FDIV: 3908 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64, 3909 RTLIB::DIV_F80, RTLIB::DIV_F128, 3910 RTLIB::DIV_PPCF128)); 3911 break; 3912 case ISD::FREM: 3913 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64, 3914 RTLIB::REM_F80, RTLIB::REM_F128, 3915 RTLIB::REM_PPCF128)); 3916 break; 3917 case ISD::FMA: 3918 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64, 3919 RTLIB::FMA_F80, RTLIB::FMA_F128, 3920 RTLIB::FMA_PPCF128)); 3921 break; 3922 case ISD::FADD: 3923 Results.push_back(ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64, 3924 RTLIB::ADD_F80, RTLIB::ADD_F128, 3925 RTLIB::ADD_PPCF128)); 3926 break; 3927 case ISD::FMUL: 3928 Results.push_back(ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64, 3929 RTLIB::MUL_F80, RTLIB::MUL_F128, 3930 RTLIB::MUL_PPCF128)); 3931 break; 3932 case ISD::FP16_TO_FP: 3933 if (Node->getValueType(0) == MVT::f32) { 3934 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false)); 3935 } 3936 break; 3937 case ISD::FP_TO_FP16: { 3938 RTLIB::Libcall LC = 3939 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16); 3940 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16"); 3941 Results.push_back(ExpandLibCall(LC, Node, false)); 3942 break; 3943 } 3944 case ISD::FSUB: 3945 Results.push_back(ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64, 3946 RTLIB::SUB_F80, RTLIB::SUB_F128, 3947 RTLIB::SUB_PPCF128)); 3948 break; 3949 case ISD::SREM: 3950 Results.push_back(ExpandIntLibCall(Node, true, 3951 RTLIB::SREM_I8, 3952 RTLIB::SREM_I16, RTLIB::SREM_I32, 3953 RTLIB::SREM_I64, RTLIB::SREM_I128)); 3954 break; 3955 case ISD::UREM: 3956 Results.push_back(ExpandIntLibCall(Node, false, 3957 RTLIB::UREM_I8, 3958 RTLIB::UREM_I16, RTLIB::UREM_I32, 3959 RTLIB::UREM_I64, RTLIB::UREM_I128)); 3960 break; 3961 case ISD::SDIV: 3962 Results.push_back(ExpandIntLibCall(Node, true, 3963 RTLIB::SDIV_I8, 3964 RTLIB::SDIV_I16, RTLIB::SDIV_I32, 3965 RTLIB::SDIV_I64, RTLIB::SDIV_I128)); 3966 break; 3967 case ISD::UDIV: 3968 Results.push_back(ExpandIntLibCall(Node, false, 3969 RTLIB::UDIV_I8, 3970 RTLIB::UDIV_I16, RTLIB::UDIV_I32, 3971 RTLIB::UDIV_I64, RTLIB::UDIV_I128)); 3972 break; 3973 case ISD::SDIVREM: 3974 case ISD::UDIVREM: 3975 // Expand into divrem libcall 3976 ExpandDivRemLibCall(Node, Results); 3977 break; 3978 case ISD::MUL: 3979 Results.push_back(ExpandIntLibCall(Node, false, 3980 RTLIB::MUL_I8, 3981 RTLIB::MUL_I16, RTLIB::MUL_I32, 3982 RTLIB::MUL_I64, RTLIB::MUL_I128)); 3983 break; 3984 } 3985 3986 // Replace the original node with the legalized result. 3987 if (!Results.empty()) 3988 ReplaceNode(Node, Results.data()); 3989 } 3990 3991 // Determine the vector type to use in place of an original scalar element when 3992 // promoting equally sized vectors. 3993 static MVT getPromotedVectorElementType(const TargetLowering &TLI, 3994 MVT EltVT, MVT NewEltVT) { 3995 unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits(); 3996 MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt); 3997 assert(TLI.isTypeLegal(MidVT) && "unexpected"); 3998 return MidVT; 3999 } 4000 4001 void SelectionDAGLegalize::PromoteNode(SDNode *Node) { 4002 SmallVector<SDValue, 8> Results; 4003 MVT OVT = Node->getSimpleValueType(0); 4004 if (Node->getOpcode() == ISD::UINT_TO_FP || 4005 Node->getOpcode() == ISD::SINT_TO_FP || 4006 Node->getOpcode() == ISD::SETCC || 4007 Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT || 4008 Node->getOpcode() == ISD::INSERT_VECTOR_ELT) { 4009 OVT = Node->getOperand(0).getSimpleValueType(); 4010 } 4011 if (Node->getOpcode() == ISD::BR_CC) 4012 OVT = Node->getOperand(2).getSimpleValueType(); 4013 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT); 4014 SDLoc dl(Node); 4015 SDValue Tmp1, Tmp2, Tmp3; 4016 switch (Node->getOpcode()) { 4017 case ISD::CTTZ: 4018 case ISD::CTTZ_ZERO_UNDEF: 4019 case ISD::CTLZ: 4020 case ISD::CTLZ_ZERO_UNDEF: 4021 case ISD::CTPOP: 4022 // Zero extend the argument. 4023 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0)); 4024 if (Node->getOpcode() == ISD::CTTZ) { 4025 // The count is the same in the promoted type except if the original 4026 // value was zero. This can be handled by setting the bit just off 4027 // the top of the original type. 4028 auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(), 4029 OVT.getSizeInBits()); 4030 Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1, 4031 DAG.getConstant(TopBit, dl, NVT)); 4032 } 4033 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is 4034 // already the correct result. 4035 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4036 if (Node->getOpcode() == ISD::CTLZ || 4037 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) { 4038 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT)) 4039 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1, 4040 DAG.getConstant(NVT.getSizeInBits() - 4041 OVT.getSizeInBits(), dl, NVT)); 4042 } 4043 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4044 break; 4045 case ISD::BSWAP: { 4046 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits(); 4047 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0)); 4048 Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1); 4049 Tmp1 = DAG.getNode( 4050 ISD::SRL, dl, NVT, Tmp1, 4051 DAG.getConstant(DiffBits, dl, 4052 TLI.getShiftAmountTy(NVT, DAG.getDataLayout()))); 4053 Results.push_back(Tmp1); 4054 break; 4055 } 4056 case ISD::FP_TO_UINT: 4057 case ISD::FP_TO_SINT: 4058 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0), 4059 Node->getOpcode() == ISD::FP_TO_SINT, dl); 4060 Results.push_back(Tmp1); 4061 break; 4062 case ISD::UINT_TO_FP: 4063 case ISD::SINT_TO_FP: 4064 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0), 4065 Node->getOpcode() == ISD::SINT_TO_FP, dl); 4066 Results.push_back(Tmp1); 4067 break; 4068 case ISD::VAARG: { 4069 SDValue Chain = Node->getOperand(0); // Get the chain. 4070 SDValue Ptr = Node->getOperand(1); // Get the pointer. 4071 4072 unsigned TruncOp; 4073 if (OVT.isVector()) { 4074 TruncOp = ISD::BITCAST; 4075 } else { 4076 assert(OVT.isInteger() 4077 && "VAARG promotion is supported only for vectors or integer types"); 4078 TruncOp = ISD::TRUNCATE; 4079 } 4080 4081 // Perform the larger operation, then convert back 4082 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2), 4083 Node->getConstantOperandVal(3)); 4084 Chain = Tmp1.getValue(1); 4085 4086 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1); 4087 4088 // Modified the chain result - switch anything that used the old chain to 4089 // use the new one. 4090 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2); 4091 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain); 4092 if (UpdatedNodes) { 4093 UpdatedNodes->insert(Tmp2.getNode()); 4094 UpdatedNodes->insert(Chain.getNode()); 4095 } 4096 ReplacedNode(Node); 4097 break; 4098 } 4099 case ISD::AND: 4100 case ISD::OR: 4101 case ISD::XOR: { 4102 unsigned ExtOp, TruncOp; 4103 if (OVT.isVector()) { 4104 ExtOp = ISD::BITCAST; 4105 TruncOp = ISD::BITCAST; 4106 } else { 4107 assert(OVT.isInteger() && "Cannot promote logic operation"); 4108 ExtOp = ISD::ANY_EXTEND; 4109 TruncOp = ISD::TRUNCATE; 4110 } 4111 // Promote each of the values to the new type. 4112 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4113 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4114 // Perform the larger operation, then convert back 4115 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2); 4116 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1)); 4117 break; 4118 } 4119 case ISD::SELECT: { 4120 unsigned ExtOp, TruncOp; 4121 if (Node->getValueType(0).isVector() || 4122 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) { 4123 ExtOp = ISD::BITCAST; 4124 TruncOp = ISD::BITCAST; 4125 } else if (Node->getValueType(0).isInteger()) { 4126 ExtOp = ISD::ANY_EXTEND; 4127 TruncOp = ISD::TRUNCATE; 4128 } else { 4129 ExtOp = ISD::FP_EXTEND; 4130 TruncOp = ISD::FP_ROUND; 4131 } 4132 Tmp1 = Node->getOperand(0); 4133 // Promote each of the values to the new type. 4134 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4135 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4136 // Perform the larger operation, then round down. 4137 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3); 4138 if (TruncOp != ISD::FP_ROUND) 4139 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1); 4140 else 4141 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1, 4142 DAG.getIntPtrConstant(0, dl)); 4143 Results.push_back(Tmp1); 4144 break; 4145 } 4146 case ISD::VECTOR_SHUFFLE: { 4147 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask(); 4148 4149 // Cast the two input vectors. 4150 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0)); 4151 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1)); 4152 4153 // Convert the shuffle mask to the right # elements. 4154 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask); 4155 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1); 4156 Results.push_back(Tmp1); 4157 break; 4158 } 4159 case ISD::SETCC: { 4160 unsigned ExtOp = ISD::FP_EXTEND; 4161 if (NVT.isInteger()) { 4162 ISD::CondCode CCCode = 4163 cast<CondCodeSDNode>(Node->getOperand(2))->get(); 4164 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4165 } 4166 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4167 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4168 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), 4169 Tmp1, Tmp2, Node->getOperand(2))); 4170 break; 4171 } 4172 case ISD::BR_CC: { 4173 unsigned ExtOp = ISD::FP_EXTEND; 4174 if (NVT.isInteger()) { 4175 ISD::CondCode CCCode = 4176 cast<CondCodeSDNode>(Node->getOperand(1))->get(); 4177 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4178 } 4179 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4180 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3)); 4181 Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), 4182 Node->getOperand(0), Node->getOperand(1), 4183 Tmp1, Tmp2, Node->getOperand(4))); 4184 break; 4185 } 4186 case ISD::FADD: 4187 case ISD::FSUB: 4188 case ISD::FMUL: 4189 case ISD::FDIV: 4190 case ISD::FREM: 4191 case ISD::FMINNUM: 4192 case ISD::FMAXNUM: 4193 case ISD::FPOW: { 4194 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4195 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1)); 4196 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, 4197 Node->getFlags()); 4198 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4199 Tmp3, DAG.getIntPtrConstant(0, dl))); 4200 break; 4201 } 4202 case ISD::FMA: { 4203 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4204 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1)); 4205 Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2)); 4206 Results.push_back( 4207 DAG.getNode(ISD::FP_ROUND, dl, OVT, 4208 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3), 4209 DAG.getIntPtrConstant(0, dl))); 4210 break; 4211 } 4212 case ISD::FCOPYSIGN: 4213 case ISD::FPOWI: { 4214 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4215 Tmp2 = Node->getOperand(1); 4216 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2); 4217 4218 // fcopysign doesn't change anything but the sign bit, so 4219 // (fp_round (fcopysign (fpext a), b)) 4220 // is as precise as 4221 // (fp_round (fpext a)) 4222 // which is a no-op. Mark it as a TRUNCating FP_ROUND. 4223 const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN); 4224 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4225 Tmp3, DAG.getIntPtrConstant(isTrunc, dl))); 4226 break; 4227 } 4228 case ISD::FFLOOR: 4229 case ISD::FCEIL: 4230 case ISD::FRINT: 4231 case ISD::FNEARBYINT: 4232 case ISD::FROUND: 4233 case ISD::FTRUNC: 4234 case ISD::FNEG: 4235 case ISD::FSQRT: 4236 case ISD::FSIN: 4237 case ISD::FCOS: 4238 case ISD::FLOG: 4239 case ISD::FLOG2: 4240 case ISD::FLOG10: 4241 case ISD::FABS: 4242 case ISD::FEXP: 4243 case ISD::FEXP2: { 4244 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4245 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4246 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4247 Tmp2, DAG.getIntPtrConstant(0, dl))); 4248 break; 4249 } 4250 case ISD::BUILD_VECTOR: { 4251 MVT EltVT = OVT.getVectorElementType(); 4252 MVT NewEltVT = NVT.getVectorElementType(); 4253 4254 // Handle bitcasts to a different vector type with the same total bit size 4255 // 4256 // e.g. v2i64 = build_vector i64:x, i64:y => v4i32 4257 // => 4258 // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y)) 4259 4260 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4261 "Invalid promote type for build_vector"); 4262 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4263 4264 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4265 4266 SmallVector<SDValue, 8> NewOps; 4267 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) { 4268 SDValue Op = Node->getOperand(I); 4269 NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op)); 4270 } 4271 4272 SDLoc SL(Node); 4273 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps); 4274 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat); 4275 Results.push_back(CvtVec); 4276 break; 4277 } 4278 case ISD::EXTRACT_VECTOR_ELT: { 4279 MVT EltVT = OVT.getVectorElementType(); 4280 MVT NewEltVT = NVT.getVectorElementType(); 4281 4282 // Handle bitcasts to a different vector type with the same total bit size. 4283 // 4284 // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32 4285 // => 4286 // v4i32:castx = bitcast x:v2i64 4287 // 4288 // i64 = bitcast 4289 // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))), 4290 // (i32 (extract_vector_elt castx, (2 * y + 1))) 4291 // 4292 4293 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4294 "Invalid promote type for extract_vector_elt"); 4295 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4296 4297 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4298 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements(); 4299 4300 SDValue Idx = Node->getOperand(1); 4301 EVT IdxVT = Idx.getValueType(); 4302 SDLoc SL(Node); 4303 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT); 4304 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor); 4305 4306 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0)); 4307 4308 SmallVector<SDValue, 8> NewOps; 4309 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) { 4310 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT); 4311 SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset); 4312 4313 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT, 4314 CastVec, TmpIdx); 4315 NewOps.push_back(Elt); 4316 } 4317 4318 SDValue NewVec = DAG.getNode(ISD::BUILD_VECTOR, SL, MidVT, NewOps); 4319 4320 Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec)); 4321 break; 4322 } 4323 case ISD::INSERT_VECTOR_ELT: { 4324 MVT EltVT = OVT.getVectorElementType(); 4325 MVT NewEltVT = NVT.getVectorElementType(); 4326 4327 // Handle bitcasts to a different vector type with the same total bit size 4328 // 4329 // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32 4330 // => 4331 // v4i32:castx = bitcast x:v2i64 4332 // v2i32:casty = bitcast y:i64 4333 // 4334 // v2i64 = bitcast 4335 // (v4i32 insert_vector_elt 4336 // (v4i32 insert_vector_elt v4i32:castx, 4337 // (extract_vector_elt casty, 0), 2 * z), 4338 // (extract_vector_elt casty, 1), (2 * z + 1)) 4339 4340 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4341 "Invalid promote type for insert_vector_elt"); 4342 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4343 4344 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4345 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements(); 4346 4347 SDValue Val = Node->getOperand(1); 4348 SDValue Idx = Node->getOperand(2); 4349 EVT IdxVT = Idx.getValueType(); 4350 SDLoc SL(Node); 4351 4352 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT); 4353 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor); 4354 4355 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0)); 4356 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val); 4357 4358 SDValue NewVec = CastVec; 4359 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) { 4360 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT); 4361 SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset); 4362 4363 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT, 4364 CastVal, IdxOffset); 4365 4366 NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT, 4367 NewVec, Elt, InEltIdx); 4368 } 4369 4370 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec)); 4371 break; 4372 } 4373 case ISD::SCALAR_TO_VECTOR: { 4374 MVT EltVT = OVT.getVectorElementType(); 4375 MVT NewEltVT = NVT.getVectorElementType(); 4376 4377 // Handle bitcasts to different vector type with the smae total bit size. 4378 // 4379 // e.g. v2i64 = scalar_to_vector x:i64 4380 // => 4381 // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef) 4382 // 4383 4384 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4385 SDValue Val = Node->getOperand(0); 4386 SDLoc SL(Node); 4387 4388 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val); 4389 SDValue Undef = DAG.getUNDEF(MidVT); 4390 4391 SmallVector<SDValue, 8> NewElts; 4392 NewElts.push_back(CastVal); 4393 for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I) 4394 NewElts.push_back(Undef); 4395 4396 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts); 4397 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat); 4398 Results.push_back(CvtVec); 4399 break; 4400 } 4401 } 4402 4403 // Replace the original node with the legalized result. 4404 if (!Results.empty()) 4405 ReplaceNode(Node, Results.data()); 4406 } 4407 4408 /// This is the entry point for the file. 4409 void SelectionDAG::Legalize() { 4410 AssignTopologicalOrder(); 4411 4412 SmallPtrSet<SDNode *, 16> LegalizedNodes; 4413 SelectionDAGLegalize Legalizer(*this, LegalizedNodes); 4414 4415 // Visit all the nodes. We start in topological order, so that we see 4416 // nodes with their original operands intact. Legalization can produce 4417 // new nodes which may themselves need to be legalized. Iterate until all 4418 // nodes have been legalized. 4419 for (;;) { 4420 bool AnyLegalized = false; 4421 for (auto NI = allnodes_end(); NI != allnodes_begin();) { 4422 --NI; 4423 4424 SDNode *N = &*NI; 4425 if (N->use_empty() && N != getRoot().getNode()) { 4426 ++NI; 4427 DeleteNode(N); 4428 continue; 4429 } 4430 4431 if (LegalizedNodes.insert(N).second) { 4432 AnyLegalized = true; 4433 Legalizer.LegalizeOp(N); 4434 4435 if (N->use_empty() && N != getRoot().getNode()) { 4436 ++NI; 4437 DeleteNode(N); 4438 } 4439 } 4440 } 4441 if (!AnyLegalized) 4442 break; 4443 4444 } 4445 4446 // Remove dead nodes now. 4447 RemoveDeadNodes(); 4448 } 4449 4450 bool SelectionDAG::LegalizeOp(SDNode *N, 4451 SmallSetVector<SDNode *, 16> &UpdatedNodes) { 4452 SmallPtrSet<SDNode *, 16> LegalizedNodes; 4453 SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes); 4454 4455 // Directly insert the node in question, and legalize it. This will recurse 4456 // as needed through operands. 4457 LegalizedNodes.insert(N); 4458 Legalizer.LegalizeOp(N); 4459 4460 return LegalizedNodes.count(N); 4461 } 4462