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