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