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