1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===// 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 implements the SelectionDAG class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/SelectionDAG.h" 15 #include "SDNodeDbgValue.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/ADT/SmallPtrSet.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/CodeGen/MachineBasicBlock.h" 23 #include "llvm/CodeGen/MachineConstantPool.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineModuleInfo.h" 26 #include "llvm/IR/CallingConv.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DebugInfo.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/GlobalAlias.h" 33 #include "llvm/IR/GlobalVariable.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/ManagedStatic.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/Mutex.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include "llvm/Target/TargetInstrInfo.h" 43 #include "llvm/Target/TargetIntrinsicInfo.h" 44 #include "llvm/Target/TargetLowering.h" 45 #include "llvm/Target/TargetMachine.h" 46 #include "llvm/Target/TargetOptions.h" 47 #include "llvm/Target/TargetRegisterInfo.h" 48 #include "llvm/Target/TargetSelectionDAGInfo.h" 49 #include <algorithm> 50 #include <cmath> 51 52 using namespace llvm; 53 54 /// makeVTList - Return an instance of the SDVTList struct initialized with the 55 /// specified members. 56 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 57 SDVTList Res = {VTs, NumVTs}; 58 return Res; 59 } 60 61 // Default null implementations of the callbacks. 62 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 63 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 64 65 //===----------------------------------------------------------------------===// 66 // ConstantFPSDNode Class 67 //===----------------------------------------------------------------------===// 68 69 /// isExactlyValue - We don't rely on operator== working on double values, as 70 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 71 /// As such, this method can be used to do an exact bit-for-bit comparison of 72 /// two floating point values. 73 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 74 return getValueAPF().bitwiseIsEqual(V); 75 } 76 77 bool ConstantFPSDNode::isValueValidForType(EVT VT, 78 const APFloat& Val) { 79 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 80 81 // convert modifies in place, so make a copy. 82 APFloat Val2 = APFloat(Val); 83 bool losesInfo; 84 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 85 APFloat::rmNearestTiesToEven, 86 &losesInfo); 87 return !losesInfo; 88 } 89 90 //===----------------------------------------------------------------------===// 91 // ISD Namespace 92 //===----------------------------------------------------------------------===// 93 94 /// isBuildVectorAllOnes - Return true if the specified node is a 95 /// BUILD_VECTOR where all of the elements are ~0 or undef. 96 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 97 // Look through a bit convert. 98 if (N->getOpcode() == ISD::BITCAST) 99 N = N->getOperand(0).getNode(); 100 101 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 102 103 unsigned i = 0, e = N->getNumOperands(); 104 105 // Skip over all of the undef values. 106 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF) 107 ++i; 108 109 // Do not accept an all-undef vector. 110 if (i == e) return false; 111 112 // Do not accept build_vectors that aren't all constants or which have non-~0 113 // elements. We have to be a bit careful here, as the type of the constant 114 // may not be the same as the type of the vector elements due to type 115 // legalization (the elements are promoted to a legal type for the target and 116 // a vector of a type may be legal when the base element type is not). 117 // We only want to check enough bits to cover the vector elements, because 118 // we care if the resultant vector is all ones, not whether the individual 119 // constants are. 120 SDValue NotZero = N->getOperand(i); 121 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 122 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 123 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 124 return false; 125 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 126 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 127 return false; 128 } else 129 return false; 130 131 // Okay, we have at least one ~0 value, check to see if the rest match or are 132 // undefs. Even with the above element type twiddling, this should be OK, as 133 // the same type legalization should have applied to all the elements. 134 for (++i; i != e; ++i) 135 if (N->getOperand(i) != NotZero && 136 N->getOperand(i).getOpcode() != ISD::UNDEF) 137 return false; 138 return true; 139 } 140 141 142 /// isBuildVectorAllZeros - Return true if the specified node is a 143 /// BUILD_VECTOR where all of the elements are 0 or undef. 144 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 145 // Look through a bit convert. 146 if (N->getOpcode() == ISD::BITCAST) 147 N = N->getOperand(0).getNode(); 148 149 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 150 151 unsigned i = 0, e = N->getNumOperands(); 152 153 // Skip over all of the undef values. 154 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF) 155 ++i; 156 157 // Do not accept an all-undef vector. 158 if (i == e) return false; 159 160 // Do not accept build_vectors that aren't all constants or which have non-0 161 // elements. 162 SDValue Zero = N->getOperand(i); 163 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Zero)) { 164 if (!CN->isNullValue()) 165 return false; 166 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Zero)) { 167 if (!CFPN->getValueAPF().isPosZero()) 168 return false; 169 } else 170 return false; 171 172 // Okay, we have at least one 0 value, check to see if the rest match or are 173 // undefs. 174 for (++i; i != e; ++i) 175 if (N->getOperand(i) != Zero && 176 N->getOperand(i).getOpcode() != ISD::UNDEF) 177 return false; 178 return true; 179 } 180 181 /// \brief Return true if the specified node is a BUILD_VECTOR node of 182 /// all ConstantSDNode or undef. 183 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 184 if (N->getOpcode() != ISD::BUILD_VECTOR) 185 return false; 186 187 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 188 SDValue Op = N->getOperand(i); 189 if (Op.getOpcode() == ISD::UNDEF) 190 continue; 191 if (!isa<ConstantSDNode>(Op)) 192 return false; 193 } 194 return true; 195 } 196 197 /// isScalarToVector - Return true if the specified node is a 198 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low 199 /// element is not an undef. 200 bool ISD::isScalarToVector(const SDNode *N) { 201 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) 202 return true; 203 204 if (N->getOpcode() != ISD::BUILD_VECTOR) 205 return false; 206 if (N->getOperand(0).getOpcode() == ISD::UNDEF) 207 return false; 208 unsigned NumElems = N->getNumOperands(); 209 if (NumElems == 1) 210 return false; 211 for (unsigned i = 1; i < NumElems; ++i) { 212 SDValue V = N->getOperand(i); 213 if (V.getOpcode() != ISD::UNDEF) 214 return false; 215 } 216 return true; 217 } 218 219 /// allOperandsUndef - Return true if the node has at least one operand 220 /// and all operands of the specified node are ISD::UNDEF. 221 bool ISD::allOperandsUndef(const SDNode *N) { 222 // Return false if the node has no operands. 223 // This is "logically inconsistent" with the definition of "all" but 224 // is probably the desired behavior. 225 if (N->getNumOperands() == 0) 226 return false; 227 228 for (unsigned i = 0, e = N->getNumOperands(); i != e ; ++i) 229 if (N->getOperand(i).getOpcode() != ISD::UNDEF) 230 return false; 231 232 return true; 233 } 234 235 ISD::NodeType ISD::getExtForLoadExtType(ISD::LoadExtType ExtType) { 236 switch (ExtType) { 237 case ISD::EXTLOAD: 238 return ISD::ANY_EXTEND; 239 case ISD::SEXTLOAD: 240 return ISD::SIGN_EXTEND; 241 case ISD::ZEXTLOAD: 242 return ISD::ZERO_EXTEND; 243 default: 244 break; 245 } 246 247 llvm_unreachable("Invalid LoadExtType"); 248 } 249 250 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X) 251 /// when given the operation for (X op Y). 252 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 253 // To perform this operation, we just need to swap the L and G bits of the 254 // operation. 255 unsigned OldL = (Operation >> 2) & 1; 256 unsigned OldG = (Operation >> 1) & 1; 257 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 258 (OldL << 1) | // New G bit 259 (OldG << 2)); // New L bit. 260 } 261 262 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where 263 /// 'op' is a valid SetCC operation. 264 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) { 265 unsigned Operation = Op; 266 if (isInteger) 267 Operation ^= 7; // Flip L, G, E bits, but not U. 268 else 269 Operation ^= 15; // Flip all of the condition bits. 270 271 if (Operation > ISD::SETTRUE2) 272 Operation &= ~8; // Don't let N and U bits get set. 273 274 return ISD::CondCode(Operation); 275 } 276 277 278 /// isSignedOp - For an integer comparison, return 1 if the comparison is a 279 /// signed operation and 2 if the result is an unsigned comparison. Return zero 280 /// if the operation does not depend on the sign of the input (setne and seteq). 281 static int isSignedOp(ISD::CondCode Opcode) { 282 switch (Opcode) { 283 default: llvm_unreachable("Illegal integer setcc operation!"); 284 case ISD::SETEQ: 285 case ISD::SETNE: return 0; 286 case ISD::SETLT: 287 case ISD::SETLE: 288 case ISD::SETGT: 289 case ISD::SETGE: return 1; 290 case ISD::SETULT: 291 case ISD::SETULE: 292 case ISD::SETUGT: 293 case ISD::SETUGE: return 2; 294 } 295 } 296 297 /// getSetCCOrOperation - Return the result of a logical OR between different 298 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function 299 /// returns SETCC_INVALID if it is not possible to represent the resultant 300 /// comparison. 301 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 302 bool isInteger) { 303 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 304 // Cannot fold a signed integer setcc with an unsigned integer setcc. 305 return ISD::SETCC_INVALID; 306 307 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 308 309 // If the N and U bits get set then the resultant comparison DOES suddenly 310 // care about orderedness, and is true when ordered. 311 if (Op > ISD::SETTRUE2) 312 Op &= ~16; // Clear the U bit if the N bit is set. 313 314 // Canonicalize illegal integer setcc's. 315 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 316 Op = ISD::SETNE; 317 318 return ISD::CondCode(Op); 319 } 320 321 /// getSetCCAndOperation - Return the result of a logical AND between different 322 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This 323 /// function returns zero if it is not possible to represent the resultant 324 /// comparison. 325 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 326 bool isInteger) { 327 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 328 // Cannot fold a signed setcc with an unsigned setcc. 329 return ISD::SETCC_INVALID; 330 331 // Combine all of the condition bits. 332 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 333 334 // Canonicalize illegal integer setcc's. 335 if (isInteger) { 336 switch (Result) { 337 default: break; 338 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 339 case ISD::SETOEQ: // SETEQ & SETU[LG]E 340 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 341 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 342 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 343 } 344 } 345 346 return Result; 347 } 348 349 //===----------------------------------------------------------------------===// 350 // SDNode Profile Support 351 //===----------------------------------------------------------------------===// 352 353 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 354 /// 355 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 356 ID.AddInteger(OpC); 357 } 358 359 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 360 /// solely with their pointer. 361 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 362 ID.AddPointer(VTList.VTs); 363 } 364 365 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 366 /// 367 static void AddNodeIDOperands(FoldingSetNodeID &ID, 368 ArrayRef<SDValue> Ops) { 369 for (auto& Op : Ops) { 370 ID.AddPointer(Op.getNode()); 371 ID.AddInteger(Op.getResNo()); 372 } 373 } 374 375 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 376 /// 377 static void AddNodeIDOperands(FoldingSetNodeID &ID, 378 ArrayRef<SDUse> Ops) { 379 for (auto& Op : Ops) { 380 ID.AddPointer(Op.getNode()); 381 ID.AddInteger(Op.getResNo()); 382 } 383 } 384 385 static void AddBinaryNodeIDCustom(FoldingSetNodeID &ID, bool nuw, bool nsw, 386 bool exact) { 387 ID.AddBoolean(nuw); 388 ID.AddBoolean(nsw); 389 ID.AddBoolean(exact); 390 } 391 392 /// AddBinaryNodeIDCustom - Add BinarySDNodes special infos 393 static void AddBinaryNodeIDCustom(FoldingSetNodeID &ID, unsigned Opcode, 394 bool nuw, bool nsw, bool exact) { 395 if (isBinOpWithFlags(Opcode)) 396 AddBinaryNodeIDCustom(ID, nuw, nsw, exact); 397 } 398 399 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 400 SDVTList VTList, ArrayRef<SDValue> OpList) { 401 AddNodeIDOpcode(ID, OpC); 402 AddNodeIDValueTypes(ID, VTList); 403 AddNodeIDOperands(ID, OpList); 404 } 405 406 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to 407 /// the NodeID data. 408 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 409 switch (N->getOpcode()) { 410 case ISD::TargetExternalSymbol: 411 case ISD::ExternalSymbol: 412 llvm_unreachable("Should only be used on nodes with operands"); 413 default: break; // Normal nodes don't need extra info. 414 case ISD::TargetConstant: 415 case ISD::Constant: { 416 const ConstantSDNode *C = cast<ConstantSDNode>(N); 417 ID.AddPointer(C->getConstantIntValue()); 418 ID.AddBoolean(C->isOpaque()); 419 break; 420 } 421 case ISD::TargetConstantFP: 422 case ISD::ConstantFP: { 423 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 424 break; 425 } 426 case ISD::TargetGlobalAddress: 427 case ISD::GlobalAddress: 428 case ISD::TargetGlobalTLSAddress: 429 case ISD::GlobalTLSAddress: { 430 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 431 ID.AddPointer(GA->getGlobal()); 432 ID.AddInteger(GA->getOffset()); 433 ID.AddInteger(GA->getTargetFlags()); 434 ID.AddInteger(GA->getAddressSpace()); 435 break; 436 } 437 case ISD::BasicBlock: 438 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 439 break; 440 case ISD::Register: 441 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 442 break; 443 case ISD::RegisterMask: 444 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 445 break; 446 case ISD::SRCVALUE: 447 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 448 break; 449 case ISD::FrameIndex: 450 case ISD::TargetFrameIndex: 451 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 452 break; 453 case ISD::JumpTable: 454 case ISD::TargetJumpTable: 455 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 456 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 457 break; 458 case ISD::ConstantPool: 459 case ISD::TargetConstantPool: { 460 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 461 ID.AddInteger(CP->getAlignment()); 462 ID.AddInteger(CP->getOffset()); 463 if (CP->isMachineConstantPoolEntry()) 464 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 465 else 466 ID.AddPointer(CP->getConstVal()); 467 ID.AddInteger(CP->getTargetFlags()); 468 break; 469 } 470 case ISD::TargetIndex: { 471 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 472 ID.AddInteger(TI->getIndex()); 473 ID.AddInteger(TI->getOffset()); 474 ID.AddInteger(TI->getTargetFlags()); 475 break; 476 } 477 case ISD::LOAD: { 478 const LoadSDNode *LD = cast<LoadSDNode>(N); 479 ID.AddInteger(LD->getMemoryVT().getRawBits()); 480 ID.AddInteger(LD->getRawSubclassData()); 481 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 482 break; 483 } 484 case ISD::STORE: { 485 const StoreSDNode *ST = cast<StoreSDNode>(N); 486 ID.AddInteger(ST->getMemoryVT().getRawBits()); 487 ID.AddInteger(ST->getRawSubclassData()); 488 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 489 break; 490 } 491 case ISD::SDIV: 492 case ISD::UDIV: 493 case ISD::SRA: 494 case ISD::SRL: 495 case ISD::MUL: 496 case ISD::ADD: 497 case ISD::SUB: 498 case ISD::SHL: { 499 const BinaryWithFlagsSDNode *BinNode = cast<BinaryWithFlagsSDNode>(N); 500 AddBinaryNodeIDCustom(ID, N->getOpcode(), BinNode->hasNoUnsignedWrap(), 501 BinNode->hasNoSignedWrap(), BinNode->isExact()); 502 break; 503 } 504 case ISD::ATOMIC_CMP_SWAP: 505 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 506 case ISD::ATOMIC_SWAP: 507 case ISD::ATOMIC_LOAD_ADD: 508 case ISD::ATOMIC_LOAD_SUB: 509 case ISD::ATOMIC_LOAD_AND: 510 case ISD::ATOMIC_LOAD_OR: 511 case ISD::ATOMIC_LOAD_XOR: 512 case ISD::ATOMIC_LOAD_NAND: 513 case ISD::ATOMIC_LOAD_MIN: 514 case ISD::ATOMIC_LOAD_MAX: 515 case ISD::ATOMIC_LOAD_UMIN: 516 case ISD::ATOMIC_LOAD_UMAX: 517 case ISD::ATOMIC_LOAD: 518 case ISD::ATOMIC_STORE: { 519 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 520 ID.AddInteger(AT->getMemoryVT().getRawBits()); 521 ID.AddInteger(AT->getRawSubclassData()); 522 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 523 break; 524 } 525 case ISD::PREFETCH: { 526 const MemSDNode *PF = cast<MemSDNode>(N); 527 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 528 break; 529 } 530 case ISD::VECTOR_SHUFFLE: { 531 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 532 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 533 i != e; ++i) 534 ID.AddInteger(SVN->getMaskElt(i)); 535 break; 536 } 537 case ISD::TargetBlockAddress: 538 case ISD::BlockAddress: { 539 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 540 ID.AddPointer(BA->getBlockAddress()); 541 ID.AddInteger(BA->getOffset()); 542 ID.AddInteger(BA->getTargetFlags()); 543 break; 544 } 545 } // end switch (N->getOpcode()) 546 547 // Target specific memory nodes could also have address spaces to check. 548 if (N->isTargetMemoryOpcode()) 549 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 550 } 551 552 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 553 /// data. 554 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 555 AddNodeIDOpcode(ID, N->getOpcode()); 556 // Add the return value info. 557 AddNodeIDValueTypes(ID, N->getVTList()); 558 // Add the operand info. 559 AddNodeIDOperands(ID, makeArrayRef(N->op_begin(), N->op_end())); 560 561 // Handle SDNode leafs with special info. 562 AddNodeIDCustom(ID, N); 563 } 564 565 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in 566 /// the CSE map that carries volatility, temporalness, indexing mode, and 567 /// extension/truncation information. 568 /// 569 static inline unsigned 570 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile, 571 bool isNonTemporal, bool isInvariant) { 572 assert((ConvType & 3) == ConvType && 573 "ConvType may not require more than 2 bits!"); 574 assert((AM & 7) == AM && 575 "AM may not require more than 3 bits!"); 576 return ConvType | 577 (AM << 2) | 578 (isVolatile << 5) | 579 (isNonTemporal << 6) | 580 (isInvariant << 7); 581 } 582 583 //===----------------------------------------------------------------------===// 584 // SelectionDAG Class 585 //===----------------------------------------------------------------------===// 586 587 /// doNotCSE - Return true if CSE should not be performed for this node. 588 static bool doNotCSE(SDNode *N) { 589 if (N->getValueType(0) == MVT::Glue) 590 return true; // Never CSE anything that produces a flag. 591 592 switch (N->getOpcode()) { 593 default: break; 594 case ISD::HANDLENODE: 595 case ISD::EH_LABEL: 596 return true; // Never CSE these nodes. 597 } 598 599 // Check that remaining values produced are not flags. 600 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 601 if (N->getValueType(i) == MVT::Glue) 602 return true; // Never CSE anything that produces a flag. 603 604 return false; 605 } 606 607 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 608 /// SelectionDAG. 609 void SelectionDAG::RemoveDeadNodes() { 610 // Create a dummy node (which is not added to allnodes), that adds a reference 611 // to the root node, preventing it from being deleted. 612 HandleSDNode Dummy(getRoot()); 613 614 SmallVector<SDNode*, 128> DeadNodes; 615 616 // Add all obviously-dead nodes to the DeadNodes worklist. 617 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I) 618 if (I->use_empty()) 619 DeadNodes.push_back(I); 620 621 RemoveDeadNodes(DeadNodes); 622 623 // If the root changed (e.g. it was a dead load, update the root). 624 setRoot(Dummy.getValue()); 625 } 626 627 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 628 /// given list, and any nodes that become unreachable as a result. 629 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 630 631 // Process the worklist, deleting the nodes and adding their uses to the 632 // worklist. 633 while (!DeadNodes.empty()) { 634 SDNode *N = DeadNodes.pop_back_val(); 635 636 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 637 DUL->NodeDeleted(N, nullptr); 638 639 // Take the node out of the appropriate CSE map. 640 RemoveNodeFromCSEMaps(N); 641 642 // Next, brutally remove the operand list. This is safe to do, as there are 643 // no cycles in the graph. 644 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 645 SDUse &Use = *I++; 646 SDNode *Operand = Use.getNode(); 647 Use.set(SDValue()); 648 649 // Now that we removed this operand, see if there are no uses of it left. 650 if (Operand->use_empty()) 651 DeadNodes.push_back(Operand); 652 } 653 654 DeallocateNode(N); 655 } 656 } 657 658 void SelectionDAG::RemoveDeadNode(SDNode *N){ 659 SmallVector<SDNode*, 16> DeadNodes(1, N); 660 661 // Create a dummy node that adds a reference to the root node, preventing 662 // it from being deleted. (This matters if the root is an operand of the 663 // dead node.) 664 HandleSDNode Dummy(getRoot()); 665 666 RemoveDeadNodes(DeadNodes); 667 } 668 669 void SelectionDAG::DeleteNode(SDNode *N) { 670 // First take this out of the appropriate CSE map. 671 RemoveNodeFromCSEMaps(N); 672 673 // Finally, remove uses due to operands of this node, remove from the 674 // AllNodes list, and delete the node. 675 DeleteNodeNotInCSEMaps(N); 676 } 677 678 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 679 assert(N != AllNodes.begin() && "Cannot delete the entry node!"); 680 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 681 682 // Drop all of the operands and decrement used node's use counts. 683 N->DropOperands(); 684 685 DeallocateNode(N); 686 } 687 688 void SelectionDAG::DeallocateNode(SDNode *N) { 689 if (N->OperandsNeedDelete) 690 delete[] N->OperandList; 691 692 // Set the opcode to DELETED_NODE to help catch bugs when node 693 // memory is reallocated. 694 N->NodeType = ISD::DELETED_NODE; 695 696 NodeAllocator.Deallocate(AllNodes.remove(N)); 697 698 // If any of the SDDbgValue nodes refer to this SDNode, invalidate them. 699 ArrayRef<SDDbgValue*> DbgVals = DbgInfo->getSDDbgValues(N); 700 for (unsigned i = 0, e = DbgVals.size(); i != e; ++i) 701 DbgVals[i]->setIsInvalidated(); 702 } 703 704 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 705 /// correspond to it. This is useful when we're about to delete or repurpose 706 /// the node. We don't want future request for structurally identical nodes 707 /// to return N anymore. 708 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 709 bool Erased = false; 710 switch (N->getOpcode()) { 711 case ISD::HANDLENODE: return false; // noop. 712 case ISD::CONDCODE: 713 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 714 "Cond code doesn't exist!"); 715 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 716 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 717 break; 718 case ISD::ExternalSymbol: 719 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 720 break; 721 case ISD::TargetExternalSymbol: { 722 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 723 Erased = TargetExternalSymbols.erase( 724 std::pair<std::string,unsigned char>(ESN->getSymbol(), 725 ESN->getTargetFlags())); 726 break; 727 } 728 case ISD::VALUETYPE: { 729 EVT VT = cast<VTSDNode>(N)->getVT(); 730 if (VT.isExtended()) { 731 Erased = ExtendedValueTypeNodes.erase(VT); 732 } else { 733 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 734 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 735 } 736 break; 737 } 738 default: 739 // Remove it from the CSE Map. 740 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 741 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 742 Erased = CSEMap.RemoveNode(N); 743 break; 744 } 745 #ifndef NDEBUG 746 // Verify that the node was actually in one of the CSE maps, unless it has a 747 // flag result (which cannot be CSE'd) or is one of the special cases that are 748 // not subject to CSE. 749 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 750 !N->isMachineOpcode() && !doNotCSE(N)) { 751 N->dump(this); 752 dbgs() << "\n"; 753 llvm_unreachable("Node is not in map!"); 754 } 755 #endif 756 return Erased; 757 } 758 759 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 760 /// maps and modified in place. Add it back to the CSE maps, unless an identical 761 /// node already exists, in which case transfer all its users to the existing 762 /// node. This transfer can potentially trigger recursive merging. 763 /// 764 void 765 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 766 // For node types that aren't CSE'd, just act as if no identical node 767 // already exists. 768 if (!doNotCSE(N)) { 769 SDNode *Existing = CSEMap.GetOrInsertNode(N); 770 if (Existing != N) { 771 // If there was already an existing matching node, use ReplaceAllUsesWith 772 // to replace the dead one with the existing one. This can cause 773 // recursive merging of other unrelated nodes down the line. 774 ReplaceAllUsesWith(N, Existing); 775 776 // N is now dead. Inform the listeners and delete it. 777 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 778 DUL->NodeDeleted(N, Existing); 779 DeleteNodeNotInCSEMaps(N); 780 return; 781 } 782 } 783 784 // If the node doesn't already exist, we updated it. Inform listeners. 785 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 786 DUL->NodeUpdated(N); 787 } 788 789 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 790 /// were replaced with those specified. If this node is never memoized, 791 /// return null, otherwise return a pointer to the slot it would take. If a 792 /// node already exists with these operands, the slot will be non-null. 793 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 794 void *&InsertPos) { 795 if (doNotCSE(N)) 796 return nullptr; 797 798 SDValue Ops[] = { Op }; 799 FoldingSetNodeID ID; 800 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 801 AddNodeIDCustom(ID, N); 802 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 803 return Node; 804 } 805 806 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 807 /// were replaced with those specified. If this node is never memoized, 808 /// return null, otherwise return a pointer to the slot it would take. If a 809 /// node already exists with these operands, the slot will be non-null. 810 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 811 SDValue Op1, SDValue Op2, 812 void *&InsertPos) { 813 if (doNotCSE(N)) 814 return nullptr; 815 816 SDValue Ops[] = { Op1, Op2 }; 817 FoldingSetNodeID ID; 818 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 819 AddNodeIDCustom(ID, N); 820 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 821 return Node; 822 } 823 824 825 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 826 /// were replaced with those specified. If this node is never memoized, 827 /// return null, otherwise return a pointer to the slot it would take. If a 828 /// node already exists with these operands, the slot will be non-null. 829 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 830 void *&InsertPos) { 831 if (doNotCSE(N)) 832 return nullptr; 833 834 FoldingSetNodeID ID; 835 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 836 AddNodeIDCustom(ID, N); 837 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 838 return Node; 839 } 840 841 #ifndef NDEBUG 842 /// VerifyNodeCommon - Sanity check the given node. Aborts if it is invalid. 843 static void VerifyNodeCommon(SDNode *N) { 844 switch (N->getOpcode()) { 845 default: 846 break; 847 case ISD::BUILD_PAIR: { 848 EVT VT = N->getValueType(0); 849 assert(N->getNumValues() == 1 && "Too many results!"); 850 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 851 "Wrong return type!"); 852 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 853 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 854 "Mismatched operand types!"); 855 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 856 "Wrong operand type!"); 857 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 858 "Wrong return type size"); 859 break; 860 } 861 case ISD::BUILD_VECTOR: { 862 assert(N->getNumValues() == 1 && "Too many results!"); 863 assert(N->getValueType(0).isVector() && "Wrong return type!"); 864 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 865 "Wrong number of operands!"); 866 EVT EltVT = N->getValueType(0).getVectorElementType(); 867 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) { 868 assert((I->getValueType() == EltVT || 869 (EltVT.isInteger() && I->getValueType().isInteger() && 870 EltVT.bitsLE(I->getValueType()))) && 871 "Wrong operand type!"); 872 assert(I->getValueType() == N->getOperand(0).getValueType() && 873 "Operands must all have the same type"); 874 } 875 break; 876 } 877 } 878 } 879 880 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 881 static void VerifySDNode(SDNode *N) { 882 // The SDNode allocators cannot be used to allocate nodes with fields that are 883 // not present in an SDNode! 884 assert(!isa<MemSDNode>(N) && "Bad MemSDNode!"); 885 assert(!isa<ShuffleVectorSDNode>(N) && "Bad ShuffleVectorSDNode!"); 886 assert(!isa<ConstantSDNode>(N) && "Bad ConstantSDNode!"); 887 assert(!isa<ConstantFPSDNode>(N) && "Bad ConstantFPSDNode!"); 888 assert(!isa<GlobalAddressSDNode>(N) && "Bad GlobalAddressSDNode!"); 889 assert(!isa<FrameIndexSDNode>(N) && "Bad FrameIndexSDNode!"); 890 assert(!isa<JumpTableSDNode>(N) && "Bad JumpTableSDNode!"); 891 assert(!isa<ConstantPoolSDNode>(N) && "Bad ConstantPoolSDNode!"); 892 assert(!isa<BasicBlockSDNode>(N) && "Bad BasicBlockSDNode!"); 893 assert(!isa<SrcValueSDNode>(N) && "Bad SrcValueSDNode!"); 894 assert(!isa<MDNodeSDNode>(N) && "Bad MDNodeSDNode!"); 895 assert(!isa<RegisterSDNode>(N) && "Bad RegisterSDNode!"); 896 assert(!isa<BlockAddressSDNode>(N) && "Bad BlockAddressSDNode!"); 897 assert(!isa<EHLabelSDNode>(N) && "Bad EHLabelSDNode!"); 898 assert(!isa<ExternalSymbolSDNode>(N) && "Bad ExternalSymbolSDNode!"); 899 assert(!isa<CondCodeSDNode>(N) && "Bad CondCodeSDNode!"); 900 assert(!isa<CvtRndSatSDNode>(N) && "Bad CvtRndSatSDNode!"); 901 assert(!isa<VTSDNode>(N) && "Bad VTSDNode!"); 902 assert(!isa<MachineSDNode>(N) && "Bad MachineSDNode!"); 903 904 VerifyNodeCommon(N); 905 } 906 907 /// VerifyMachineNode - Sanity check the given MachineNode. Aborts if it is 908 /// invalid. 909 static void VerifyMachineNode(SDNode *N) { 910 // The MachineNode allocators cannot be used to allocate nodes with fields 911 // that are not present in a MachineNode! 912 // Currently there are no such nodes. 913 914 VerifyNodeCommon(N); 915 } 916 #endif // NDEBUG 917 918 /// getEVTAlignment - Compute the default alignment value for the 919 /// given type. 920 /// 921 unsigned SelectionDAG::getEVTAlignment(EVT VT) const { 922 Type *Ty = VT == MVT::iPTR ? 923 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 924 VT.getTypeForEVT(*getContext()); 925 926 return TM.getTargetLowering()->getDataLayout()->getABITypeAlignment(Ty); 927 } 928 929 // EntryNode could meaningfully have debug info if we can find it... 930 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 931 : TM(tm), TSI(*tm.getSelectionDAGInfo()), TLI(nullptr), OptLevel(OL), 932 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 933 Root(getEntryNode()), NewNodesMustHaveLegalTypes(false), 934 UpdateListeners(nullptr) { 935 AllNodes.push_back(&EntryNode); 936 DbgInfo = new SDDbgInfo(); 937 } 938 939 void SelectionDAG::init(MachineFunction &mf, const TargetLowering *tli) { 940 MF = &mf; 941 TLI = tli; 942 Context = &mf.getFunction()->getContext(); 943 } 944 945 SelectionDAG::~SelectionDAG() { 946 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 947 allnodes_clear(); 948 delete DbgInfo; 949 } 950 951 void SelectionDAG::allnodes_clear() { 952 assert(&*AllNodes.begin() == &EntryNode); 953 AllNodes.remove(AllNodes.begin()); 954 while (!AllNodes.empty()) 955 DeallocateNode(AllNodes.begin()); 956 } 957 958 BinarySDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, SDLoc DL, 959 SDVTList VTs, SDValue N1, 960 SDValue N2, bool nuw, bool nsw, 961 bool exact) { 962 if (isBinOpWithFlags(Opcode)) { 963 BinaryWithFlagsSDNode *FN = new (NodeAllocator) BinaryWithFlagsSDNode( 964 Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2); 965 FN->setHasNoUnsignedWrap(nuw); 966 FN->setHasNoSignedWrap(nsw); 967 FN->setIsExact(exact); 968 969 return FN; 970 } 971 972 BinarySDNode *N = new (NodeAllocator) 973 BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2); 974 return N; 975 } 976 977 void SelectionDAG::clear() { 978 allnodes_clear(); 979 OperandAllocator.Reset(); 980 CSEMap.clear(); 981 982 ExtendedValueTypeNodes.clear(); 983 ExternalSymbols.clear(); 984 TargetExternalSymbols.clear(); 985 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 986 static_cast<CondCodeSDNode*>(nullptr)); 987 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 988 static_cast<SDNode*>(nullptr)); 989 990 EntryNode.UseList = nullptr; 991 AllNodes.push_back(&EntryNode); 992 Root = getEntryNode(); 993 DbgInfo->clear(); 994 } 995 996 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) { 997 return VT.bitsGT(Op.getValueType()) ? 998 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 999 getNode(ISD::TRUNCATE, DL, VT, Op); 1000 } 1001 1002 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) { 1003 return VT.bitsGT(Op.getValueType()) ? 1004 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1005 getNode(ISD::TRUNCATE, DL, VT, Op); 1006 } 1007 1008 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) { 1009 return VT.bitsGT(Op.getValueType()) ? 1010 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1011 getNode(ISD::TRUNCATE, DL, VT, Op); 1012 } 1013 1014 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, SDLoc SL, EVT VT) { 1015 if (VT.bitsLE(Op.getValueType())) 1016 return getNode(ISD::TRUNCATE, SL, VT, Op); 1017 1018 TargetLowering::BooleanContent BType = TLI->getBooleanContents(VT.isVector()); 1019 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1020 } 1021 1022 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, SDLoc DL, EVT VT) { 1023 assert(!VT.isVector() && 1024 "getZeroExtendInReg should use the vector element type instead of " 1025 "the vector type!"); 1026 if (Op.getValueType() == VT) return Op; 1027 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 1028 APInt Imm = APInt::getLowBitsSet(BitWidth, 1029 VT.getSizeInBits()); 1030 return getNode(ISD::AND, DL, Op.getValueType(), Op, 1031 getConstant(Imm, Op.getValueType())); 1032 } 1033 1034 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1035 /// 1036 SDValue SelectionDAG::getNOT(SDLoc DL, SDValue Val, EVT VT) { 1037 EVT EltVT = VT.getScalarType(); 1038 SDValue NegOne = 1039 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 1040 return getNode(ISD::XOR, DL, VT, Val, NegOne); 1041 } 1042 1043 SDValue SelectionDAG::getLogicalNOT(SDLoc DL, SDValue Val, EVT VT) { 1044 EVT EltVT = VT.getScalarType(); 1045 SDValue TrueValue; 1046 switch (TLI->getBooleanContents(VT.isVector())) { 1047 case TargetLowering::ZeroOrOneBooleanContent: 1048 case TargetLowering::UndefinedBooleanContent: 1049 TrueValue = getConstant(1, VT); 1050 break; 1051 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1052 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 1053 VT); 1054 break; 1055 } 1056 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1057 } 1058 1059 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT, bool isO) { 1060 EVT EltVT = VT.getScalarType(); 1061 assert((EltVT.getSizeInBits() >= 64 || 1062 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1063 "getConstant with a uint64_t value that doesn't fit in the type!"); 1064 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT, isO); 1065 } 1066 1067 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT, bool isO) 1068 { 1069 return getConstant(*ConstantInt::get(*Context, Val), VT, isT, isO); 1070 } 1071 1072 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT, 1073 bool isO) { 1074 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1075 1076 EVT EltVT = VT.getScalarType(); 1077 const ConstantInt *Elt = &Val; 1078 1079 const TargetLowering *TLI = TM.getTargetLowering(); 1080 1081 // In some cases the vector type is legal but the element type is illegal and 1082 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1083 // inserted value (the type does not need to match the vector element type). 1084 // Any extra bits introduced will be truncated away. 1085 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1086 TargetLowering::TypePromoteInteger) { 1087 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1088 APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits()); 1089 Elt = ConstantInt::get(*getContext(), NewVal); 1090 } 1091 // In other cases the element type is illegal and needs to be expanded, for 1092 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1093 // the value into n parts and use a vector type with n-times the elements. 1094 // Then bitcast to the type requested. 1095 // Legalizing constants too early makes the DAGCombiner's job harder so we 1096 // only legalize if the DAG tells us we must produce legal types. 1097 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1098 TLI->getTypeAction(*getContext(), EltVT) == 1099 TargetLowering::TypeExpandInteger) { 1100 APInt NewVal = Elt->getValue(); 1101 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1102 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1103 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1104 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1105 1106 // Check the temporary vector is the correct size. If this fails then 1107 // getTypeToTransformTo() probably returned a type whose size (in bits) 1108 // isn't a power-of-2 factor of the requested type size. 1109 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1110 1111 SmallVector<SDValue, 2> EltParts; 1112 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) { 1113 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits) 1114 .trunc(ViaEltSizeInBits), 1115 ViaEltVT, isT, isO)); 1116 } 1117 1118 // EltParts is currently in little endian order. If we actually want 1119 // big-endian order then reverse it now. 1120 if (TLI->isBigEndian()) 1121 std::reverse(EltParts.begin(), EltParts.end()); 1122 1123 // The elements must be reversed when the element order is different 1124 // to the endianness of the elements (because the BITCAST is itself a 1125 // vector shuffle in this situation). However, we do not need any code to 1126 // perform this reversal because getConstant() is producing a vector 1127 // splat. 1128 // This situation occurs in MIPS MSA. 1129 1130 SmallVector<SDValue, 8> Ops; 1131 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) 1132 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end()); 1133 1134 SDValue Result = getNode(ISD::BITCAST, SDLoc(), VT, 1135 getNode(ISD::BUILD_VECTOR, SDLoc(), ViaVecVT, 1136 Ops)); 1137 return Result; 1138 } 1139 1140 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1141 "APInt size does not match type size!"); 1142 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1143 FoldingSetNodeID ID; 1144 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1145 ID.AddPointer(Elt); 1146 ID.AddBoolean(isO); 1147 void *IP = nullptr; 1148 SDNode *N = nullptr; 1149 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP))) 1150 if (!VT.isVector()) 1151 return SDValue(N, 0); 1152 1153 if (!N) { 1154 N = new (NodeAllocator) ConstantSDNode(isT, isO, Elt, EltVT); 1155 CSEMap.InsertNode(N, IP); 1156 AllNodes.push_back(N); 1157 } 1158 1159 SDValue Result(N, 0); 1160 if (VT.isVector()) { 1161 SmallVector<SDValue, 8> Ops; 1162 Ops.assign(VT.getVectorNumElements(), Result); 1163 Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Ops); 1164 } 1165 return Result; 1166 } 1167 1168 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) { 1169 return getConstant(Val, TM.getTargetLowering()->getPointerTy(), isTarget); 1170 } 1171 1172 1173 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) { 1174 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget); 1175 } 1176 1177 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){ 1178 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1179 1180 EVT EltVT = VT.getScalarType(); 1181 1182 // Do the map lookup using the actual bit pattern for the floating point 1183 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1184 // we don't have issues with SNANs. 1185 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1186 FoldingSetNodeID ID; 1187 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1188 ID.AddPointer(&V); 1189 void *IP = nullptr; 1190 SDNode *N = nullptr; 1191 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP))) 1192 if (!VT.isVector()) 1193 return SDValue(N, 0); 1194 1195 if (!N) { 1196 N = new (NodeAllocator) ConstantFPSDNode(isTarget, &V, EltVT); 1197 CSEMap.InsertNode(N, IP); 1198 AllNodes.push_back(N); 1199 } 1200 1201 SDValue Result(N, 0); 1202 if (VT.isVector()) { 1203 SmallVector<SDValue, 8> Ops; 1204 Ops.assign(VT.getVectorNumElements(), Result); 1205 // FIXME SDLoc info might be appropriate here 1206 Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Ops); 1207 } 1208 return Result; 1209 } 1210 1211 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) { 1212 EVT EltVT = VT.getScalarType(); 1213 if (EltVT==MVT::f32) 1214 return getConstantFP(APFloat((float)Val), VT, isTarget); 1215 else if (EltVT==MVT::f64) 1216 return getConstantFP(APFloat(Val), VT, isTarget); 1217 else if (EltVT==MVT::f80 || EltVT==MVT::f128 || EltVT==MVT::ppcf128 || 1218 EltVT==MVT::f16) { 1219 bool ignored; 1220 APFloat apf = APFloat(Val); 1221 apf.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1222 &ignored); 1223 return getConstantFP(apf, VT, isTarget); 1224 } else 1225 llvm_unreachable("Unsupported type in getConstantFP"); 1226 } 1227 1228 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, SDLoc DL, 1229 EVT VT, int64_t Offset, 1230 bool isTargetGA, 1231 unsigned char TargetFlags) { 1232 assert((TargetFlags == 0 || isTargetGA) && 1233 "Cannot set target flags on target-independent globals"); 1234 const TargetLowering *TLI = TM.getTargetLowering(); 1235 1236 // Truncate (with sign-extension) the offset value to the pointer size. 1237 unsigned BitWidth = TLI->getPointerTypeSizeInBits(GV->getType()); 1238 if (BitWidth < 64) 1239 Offset = SignExtend64(Offset, BitWidth); 1240 1241 unsigned Opc; 1242 if (GV->isThreadLocal()) 1243 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1244 else 1245 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1246 1247 FoldingSetNodeID ID; 1248 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1249 ID.AddPointer(GV); 1250 ID.AddInteger(Offset); 1251 ID.AddInteger(TargetFlags); 1252 ID.AddInteger(GV->getType()->getAddressSpace()); 1253 void *IP = nullptr; 1254 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1255 return SDValue(E, 0); 1256 1257 SDNode *N = new (NodeAllocator) GlobalAddressSDNode(Opc, DL.getIROrder(), 1258 DL.getDebugLoc(), GV, VT, 1259 Offset, TargetFlags); 1260 CSEMap.InsertNode(N, IP); 1261 AllNodes.push_back(N); 1262 return SDValue(N, 0); 1263 } 1264 1265 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1266 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1267 FoldingSetNodeID ID; 1268 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1269 ID.AddInteger(FI); 1270 void *IP = nullptr; 1271 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1272 return SDValue(E, 0); 1273 1274 SDNode *N = new (NodeAllocator) FrameIndexSDNode(FI, VT, isTarget); 1275 CSEMap.InsertNode(N, IP); 1276 AllNodes.push_back(N); 1277 return SDValue(N, 0); 1278 } 1279 1280 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1281 unsigned char TargetFlags) { 1282 assert((TargetFlags == 0 || isTarget) && 1283 "Cannot set target flags on target-independent jump tables"); 1284 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1285 FoldingSetNodeID ID; 1286 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1287 ID.AddInteger(JTI); 1288 ID.AddInteger(TargetFlags); 1289 void *IP = nullptr; 1290 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1291 return SDValue(E, 0); 1292 1293 SDNode *N = new (NodeAllocator) JumpTableSDNode(JTI, VT, isTarget, 1294 TargetFlags); 1295 CSEMap.InsertNode(N, IP); 1296 AllNodes.push_back(N); 1297 return SDValue(N, 0); 1298 } 1299 1300 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1301 unsigned Alignment, int Offset, 1302 bool isTarget, 1303 unsigned char TargetFlags) { 1304 assert((TargetFlags == 0 || isTarget) && 1305 "Cannot set target flags on target-independent globals"); 1306 if (Alignment == 0) 1307 Alignment = 1308 TM.getTargetLowering()->getDataLayout()->getPrefTypeAlignment(C->getType()); 1309 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1310 FoldingSetNodeID ID; 1311 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1312 ID.AddInteger(Alignment); 1313 ID.AddInteger(Offset); 1314 ID.AddPointer(C); 1315 ID.AddInteger(TargetFlags); 1316 void *IP = nullptr; 1317 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1318 return SDValue(E, 0); 1319 1320 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset, 1321 Alignment, TargetFlags); 1322 CSEMap.InsertNode(N, IP); 1323 AllNodes.push_back(N); 1324 return SDValue(N, 0); 1325 } 1326 1327 1328 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1329 unsigned Alignment, int Offset, 1330 bool isTarget, 1331 unsigned char TargetFlags) { 1332 assert((TargetFlags == 0 || isTarget) && 1333 "Cannot set target flags on target-independent globals"); 1334 if (Alignment == 0) 1335 Alignment = 1336 TM.getTargetLowering()->getDataLayout()->getPrefTypeAlignment(C->getType()); 1337 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1338 FoldingSetNodeID ID; 1339 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1340 ID.AddInteger(Alignment); 1341 ID.AddInteger(Offset); 1342 C->addSelectionDAGCSEId(ID); 1343 ID.AddInteger(TargetFlags); 1344 void *IP = nullptr; 1345 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1346 return SDValue(E, 0); 1347 1348 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset, 1349 Alignment, TargetFlags); 1350 CSEMap.InsertNode(N, IP); 1351 AllNodes.push_back(N); 1352 return SDValue(N, 0); 1353 } 1354 1355 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1356 unsigned char TargetFlags) { 1357 FoldingSetNodeID ID; 1358 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1359 ID.AddInteger(Index); 1360 ID.AddInteger(Offset); 1361 ID.AddInteger(TargetFlags); 1362 void *IP = nullptr; 1363 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1364 return SDValue(E, 0); 1365 1366 SDNode *N = new (NodeAllocator) TargetIndexSDNode(Index, VT, Offset, 1367 TargetFlags); 1368 CSEMap.InsertNode(N, IP); 1369 AllNodes.push_back(N); 1370 return SDValue(N, 0); 1371 } 1372 1373 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1374 FoldingSetNodeID ID; 1375 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1376 ID.AddPointer(MBB); 1377 void *IP = nullptr; 1378 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1379 return SDValue(E, 0); 1380 1381 SDNode *N = new (NodeAllocator) BasicBlockSDNode(MBB); 1382 CSEMap.InsertNode(N, IP); 1383 AllNodes.push_back(N); 1384 return SDValue(N, 0); 1385 } 1386 1387 SDValue SelectionDAG::getValueType(EVT VT) { 1388 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1389 ValueTypeNodes.size()) 1390 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1391 1392 SDNode *&N = VT.isExtended() ? 1393 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1394 1395 if (N) return SDValue(N, 0); 1396 N = new (NodeAllocator) VTSDNode(VT); 1397 AllNodes.push_back(N); 1398 return SDValue(N, 0); 1399 } 1400 1401 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1402 SDNode *&N = ExternalSymbols[Sym]; 1403 if (N) return SDValue(N, 0); 1404 N = new (NodeAllocator) ExternalSymbolSDNode(false, Sym, 0, VT); 1405 AllNodes.push_back(N); 1406 return SDValue(N, 0); 1407 } 1408 1409 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1410 unsigned char TargetFlags) { 1411 SDNode *&N = 1412 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym, 1413 TargetFlags)]; 1414 if (N) return SDValue(N, 0); 1415 N = new (NodeAllocator) ExternalSymbolSDNode(true, Sym, TargetFlags, VT); 1416 AllNodes.push_back(N); 1417 return SDValue(N, 0); 1418 } 1419 1420 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1421 if ((unsigned)Cond >= CondCodeNodes.size()) 1422 CondCodeNodes.resize(Cond+1); 1423 1424 if (!CondCodeNodes[Cond]) { 1425 CondCodeSDNode *N = new (NodeAllocator) CondCodeSDNode(Cond); 1426 CondCodeNodes[Cond] = N; 1427 AllNodes.push_back(N); 1428 } 1429 1430 return SDValue(CondCodeNodes[Cond], 0); 1431 } 1432 1433 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in 1434 // the shuffle mask M that point at N1 to point at N2, and indices that point 1435 // N2 to point at N1. 1436 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) { 1437 std::swap(N1, N2); 1438 int NElts = M.size(); 1439 for (int i = 0; i != NElts; ++i) { 1440 if (M[i] >= NElts) 1441 M[i] -= NElts; 1442 else if (M[i] >= 0) 1443 M[i] += NElts; 1444 } 1445 } 1446 1447 SDValue SelectionDAG::getVectorShuffle(EVT VT, SDLoc dl, SDValue N1, 1448 SDValue N2, const int *Mask) { 1449 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1450 "Invalid VECTOR_SHUFFLE"); 1451 1452 // Canonicalize shuffle undef, undef -> undef 1453 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF) 1454 return getUNDEF(VT); 1455 1456 // Validate that all indices in Mask are within the range of the elements 1457 // input to the shuffle. 1458 unsigned NElts = VT.getVectorNumElements(); 1459 SmallVector<int, 8> MaskVec; 1460 for (unsigned i = 0; i != NElts; ++i) { 1461 assert(Mask[i] < (int)(NElts * 2) && "Index out of range"); 1462 MaskVec.push_back(Mask[i]); 1463 } 1464 1465 // Canonicalize shuffle v, v -> v, undef 1466 if (N1 == N2) { 1467 N2 = getUNDEF(VT); 1468 for (unsigned i = 0; i != NElts; ++i) 1469 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts; 1470 } 1471 1472 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1473 if (N1.getOpcode() == ISD::UNDEF) 1474 commuteShuffle(N1, N2, MaskVec); 1475 1476 // Canonicalize all index into lhs, -> shuffle lhs, undef 1477 // Canonicalize all index into rhs, -> shuffle rhs, undef 1478 bool AllLHS = true, AllRHS = true; 1479 bool N2Undef = N2.getOpcode() == ISD::UNDEF; 1480 for (unsigned i = 0; i != NElts; ++i) { 1481 if (MaskVec[i] >= (int)NElts) { 1482 if (N2Undef) 1483 MaskVec[i] = -1; 1484 else 1485 AllLHS = false; 1486 } else if (MaskVec[i] >= 0) { 1487 AllRHS = false; 1488 } 1489 } 1490 if (AllLHS && AllRHS) 1491 return getUNDEF(VT); 1492 if (AllLHS && !N2Undef) 1493 N2 = getUNDEF(VT); 1494 if (AllRHS) { 1495 N1 = getUNDEF(VT); 1496 commuteShuffle(N1, N2, MaskVec); 1497 } 1498 1499 // If Identity shuffle return that node. 1500 bool Identity = true; 1501 for (unsigned i = 0; i != NElts; ++i) { 1502 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false; 1503 } 1504 if (Identity && NElts) 1505 return N1; 1506 1507 // Shuffling a constant splat doesn't change the result. 1508 if (N2Undef && N1.getOpcode() == ISD::BUILD_VECTOR) 1509 if (cast<BuildVectorSDNode>(N1)->getConstantSplatValue()) 1510 return N1; 1511 1512 FoldingSetNodeID ID; 1513 SDValue Ops[2] = { N1, N2 }; 1514 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1515 for (unsigned i = 0; i != NElts; ++i) 1516 ID.AddInteger(MaskVec[i]); 1517 1518 void* IP = nullptr; 1519 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1520 return SDValue(E, 0); 1521 1522 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1523 // SDNode doesn't have access to it. This memory will be "leaked" when 1524 // the node is deallocated, but recovered when the NodeAllocator is released. 1525 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1526 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int)); 1527 1528 ShuffleVectorSDNode *N = 1529 new (NodeAllocator) ShuffleVectorSDNode(VT, dl.getIROrder(), 1530 dl.getDebugLoc(), N1, N2, 1531 MaskAlloc); 1532 CSEMap.InsertNode(N, IP); 1533 AllNodes.push_back(N); 1534 return SDValue(N, 0); 1535 } 1536 1537 SDValue SelectionDAG::getConvertRndSat(EVT VT, SDLoc dl, 1538 SDValue Val, SDValue DTy, 1539 SDValue STy, SDValue Rnd, SDValue Sat, 1540 ISD::CvtCode Code) { 1541 // If the src and dest types are the same and the conversion is between 1542 // integer types of the same sign or two floats, no conversion is necessary. 1543 if (DTy == STy && 1544 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF)) 1545 return Val; 1546 1547 FoldingSetNodeID ID; 1548 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat }; 1549 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), Ops); 1550 void* IP = nullptr; 1551 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1552 return SDValue(E, 0); 1553 1554 CvtRndSatSDNode *N = new (NodeAllocator) CvtRndSatSDNode(VT, dl.getIROrder(), 1555 dl.getDebugLoc(), 1556 Ops, Code); 1557 CSEMap.InsertNode(N, IP); 1558 AllNodes.push_back(N); 1559 return SDValue(N, 0); 1560 } 1561 1562 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1563 FoldingSetNodeID ID; 1564 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 1565 ID.AddInteger(RegNo); 1566 void *IP = nullptr; 1567 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1568 return SDValue(E, 0); 1569 1570 SDNode *N = new (NodeAllocator) RegisterSDNode(RegNo, VT); 1571 CSEMap.InsertNode(N, IP); 1572 AllNodes.push_back(N); 1573 return SDValue(N, 0); 1574 } 1575 1576 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 1577 FoldingSetNodeID ID; 1578 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 1579 ID.AddPointer(RegMask); 1580 void *IP = nullptr; 1581 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1582 return SDValue(E, 0); 1583 1584 SDNode *N = new (NodeAllocator) RegisterMaskSDNode(RegMask); 1585 CSEMap.InsertNode(N, IP); 1586 AllNodes.push_back(N); 1587 return SDValue(N, 0); 1588 } 1589 1590 SDValue SelectionDAG::getEHLabel(SDLoc dl, SDValue Root, MCSymbol *Label) { 1591 FoldingSetNodeID ID; 1592 SDValue Ops[] = { Root }; 1593 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops); 1594 ID.AddPointer(Label); 1595 void *IP = nullptr; 1596 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1597 return SDValue(E, 0); 1598 1599 SDNode *N = new (NodeAllocator) EHLabelSDNode(dl.getIROrder(), 1600 dl.getDebugLoc(), Root, Label); 1601 CSEMap.InsertNode(N, IP); 1602 AllNodes.push_back(N); 1603 return SDValue(N, 0); 1604 } 1605 1606 1607 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 1608 int64_t Offset, 1609 bool isTarget, 1610 unsigned char TargetFlags) { 1611 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 1612 1613 FoldingSetNodeID ID; 1614 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1615 ID.AddPointer(BA); 1616 ID.AddInteger(Offset); 1617 ID.AddInteger(TargetFlags); 1618 void *IP = nullptr; 1619 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1620 return SDValue(E, 0); 1621 1622 SDNode *N = new (NodeAllocator) BlockAddressSDNode(Opc, VT, BA, Offset, 1623 TargetFlags); 1624 CSEMap.InsertNode(N, IP); 1625 AllNodes.push_back(N); 1626 return SDValue(N, 0); 1627 } 1628 1629 SDValue SelectionDAG::getSrcValue(const Value *V) { 1630 assert((!V || V->getType()->isPointerTy()) && 1631 "SrcValue is not a pointer?"); 1632 1633 FoldingSetNodeID ID; 1634 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 1635 ID.AddPointer(V); 1636 1637 void *IP = nullptr; 1638 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1639 return SDValue(E, 0); 1640 1641 SDNode *N = new (NodeAllocator) SrcValueSDNode(V); 1642 CSEMap.InsertNode(N, IP); 1643 AllNodes.push_back(N); 1644 return SDValue(N, 0); 1645 } 1646 1647 /// getMDNode - Return an MDNodeSDNode which holds an MDNode. 1648 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 1649 FoldingSetNodeID ID; 1650 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 1651 ID.AddPointer(MD); 1652 1653 void *IP = nullptr; 1654 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1655 return SDValue(E, 0); 1656 1657 SDNode *N = new (NodeAllocator) MDNodeSDNode(MD); 1658 CSEMap.InsertNode(N, IP); 1659 AllNodes.push_back(N); 1660 return SDValue(N, 0); 1661 } 1662 1663 /// getAddrSpaceCast - Return an AddrSpaceCastSDNode. 1664 SDValue SelectionDAG::getAddrSpaceCast(SDLoc dl, EVT VT, SDValue Ptr, 1665 unsigned SrcAS, unsigned DestAS) { 1666 SDValue Ops[] = {Ptr}; 1667 FoldingSetNodeID ID; 1668 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 1669 ID.AddInteger(SrcAS); 1670 ID.AddInteger(DestAS); 1671 1672 void *IP = nullptr; 1673 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1674 return SDValue(E, 0); 1675 1676 SDNode *N = new (NodeAllocator) AddrSpaceCastSDNode(dl.getIROrder(), 1677 dl.getDebugLoc(), 1678 VT, Ptr, SrcAS, DestAS); 1679 CSEMap.InsertNode(N, IP); 1680 AllNodes.push_back(N); 1681 return SDValue(N, 0); 1682 } 1683 1684 /// getShiftAmountOperand - Return the specified value casted to 1685 /// the target's desired shift amount type. 1686 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 1687 EVT OpTy = Op.getValueType(); 1688 EVT ShTy = TM.getTargetLowering()->getShiftAmountTy(LHSTy); 1689 if (OpTy == ShTy || OpTy.isVector()) return Op; 1690 1691 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND; 1692 return getNode(Opcode, SDLoc(Op), ShTy, Op); 1693 } 1694 1695 /// CreateStackTemporary - Create a stack temporary, suitable for holding the 1696 /// specified value type. 1697 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 1698 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo(); 1699 unsigned ByteSize = VT.getStoreSize(); 1700 Type *Ty = VT.getTypeForEVT(*getContext()); 1701 const TargetLowering *TLI = TM.getTargetLowering(); 1702 unsigned StackAlign = 1703 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty), minAlign); 1704 1705 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 1706 return getFrameIndex(FrameIdx, TLI->getPointerTy()); 1707 } 1708 1709 /// CreateStackTemporary - Create a stack temporary suitable for holding 1710 /// either of the specified value types. 1711 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 1712 unsigned Bytes = std::max(VT1.getStoreSizeInBits(), 1713 VT2.getStoreSizeInBits())/8; 1714 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 1715 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 1716 const TargetLowering *TLI = TM.getTargetLowering(); 1717 const DataLayout *TD = TLI->getDataLayout(); 1718 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1), 1719 TD->getPrefTypeAlignment(Ty2)); 1720 1721 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo(); 1722 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false); 1723 return getFrameIndex(FrameIdx, TLI->getPointerTy()); 1724 } 1725 1726 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, 1727 SDValue N2, ISD::CondCode Cond, SDLoc dl) { 1728 // These setcc operations always fold. 1729 switch (Cond) { 1730 default: break; 1731 case ISD::SETFALSE: 1732 case ISD::SETFALSE2: return getConstant(0, VT); 1733 case ISD::SETTRUE: 1734 case ISD::SETTRUE2: { 1735 const TargetLowering *TLI = TM.getTargetLowering(); 1736 TargetLowering::BooleanContent Cnt = TLI->getBooleanContents(VT.isVector()); 1737 return getConstant( 1738 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, VT); 1739 } 1740 1741 case ISD::SETOEQ: 1742 case ISD::SETOGT: 1743 case ISD::SETOGE: 1744 case ISD::SETOLT: 1745 case ISD::SETOLE: 1746 case ISD::SETONE: 1747 case ISD::SETO: 1748 case ISD::SETUO: 1749 case ISD::SETUEQ: 1750 case ISD::SETUNE: 1751 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!"); 1752 break; 1753 } 1754 1755 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) { 1756 const APInt &C2 = N2C->getAPIntValue(); 1757 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 1758 const APInt &C1 = N1C->getAPIntValue(); 1759 1760 switch (Cond) { 1761 default: llvm_unreachable("Unknown integer setcc!"); 1762 case ISD::SETEQ: return getConstant(C1 == C2, VT); 1763 case ISD::SETNE: return getConstant(C1 != C2, VT); 1764 case ISD::SETULT: return getConstant(C1.ult(C2), VT); 1765 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT); 1766 case ISD::SETULE: return getConstant(C1.ule(C2), VT); 1767 case ISD::SETUGE: return getConstant(C1.uge(C2), VT); 1768 case ISD::SETLT: return getConstant(C1.slt(C2), VT); 1769 case ISD::SETGT: return getConstant(C1.sgt(C2), VT); 1770 case ISD::SETLE: return getConstant(C1.sle(C2), VT); 1771 case ISD::SETGE: return getConstant(C1.sge(C2), VT); 1772 } 1773 } 1774 } 1775 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) { 1776 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) { 1777 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF()); 1778 switch (Cond) { 1779 default: break; 1780 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 1781 return getUNDEF(VT); 1782 // fall through 1783 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT); 1784 case ISD::SETNE: if (R==APFloat::cmpUnordered) 1785 return getUNDEF(VT); 1786 // fall through 1787 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan || 1788 R==APFloat::cmpLessThan, VT); 1789 case ISD::SETLT: if (R==APFloat::cmpUnordered) 1790 return getUNDEF(VT); 1791 // fall through 1792 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT); 1793 case ISD::SETGT: if (R==APFloat::cmpUnordered) 1794 return getUNDEF(VT); 1795 // fall through 1796 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT); 1797 case ISD::SETLE: if (R==APFloat::cmpUnordered) 1798 return getUNDEF(VT); 1799 // fall through 1800 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan || 1801 R==APFloat::cmpEqual, VT); 1802 case ISD::SETGE: if (R==APFloat::cmpUnordered) 1803 return getUNDEF(VT); 1804 // fall through 1805 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan || 1806 R==APFloat::cmpEqual, VT); 1807 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT); 1808 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT); 1809 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered || 1810 R==APFloat::cmpEqual, VT); 1811 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT); 1812 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered || 1813 R==APFloat::cmpLessThan, VT); 1814 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan || 1815 R==APFloat::cmpUnordered, VT); 1816 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT); 1817 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT); 1818 } 1819 } else { 1820 // Ensure that the constant occurs on the RHS. 1821 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 1822 MVT CompVT = N1.getValueType().getSimpleVT(); 1823 if (!TM.getTargetLowering()->isCondCodeLegal(SwappedCond, CompVT)) 1824 return SDValue(); 1825 1826 return getSetCC(dl, VT, N2, N1, SwappedCond); 1827 } 1828 } 1829 1830 // Could not fold it. 1831 return SDValue(); 1832 } 1833 1834 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 1835 /// use this predicate to simplify operations downstream. 1836 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 1837 // This predicate is not safe for vector operations. 1838 if (Op.getValueType().isVector()) 1839 return false; 1840 1841 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 1842 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth); 1843 } 1844 1845 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 1846 /// this predicate to simplify operations downstream. Mask is known to be zero 1847 /// for bits that V cannot have. 1848 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask, 1849 unsigned Depth) const { 1850 APInt KnownZero, KnownOne; 1851 computeKnownBits(Op, KnownZero, KnownOne, Depth); 1852 return (KnownZero & Mask) == Mask; 1853 } 1854 1855 /// Determine which bits of Op are known to be either zero or one and return 1856 /// them in the KnownZero/KnownOne bitsets. 1857 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero, 1858 APInt &KnownOne, unsigned Depth) const { 1859 const TargetLowering *TLI = TM.getTargetLowering(); 1860 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 1861 1862 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything. 1863 if (Depth == 6) 1864 return; // Limit search depth. 1865 1866 APInt KnownZero2, KnownOne2; 1867 1868 switch (Op.getOpcode()) { 1869 case ISD::Constant: 1870 // We know all of the bits for a constant! 1871 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue(); 1872 KnownZero = ~KnownOne; 1873 break; 1874 case ISD::AND: 1875 // If either the LHS or the RHS are Zero, the result is zero. 1876 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 1877 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 1878 1879 // Output known-1 bits are only known if set in both the LHS & RHS. 1880 KnownOne &= KnownOne2; 1881 // Output known-0 are known to be clear if zero in either the LHS | RHS. 1882 KnownZero |= KnownZero2; 1883 break; 1884 case ISD::OR: 1885 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 1886 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 1887 1888 // Output known-0 bits are only known if clear in both the LHS & RHS. 1889 KnownZero &= KnownZero2; 1890 // Output known-1 are known to be set if set in either the LHS | RHS. 1891 KnownOne |= KnownOne2; 1892 break; 1893 case ISD::XOR: { 1894 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 1895 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 1896 1897 // Output known-0 bits are known if clear or set in both the LHS & RHS. 1898 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 1899 // Output known-1 are known to be set if set in only one of the LHS, RHS. 1900 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 1901 KnownZero = KnownZeroOut; 1902 break; 1903 } 1904 case ISD::MUL: { 1905 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 1906 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 1907 1908 // If low bits are zero in either operand, output low known-0 bits. 1909 // Also compute a conserative estimate for high known-0 bits. 1910 // More trickiness is possible, but this is sufficient for the 1911 // interesting case of alignment computation. 1912 KnownOne.clearAllBits(); 1913 unsigned TrailZ = KnownZero.countTrailingOnes() + 1914 KnownZero2.countTrailingOnes(); 1915 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() + 1916 KnownZero2.countLeadingOnes(), 1917 BitWidth) - BitWidth; 1918 1919 TrailZ = std::min(TrailZ, BitWidth); 1920 LeadZ = std::min(LeadZ, BitWidth); 1921 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) | 1922 APInt::getHighBitsSet(BitWidth, LeadZ); 1923 break; 1924 } 1925 case ISD::UDIV: { 1926 // For the purposes of computing leading zeros we can conservatively 1927 // treat a udiv as a logical right shift by the power of 2 known to 1928 // be less than the denominator. 1929 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 1930 unsigned LeadZ = KnownZero2.countLeadingOnes(); 1931 1932 KnownOne2.clearAllBits(); 1933 KnownZero2.clearAllBits(); 1934 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 1935 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros(); 1936 if (RHSUnknownLeadingOnes != BitWidth) 1937 LeadZ = std::min(BitWidth, 1938 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); 1939 1940 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ); 1941 break; 1942 } 1943 case ISD::SELECT: 1944 computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1); 1945 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 1946 1947 // Only known if known in both the LHS and RHS. 1948 KnownOne &= KnownOne2; 1949 KnownZero &= KnownZero2; 1950 break; 1951 case ISD::SELECT_CC: 1952 computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1); 1953 computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1); 1954 1955 // Only known if known in both the LHS and RHS. 1956 KnownOne &= KnownOne2; 1957 KnownZero &= KnownZero2; 1958 break; 1959 case ISD::SADDO: 1960 case ISD::UADDO: 1961 case ISD::SSUBO: 1962 case ISD::USUBO: 1963 case ISD::SMULO: 1964 case ISD::UMULO: 1965 if (Op.getResNo() != 1) 1966 break; 1967 // The boolean result conforms to getBooleanContents. Fall through. 1968 case ISD::SETCC: 1969 // If we know the result of a setcc has the top bits zero, use this info. 1970 if (TLI->getBooleanContents(Op.getValueType().isVector()) == 1971 TargetLowering::ZeroOrOneBooleanContent && BitWidth > 1) 1972 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 1973 break; 1974 case ISD::SHL: 1975 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0 1976 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1977 unsigned ShAmt = SA->getZExtValue(); 1978 1979 // If the shift count is an invalid immediate, don't do anything. 1980 if (ShAmt >= BitWidth) 1981 break; 1982 1983 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 1984 KnownZero <<= ShAmt; 1985 KnownOne <<= ShAmt; 1986 // low bits known zero. 1987 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt); 1988 } 1989 break; 1990 case ISD::SRL: 1991 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 1992 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1993 unsigned ShAmt = SA->getZExtValue(); 1994 1995 // If the shift count is an invalid immediate, don't do anything. 1996 if (ShAmt >= BitWidth) 1997 break; 1998 1999 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2000 KnownZero = KnownZero.lshr(ShAmt); 2001 KnownOne = KnownOne.lshr(ShAmt); 2002 2003 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 2004 KnownZero |= HighBits; // High bits known zero. 2005 } 2006 break; 2007 case ISD::SRA: 2008 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2009 unsigned ShAmt = SA->getZExtValue(); 2010 2011 // If the shift count is an invalid immediate, don't do anything. 2012 if (ShAmt >= BitWidth) 2013 break; 2014 2015 // If any of the demanded bits are produced by the sign extension, we also 2016 // demand the input sign bit. 2017 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 2018 2019 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2020 KnownZero = KnownZero.lshr(ShAmt); 2021 KnownOne = KnownOne.lshr(ShAmt); 2022 2023 // Handle the sign bits. 2024 APInt SignBit = APInt::getSignBit(BitWidth); 2025 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask. 2026 2027 if (KnownZero.intersects(SignBit)) { 2028 KnownZero |= HighBits; // New bits are known zero. 2029 } else if (KnownOne.intersects(SignBit)) { 2030 KnownOne |= HighBits; // New bits are known one. 2031 } 2032 } 2033 break; 2034 case ISD::SIGN_EXTEND_INREG: { 2035 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2036 unsigned EBits = EVT.getScalarType().getSizeInBits(); 2037 2038 // Sign extension. Compute the demanded bits in the result that are not 2039 // present in the input. 2040 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits); 2041 2042 APInt InSignBit = APInt::getSignBit(EBits); 2043 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits); 2044 2045 // If the sign extended bits are demanded, we know that the sign 2046 // bit is demanded. 2047 InSignBit = InSignBit.zext(BitWidth); 2048 if (NewBits.getBoolValue()) 2049 InputDemandedBits |= InSignBit; 2050 2051 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2052 KnownOne &= InputDemandedBits; 2053 KnownZero &= InputDemandedBits; 2054 2055 // If the sign bit of the input is known set or clear, then we know the 2056 // top bits of the result. 2057 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear 2058 KnownZero |= NewBits; 2059 KnownOne &= ~NewBits; 2060 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 2061 KnownOne |= NewBits; 2062 KnownZero &= ~NewBits; 2063 } else { // Input sign bit unknown 2064 KnownZero &= ~NewBits; 2065 KnownOne &= ~NewBits; 2066 } 2067 break; 2068 } 2069 case ISD::CTTZ: 2070 case ISD::CTTZ_ZERO_UNDEF: 2071 case ISD::CTLZ: 2072 case ISD::CTLZ_ZERO_UNDEF: 2073 case ISD::CTPOP: { 2074 unsigned LowBits = Log2_32(BitWidth)+1; 2075 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits); 2076 KnownOne.clearAllBits(); 2077 break; 2078 } 2079 case ISD::LOAD: { 2080 LoadSDNode *LD = cast<LoadSDNode>(Op); 2081 // If this is a ZEXTLoad and we are looking at the loaded value. 2082 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 2083 EVT VT = LD->getMemoryVT(); 2084 unsigned MemBits = VT.getScalarType().getSizeInBits(); 2085 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 2086 } else if (const MDNode *Ranges = LD->getRanges()) { 2087 computeKnownBitsLoad(*Ranges, KnownZero); 2088 } 2089 break; 2090 } 2091 case ISD::ZERO_EXTEND: { 2092 EVT InVT = Op.getOperand(0).getValueType(); 2093 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2094 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits); 2095 KnownZero = KnownZero.trunc(InBits); 2096 KnownOne = KnownOne.trunc(InBits); 2097 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2098 KnownZero = KnownZero.zext(BitWidth); 2099 KnownOne = KnownOne.zext(BitWidth); 2100 KnownZero |= NewBits; 2101 break; 2102 } 2103 case ISD::SIGN_EXTEND: { 2104 EVT InVT = Op.getOperand(0).getValueType(); 2105 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2106 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits); 2107 2108 KnownZero = KnownZero.trunc(InBits); 2109 KnownOne = KnownOne.trunc(InBits); 2110 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2111 2112 // Note if the sign bit is known to be zero or one. 2113 bool SignBitKnownZero = KnownZero.isNegative(); 2114 bool SignBitKnownOne = KnownOne.isNegative(); 2115 2116 KnownZero = KnownZero.zext(BitWidth); 2117 KnownOne = KnownOne.zext(BitWidth); 2118 2119 // If the sign bit is known zero or one, the top bits match. 2120 if (SignBitKnownZero) 2121 KnownZero |= NewBits; 2122 else if (SignBitKnownOne) 2123 KnownOne |= NewBits; 2124 break; 2125 } 2126 case ISD::ANY_EXTEND: { 2127 EVT InVT = Op.getOperand(0).getValueType(); 2128 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2129 KnownZero = KnownZero.trunc(InBits); 2130 KnownOne = KnownOne.trunc(InBits); 2131 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2132 KnownZero = KnownZero.zext(BitWidth); 2133 KnownOne = KnownOne.zext(BitWidth); 2134 break; 2135 } 2136 case ISD::TRUNCATE: { 2137 EVT InVT = Op.getOperand(0).getValueType(); 2138 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2139 KnownZero = KnownZero.zext(InBits); 2140 KnownOne = KnownOne.zext(InBits); 2141 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2142 KnownZero = KnownZero.trunc(BitWidth); 2143 KnownOne = KnownOne.trunc(BitWidth); 2144 break; 2145 } 2146 case ISD::AssertZext: { 2147 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2148 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 2149 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2150 KnownZero |= (~InMask); 2151 KnownOne &= (~KnownZero); 2152 break; 2153 } 2154 case ISD::FGETSIGN: 2155 // All bits are zero except the low bit. 2156 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2157 break; 2158 2159 case ISD::SUB: { 2160 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) { 2161 // We know that the top bits of C-X are clear if X contains less bits 2162 // than C (i.e. no wrap-around can happen). For example, 20-X is 2163 // positive if we can prove that X is >= 0 and < 16. 2164 if (CLHS->getAPIntValue().isNonNegative()) { 2165 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros(); 2166 // NLZ can't be BitWidth with no sign bit 2167 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1); 2168 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2169 2170 // If all of the MaskV bits are known to be zero, then we know the 2171 // output top bits are zero, because we now know that the output is 2172 // from [0-C]. 2173 if ((KnownZero2 & MaskV) == MaskV) { 2174 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros(); 2175 // Top bits known zero. 2176 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2); 2177 } 2178 } 2179 } 2180 } 2181 // fall through 2182 case ISD::ADD: 2183 case ISD::ADDE: { 2184 // Output known-0 bits are known if clear or set in both the low clear bits 2185 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the 2186 // low 3 bits clear. 2187 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2188 unsigned KnownZeroOut = KnownZero2.countTrailingOnes(); 2189 2190 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2191 KnownZeroOut = std::min(KnownZeroOut, 2192 KnownZero2.countTrailingOnes()); 2193 2194 if (Op.getOpcode() == ISD::ADD) { 2195 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut); 2196 break; 2197 } 2198 2199 // With ADDE, a carry bit may be added in, so we can only use this 2200 // information if we know (at least) that the low two bits are clear. We 2201 // then return to the caller that the low bit is unknown but that other bits 2202 // are known zero. 2203 if (KnownZeroOut >= 2) // ADDE 2204 KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroOut); 2205 break; 2206 } 2207 case ISD::SREM: 2208 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2209 const APInt &RA = Rem->getAPIntValue().abs(); 2210 if (RA.isPowerOf2()) { 2211 APInt LowBits = RA - 1; 2212 computeKnownBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1); 2213 2214 // The low bits of the first operand are unchanged by the srem. 2215 KnownZero = KnownZero2 & LowBits; 2216 KnownOne = KnownOne2 & LowBits; 2217 2218 // If the first operand is non-negative or has all low bits zero, then 2219 // the upper bits are all zero. 2220 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits)) 2221 KnownZero |= ~LowBits; 2222 2223 // If the first operand is negative and not all low bits are zero, then 2224 // the upper bits are all one. 2225 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0)) 2226 KnownOne |= ~LowBits; 2227 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 2228 } 2229 } 2230 break; 2231 case ISD::UREM: { 2232 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2233 const APInt &RA = Rem->getAPIntValue(); 2234 if (RA.isPowerOf2()) { 2235 APInt LowBits = (RA - 1); 2236 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth + 1); 2237 2238 // The upper bits are all zero, the lower ones are unchanged. 2239 KnownZero = KnownZero2 | ~LowBits; 2240 KnownOne = KnownOne2 & LowBits; 2241 break; 2242 } 2243 } 2244 2245 // Since the result is less than or equal to either operand, any leading 2246 // zero bits in either operand must also exist in the result. 2247 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2248 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2249 2250 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(), 2251 KnownZero2.countLeadingOnes()); 2252 KnownOne.clearAllBits(); 2253 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders); 2254 break; 2255 } 2256 case ISD::FrameIndex: 2257 case ISD::TargetFrameIndex: 2258 if (unsigned Align = InferPtrAlignment(Op)) { 2259 // The low bits are known zero if the pointer is aligned. 2260 KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align)); 2261 break; 2262 } 2263 break; 2264 2265 default: 2266 if (Op.getOpcode() < ISD::BUILTIN_OP_END) 2267 break; 2268 // Fallthrough 2269 case ISD::INTRINSIC_WO_CHAIN: 2270 case ISD::INTRINSIC_W_CHAIN: 2271 case ISD::INTRINSIC_VOID: 2272 // Allow the target to implement this method for its nodes. 2273 TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth); 2274 break; 2275 } 2276 2277 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 2278 } 2279 2280 /// ComputeNumSignBits - Return the number of times the sign bit of the 2281 /// register is replicated into the other bits. We know that at least 1 bit 2282 /// is always equal to the sign bit (itself), but other cases can give us 2283 /// information. For example, immediately after an "SRA X, 2", we know that 2284 /// the top 3 bits are all equal to each other, so we return 3. 2285 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{ 2286 const TargetLowering *TLI = TM.getTargetLowering(); 2287 EVT VT = Op.getValueType(); 2288 assert(VT.isInteger() && "Invalid VT!"); 2289 unsigned VTBits = VT.getScalarType().getSizeInBits(); 2290 unsigned Tmp, Tmp2; 2291 unsigned FirstAnswer = 1; 2292 2293 if (Depth == 6) 2294 return 1; // Limit search depth. 2295 2296 switch (Op.getOpcode()) { 2297 default: break; 2298 case ISD::AssertSext: 2299 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2300 return VTBits-Tmp+1; 2301 case ISD::AssertZext: 2302 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2303 return VTBits-Tmp; 2304 2305 case ISD::Constant: { 2306 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue(); 2307 return Val.getNumSignBits(); 2308 } 2309 2310 case ISD::SIGN_EXTEND: 2311 Tmp = 2312 VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 2313 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp; 2314 2315 case ISD::SIGN_EXTEND_INREG: 2316 // Max of the input and what this extends. 2317 Tmp = 2318 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits(); 2319 Tmp = VTBits-Tmp+1; 2320 2321 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2322 return std::max(Tmp, Tmp2); 2323 2324 case ISD::SRA: 2325 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2326 // SRA X, C -> adds C sign bits. 2327 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2328 Tmp += C->getZExtValue(); 2329 if (Tmp > VTBits) Tmp = VTBits; 2330 } 2331 return Tmp; 2332 case ISD::SHL: 2333 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2334 // shl destroys sign bits. 2335 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2336 if (C->getZExtValue() >= VTBits || // Bad shift. 2337 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out. 2338 return Tmp - C->getZExtValue(); 2339 } 2340 break; 2341 case ISD::AND: 2342 case ISD::OR: 2343 case ISD::XOR: // NOT is handled here. 2344 // Logical binary ops preserve the number of sign bits at the worst. 2345 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2346 if (Tmp != 1) { 2347 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2348 FirstAnswer = std::min(Tmp, Tmp2); 2349 // We computed what we know about the sign bits as our first 2350 // answer. Now proceed to the generic code that uses 2351 // computeKnownBits, and pick whichever answer is better. 2352 } 2353 break; 2354 2355 case ISD::SELECT: 2356 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2357 if (Tmp == 1) return 1; // Early out. 2358 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1); 2359 return std::min(Tmp, Tmp2); 2360 2361 case ISD::SADDO: 2362 case ISD::UADDO: 2363 case ISD::SSUBO: 2364 case ISD::USUBO: 2365 case ISD::SMULO: 2366 case ISD::UMULO: 2367 if (Op.getResNo() != 1) 2368 break; 2369 // The boolean result conforms to getBooleanContents. Fall through. 2370 case ISD::SETCC: 2371 // If setcc returns 0/-1, all bits are sign bits. 2372 if (TLI->getBooleanContents(Op.getValueType().isVector()) == 2373 TargetLowering::ZeroOrNegativeOneBooleanContent) 2374 return VTBits; 2375 break; 2376 case ISD::ROTL: 2377 case ISD::ROTR: 2378 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2379 unsigned RotAmt = C->getZExtValue() & (VTBits-1); 2380 2381 // Handle rotate right by N like a rotate left by 32-N. 2382 if (Op.getOpcode() == ISD::ROTR) 2383 RotAmt = (VTBits-RotAmt) & (VTBits-1); 2384 2385 // If we aren't rotating out all of the known-in sign bits, return the 2386 // number that are left. This handles rotl(sext(x), 1) for example. 2387 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2388 if (Tmp > RotAmt+1) return Tmp-RotAmt; 2389 } 2390 break; 2391 case ISD::ADD: 2392 // Add can have at most one carry bit. Thus we know that the output 2393 // is, at worst, one more bit than the inputs. 2394 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2395 if (Tmp == 1) return 1; // Early out. 2396 2397 // Special case decrementing a value (ADD X, -1): 2398 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2399 if (CRHS->isAllOnesValue()) { 2400 APInt KnownZero, KnownOne; 2401 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2402 2403 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2404 // sign bits set. 2405 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue()) 2406 return VTBits; 2407 2408 // If we are subtracting one from a positive number, there is no carry 2409 // out of the result. 2410 if (KnownZero.isNegative()) 2411 return Tmp; 2412 } 2413 2414 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2415 if (Tmp2 == 1) return 1; 2416 return std::min(Tmp, Tmp2)-1; 2417 2418 case ISD::SUB: 2419 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2420 if (Tmp2 == 1) return 1; 2421 2422 // Handle NEG. 2423 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) 2424 if (CLHS->isNullValue()) { 2425 APInt KnownZero, KnownOne; 2426 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2427 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2428 // sign bits set. 2429 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue()) 2430 return VTBits; 2431 2432 // If the input is known to be positive (the sign bit is known clear), 2433 // the output of the NEG has the same number of sign bits as the input. 2434 if (KnownZero.isNegative()) 2435 return Tmp2; 2436 2437 // Otherwise, we treat this like a SUB. 2438 } 2439 2440 // Sub can have at most one carry bit. Thus we know that the output 2441 // is, at worst, one more bit than the inputs. 2442 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2443 if (Tmp == 1) return 1; // Early out. 2444 return std::min(Tmp, Tmp2)-1; 2445 case ISD::TRUNCATE: 2446 // FIXME: it's tricky to do anything useful for this, but it is an important 2447 // case for targets like X86. 2448 break; 2449 } 2450 2451 // If we are looking at the loaded value of the SDNode. 2452 if (Op.getResNo() == 0) { 2453 // Handle LOADX separately here. EXTLOAD case will fallthrough. 2454 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 2455 unsigned ExtType = LD->getExtensionType(); 2456 switch (ExtType) { 2457 default: break; 2458 case ISD::SEXTLOAD: // '17' bits known 2459 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits(); 2460 return VTBits-Tmp+1; 2461 case ISD::ZEXTLOAD: // '16' bits known 2462 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits(); 2463 return VTBits-Tmp; 2464 } 2465 } 2466 } 2467 2468 // Allow the target to implement this method for its nodes. 2469 if (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2470 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2471 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2472 Op.getOpcode() == ISD::INTRINSIC_VOID) { 2473 unsigned NumBits = TLI->ComputeNumSignBitsForTargetNode(Op, *this, Depth); 2474 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits); 2475 } 2476 2477 // Finally, if we can prove that the top bits of the result are 0's or 1's, 2478 // use this information. 2479 APInt KnownZero, KnownOne; 2480 computeKnownBits(Op, KnownZero, KnownOne, Depth); 2481 2482 APInt Mask; 2483 if (KnownZero.isNegative()) { // sign bit is 0 2484 Mask = KnownZero; 2485 } else if (KnownOne.isNegative()) { // sign bit is 1; 2486 Mask = KnownOne; 2487 } else { 2488 // Nothing known. 2489 return FirstAnswer; 2490 } 2491 2492 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine 2493 // the number of identical bits in the top of the input value. 2494 Mask = ~Mask; 2495 Mask <<= Mask.getBitWidth()-VTBits; 2496 // Return # leading zeros. We use 'min' here in case Val was zero before 2497 // shifting. We don't want to return '64' as for an i32 "0". 2498 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros())); 2499 } 2500 2501 /// isBaseWithConstantOffset - Return true if the specified operand is an 2502 /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an 2503 /// ISD::OR with a ConstantSDNode that is guaranteed to have the same 2504 /// semantics as an ADD. This handles the equivalence: 2505 /// X|Cst == X+Cst iff X&Cst = 0. 2506 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 2507 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 2508 !isa<ConstantSDNode>(Op.getOperand(1))) 2509 return false; 2510 2511 if (Op.getOpcode() == ISD::OR && 2512 !MaskedValueIsZero(Op.getOperand(0), 2513 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue())) 2514 return false; 2515 2516 return true; 2517 } 2518 2519 2520 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const { 2521 // If we're told that NaNs won't happen, assume they won't. 2522 if (getTarget().Options.NoNaNsFPMath) 2523 return true; 2524 2525 // If the value is a constant, we can obviously see if it is a NaN or not. 2526 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 2527 return !C->getValueAPF().isNaN(); 2528 2529 // TODO: Recognize more cases here. 2530 2531 return false; 2532 } 2533 2534 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 2535 // If the value is a constant, we can obviously see if it is a zero or not. 2536 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 2537 return !C->isZero(); 2538 2539 // TODO: Recognize more cases here. 2540 switch (Op.getOpcode()) { 2541 default: break; 2542 case ISD::OR: 2543 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2544 return !C->isNullValue(); 2545 break; 2546 } 2547 2548 return false; 2549 } 2550 2551 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 2552 // Check the obvious case. 2553 if (A == B) return true; 2554 2555 // For for negative and positive zero. 2556 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 2557 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 2558 if (CA->isZero() && CB->isZero()) return true; 2559 2560 // Otherwise they may not be equal. 2561 return false; 2562 } 2563 2564 /// getNode - Gets or creates the specified node. 2565 /// 2566 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT) { 2567 FoldingSetNodeID ID; 2568 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 2569 void *IP = nullptr; 2570 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 2571 return SDValue(E, 0); 2572 2573 SDNode *N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), 2574 DL.getDebugLoc(), getVTList(VT)); 2575 CSEMap.InsertNode(N, IP); 2576 2577 AllNodes.push_back(N); 2578 #ifndef NDEBUG 2579 VerifySDNode(N); 2580 #endif 2581 return SDValue(N, 0); 2582 } 2583 2584 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, 2585 EVT VT, SDValue Operand) { 2586 // Constant fold unary operations with an integer constant operand. Even 2587 // opaque constant will be folded, because the folding of unary operations 2588 // doesn't create new constants with different values. Nevertheless, the 2589 // opaque flag is preserved during folding to prevent future folding with 2590 // other constants. 2591 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) { 2592 const APInt &Val = C->getAPIntValue(); 2593 switch (Opcode) { 2594 default: break; 2595 case ISD::SIGN_EXTEND: 2596 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), VT, 2597 C->isTargetOpcode(), C->isOpaque()); 2598 case ISD::ANY_EXTEND: 2599 case ISD::ZERO_EXTEND: 2600 case ISD::TRUNCATE: 2601 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), VT, 2602 C->isTargetOpcode(), C->isOpaque()); 2603 case ISD::UINT_TO_FP: 2604 case ISD::SINT_TO_FP: { 2605 APFloat apf(EVTToAPFloatSemantics(VT), 2606 APInt::getNullValue(VT.getSizeInBits())); 2607 (void)apf.convertFromAPInt(Val, 2608 Opcode==ISD::SINT_TO_FP, 2609 APFloat::rmNearestTiesToEven); 2610 return getConstantFP(apf, VT); 2611 } 2612 case ISD::BITCAST: 2613 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 2614 return getConstantFP(APFloat(APFloat::IEEEsingle, Val), VT); 2615 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 2616 return getConstantFP(APFloat(APFloat::IEEEdouble, Val), VT); 2617 break; 2618 case ISD::BSWAP: 2619 return getConstant(Val.byteSwap(), VT, C->isTargetOpcode(), 2620 C->isOpaque()); 2621 case ISD::CTPOP: 2622 return getConstant(Val.countPopulation(), VT, C->isTargetOpcode(), 2623 C->isOpaque()); 2624 case ISD::CTLZ: 2625 case ISD::CTLZ_ZERO_UNDEF: 2626 return getConstant(Val.countLeadingZeros(), VT, C->isTargetOpcode(), 2627 C->isOpaque()); 2628 case ISD::CTTZ: 2629 case ISD::CTTZ_ZERO_UNDEF: 2630 return getConstant(Val.countTrailingZeros(), VT, C->isTargetOpcode(), 2631 C->isOpaque()); 2632 } 2633 } 2634 2635 // Constant fold unary operations with a floating point constant operand. 2636 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) { 2637 APFloat V = C->getValueAPF(); // make copy 2638 switch (Opcode) { 2639 case ISD::FNEG: 2640 V.changeSign(); 2641 return getConstantFP(V, VT); 2642 case ISD::FABS: 2643 V.clearSign(); 2644 return getConstantFP(V, VT); 2645 case ISD::FCEIL: { 2646 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 2647 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2648 return getConstantFP(V, VT); 2649 break; 2650 } 2651 case ISD::FTRUNC: { 2652 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 2653 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2654 return getConstantFP(V, VT); 2655 break; 2656 } 2657 case ISD::FFLOOR: { 2658 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 2659 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2660 return getConstantFP(V, VT); 2661 break; 2662 } 2663 case ISD::FP_EXTEND: { 2664 bool ignored; 2665 // This can return overflow, underflow, or inexact; we don't care. 2666 // FIXME need to be more flexible about rounding mode. 2667 (void)V.convert(EVTToAPFloatSemantics(VT), 2668 APFloat::rmNearestTiesToEven, &ignored); 2669 return getConstantFP(V, VT); 2670 } 2671 case ISD::FP_TO_SINT: 2672 case ISD::FP_TO_UINT: { 2673 integerPart x[2]; 2674 bool ignored; 2675 assert(integerPartWidth >= 64); 2676 // FIXME need to be more flexible about rounding mode. 2677 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(), 2678 Opcode==ISD::FP_TO_SINT, 2679 APFloat::rmTowardZero, &ignored); 2680 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual 2681 break; 2682 APInt api(VT.getSizeInBits(), x); 2683 return getConstant(api, VT); 2684 } 2685 case ISD::BITCAST: 2686 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 2687 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT); 2688 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 2689 return getConstant(V.bitcastToAPInt().getZExtValue(), VT); 2690 break; 2691 } 2692 } 2693 2694 unsigned OpOpcode = Operand.getNode()->getOpcode(); 2695 switch (Opcode) { 2696 case ISD::TokenFactor: 2697 case ISD::MERGE_VALUES: 2698 case ISD::CONCAT_VECTORS: 2699 return Operand; // Factor, merge or concat of one node? No need. 2700 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 2701 case ISD::FP_EXTEND: 2702 assert(VT.isFloatingPoint() && 2703 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 2704 if (Operand.getValueType() == VT) return Operand; // noop conversion. 2705 assert((!VT.isVector() || 2706 VT.getVectorNumElements() == 2707 Operand.getValueType().getVectorNumElements()) && 2708 "Vector element count mismatch!"); 2709 if (Operand.getOpcode() == ISD::UNDEF) 2710 return getUNDEF(VT); 2711 break; 2712 case ISD::SIGN_EXTEND: 2713 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2714 "Invalid SIGN_EXTEND!"); 2715 if (Operand.getValueType() == VT) return Operand; // noop extension 2716 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) && 2717 "Invalid sext node, dst < src!"); 2718 assert((!VT.isVector() || 2719 VT.getVectorNumElements() == 2720 Operand.getValueType().getVectorNumElements()) && 2721 "Vector element count mismatch!"); 2722 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 2723 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 2724 else if (OpOpcode == ISD::UNDEF) 2725 // sext(undef) = 0, because the top bits will all be the same. 2726 return getConstant(0, VT); 2727 break; 2728 case ISD::ZERO_EXTEND: 2729 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2730 "Invalid ZERO_EXTEND!"); 2731 if (Operand.getValueType() == VT) return Operand; // noop extension 2732 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) && 2733 "Invalid zext node, dst < src!"); 2734 assert((!VT.isVector() || 2735 VT.getVectorNumElements() == 2736 Operand.getValueType().getVectorNumElements()) && 2737 "Vector element count mismatch!"); 2738 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 2739 return getNode(ISD::ZERO_EXTEND, DL, VT, 2740 Operand.getNode()->getOperand(0)); 2741 else if (OpOpcode == ISD::UNDEF) 2742 // zext(undef) = 0, because the top bits will be zero. 2743 return getConstant(0, VT); 2744 break; 2745 case ISD::ANY_EXTEND: 2746 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2747 "Invalid ANY_EXTEND!"); 2748 if (Operand.getValueType() == VT) return Operand; // noop extension 2749 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) && 2750 "Invalid anyext node, dst < src!"); 2751 assert((!VT.isVector() || 2752 VT.getVectorNumElements() == 2753 Operand.getValueType().getVectorNumElements()) && 2754 "Vector element count mismatch!"); 2755 2756 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 2757 OpOpcode == ISD::ANY_EXTEND) 2758 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 2759 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 2760 else if (OpOpcode == ISD::UNDEF) 2761 return getUNDEF(VT); 2762 2763 // (ext (trunx x)) -> x 2764 if (OpOpcode == ISD::TRUNCATE) { 2765 SDValue OpOp = Operand.getNode()->getOperand(0); 2766 if (OpOp.getValueType() == VT) 2767 return OpOp; 2768 } 2769 break; 2770 case ISD::TRUNCATE: 2771 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2772 "Invalid TRUNCATE!"); 2773 if (Operand.getValueType() == VT) return Operand; // noop truncate 2774 assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) && 2775 "Invalid truncate node, src < dst!"); 2776 assert((!VT.isVector() || 2777 VT.getVectorNumElements() == 2778 Operand.getValueType().getVectorNumElements()) && 2779 "Vector element count mismatch!"); 2780 if (OpOpcode == ISD::TRUNCATE) 2781 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 2782 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 2783 OpOpcode == ISD::ANY_EXTEND) { 2784 // If the source is smaller than the dest, we still need an extend. 2785 if (Operand.getNode()->getOperand(0).getValueType().getScalarType() 2786 .bitsLT(VT.getScalarType())) 2787 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 2788 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT)) 2789 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 2790 return Operand.getNode()->getOperand(0); 2791 } 2792 if (OpOpcode == ISD::UNDEF) 2793 return getUNDEF(VT); 2794 break; 2795 case ISD::BITCAST: 2796 // Basic sanity checking. 2797 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits() 2798 && "Cannot BITCAST between types of different sizes!"); 2799 if (VT == Operand.getValueType()) return Operand; // noop conversion. 2800 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 2801 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 2802 if (OpOpcode == ISD::UNDEF) 2803 return getUNDEF(VT); 2804 break; 2805 case ISD::SCALAR_TO_VECTOR: 2806 assert(VT.isVector() && !Operand.getValueType().isVector() && 2807 (VT.getVectorElementType() == Operand.getValueType() || 2808 (VT.getVectorElementType().isInteger() && 2809 Operand.getValueType().isInteger() && 2810 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 2811 "Illegal SCALAR_TO_VECTOR node!"); 2812 if (OpOpcode == ISD::UNDEF) 2813 return getUNDEF(VT); 2814 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 2815 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 2816 isa<ConstantSDNode>(Operand.getOperand(1)) && 2817 Operand.getConstantOperandVal(1) == 0 && 2818 Operand.getOperand(0).getValueType() == VT) 2819 return Operand.getOperand(0); 2820 break; 2821 case ISD::FNEG: 2822 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 2823 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB) 2824 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1), 2825 Operand.getNode()->getOperand(0)); 2826 if (OpOpcode == ISD::FNEG) // --X -> X 2827 return Operand.getNode()->getOperand(0); 2828 break; 2829 case ISD::FABS: 2830 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 2831 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0)); 2832 break; 2833 } 2834 2835 SDNode *N; 2836 SDVTList VTs = getVTList(VT); 2837 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 2838 FoldingSetNodeID ID; 2839 SDValue Ops[1] = { Operand }; 2840 AddNodeIDNode(ID, Opcode, VTs, Ops); 2841 void *IP = nullptr; 2842 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 2843 return SDValue(E, 0); 2844 2845 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), 2846 DL.getDebugLoc(), VTs, Operand); 2847 CSEMap.InsertNode(N, IP); 2848 } else { 2849 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), 2850 DL.getDebugLoc(), VTs, Operand); 2851 } 2852 2853 AllNodes.push_back(N); 2854 #ifndef NDEBUG 2855 VerifySDNode(N); 2856 #endif 2857 return SDValue(N, 0); 2858 } 2859 2860 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, EVT VT, 2861 SDNode *Cst1, SDNode *Cst2) { 2862 // If the opcode is a target-specific ISD node, there's nothing we can 2863 // do here and the operand rules may not line up with the below, so 2864 // bail early. 2865 if (Opcode >= ISD::BUILTIN_OP_END) 2866 return SDValue(); 2867 2868 SmallVector<std::pair<ConstantSDNode *, ConstantSDNode *>, 4> Inputs; 2869 SmallVector<SDValue, 4> Outputs; 2870 EVT SVT = VT.getScalarType(); 2871 2872 ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1); 2873 ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2); 2874 if (Scalar1 && Scalar2 && (Scalar1->isOpaque() || Scalar2->isOpaque())) 2875 return SDValue(); 2876 2877 if (Scalar1 && Scalar2) 2878 // Scalar instruction. 2879 Inputs.push_back(std::make_pair(Scalar1, Scalar2)); 2880 else { 2881 // For vectors extract each constant element into Inputs so we can constant 2882 // fold them individually. 2883 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1); 2884 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2); 2885 if (!BV1 || !BV2) 2886 return SDValue(); 2887 2888 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!"); 2889 2890 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) { 2891 ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I)); 2892 ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I)); 2893 if (!V1 || !V2) // Not a constant, bail. 2894 return SDValue(); 2895 2896 if (V1->isOpaque() || V2->isOpaque()) 2897 return SDValue(); 2898 2899 // Avoid BUILD_VECTOR nodes that perform implicit truncation. 2900 // FIXME: This is valid and could be handled by truncating the APInts. 2901 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT) 2902 return SDValue(); 2903 2904 Inputs.push_back(std::make_pair(V1, V2)); 2905 } 2906 } 2907 2908 // We have a number of constant values, constant fold them element by element. 2909 for (unsigned I = 0, E = Inputs.size(); I != E; ++I) { 2910 const APInt &C1 = Inputs[I].first->getAPIntValue(); 2911 const APInt &C2 = Inputs[I].second->getAPIntValue(); 2912 2913 switch (Opcode) { 2914 case ISD::ADD: 2915 Outputs.push_back(getConstant(C1 + C2, SVT)); 2916 break; 2917 case ISD::SUB: 2918 Outputs.push_back(getConstant(C1 - C2, SVT)); 2919 break; 2920 case ISD::MUL: 2921 Outputs.push_back(getConstant(C1 * C2, SVT)); 2922 break; 2923 case ISD::UDIV: 2924 if (!C2.getBoolValue()) 2925 return SDValue(); 2926 Outputs.push_back(getConstant(C1.udiv(C2), SVT)); 2927 break; 2928 case ISD::UREM: 2929 if (!C2.getBoolValue()) 2930 return SDValue(); 2931 Outputs.push_back(getConstant(C1.urem(C2), SVT)); 2932 break; 2933 case ISD::SDIV: 2934 if (!C2.getBoolValue()) 2935 return SDValue(); 2936 Outputs.push_back(getConstant(C1.sdiv(C2), SVT)); 2937 break; 2938 case ISD::SREM: 2939 if (!C2.getBoolValue()) 2940 return SDValue(); 2941 Outputs.push_back(getConstant(C1.srem(C2), SVT)); 2942 break; 2943 case ISD::AND: 2944 Outputs.push_back(getConstant(C1 & C2, SVT)); 2945 break; 2946 case ISD::OR: 2947 Outputs.push_back(getConstant(C1 | C2, SVT)); 2948 break; 2949 case ISD::XOR: 2950 Outputs.push_back(getConstant(C1 ^ C2, SVT)); 2951 break; 2952 case ISD::SHL: 2953 Outputs.push_back(getConstant(C1 << C2, SVT)); 2954 break; 2955 case ISD::SRL: 2956 Outputs.push_back(getConstant(C1.lshr(C2), SVT)); 2957 break; 2958 case ISD::SRA: 2959 Outputs.push_back(getConstant(C1.ashr(C2), SVT)); 2960 break; 2961 case ISD::ROTL: 2962 Outputs.push_back(getConstant(C1.rotl(C2), SVT)); 2963 break; 2964 case ISD::ROTR: 2965 Outputs.push_back(getConstant(C1.rotr(C2), SVT)); 2966 break; 2967 default: 2968 return SDValue(); 2969 } 2970 } 2971 2972 assert((Scalar1 && Scalar2) || (VT.getVectorNumElements() == Outputs.size() && 2973 "Expected a scalar or vector!")); 2974 2975 // Handle the scalar case first. 2976 if (!VT.isVector()) 2977 return Outputs.back(); 2978 2979 // We may have a vector type but a scalar result. Create a splat. 2980 Outputs.resize(VT.getVectorNumElements(), Outputs.back()); 2981 2982 // Build a big vector out of the scalar elements we generated. 2983 return getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Outputs); 2984 } 2985 2986 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, SDValue N1, 2987 SDValue N2, bool nuw, bool nsw, bool exact) { 2988 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 2989 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 2990 switch (Opcode) { 2991 default: break; 2992 case ISD::TokenFactor: 2993 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 2994 N2.getValueType() == MVT::Other && "Invalid token factor!"); 2995 // Fold trivial token factors. 2996 if (N1.getOpcode() == ISD::EntryToken) return N2; 2997 if (N2.getOpcode() == ISD::EntryToken) return N1; 2998 if (N1 == N2) return N1; 2999 break; 3000 case ISD::CONCAT_VECTORS: 3001 // Concat of UNDEFs is UNDEF. 3002 if (N1.getOpcode() == ISD::UNDEF && 3003 N2.getOpcode() == ISD::UNDEF) 3004 return getUNDEF(VT); 3005 3006 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to 3007 // one big BUILD_VECTOR. 3008 if (N1.getOpcode() == ISD::BUILD_VECTOR && 3009 N2.getOpcode() == ISD::BUILD_VECTOR) { 3010 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), 3011 N1.getNode()->op_end()); 3012 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end()); 3013 return getNode(ISD::BUILD_VECTOR, DL, VT, Elts); 3014 } 3015 break; 3016 case ISD::AND: 3017 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3018 assert(N1.getValueType() == N2.getValueType() && 3019 N1.getValueType() == VT && "Binary operator types must match!"); 3020 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 3021 // worth handling here. 3022 if (N2C && N2C->isNullValue()) 3023 return N2; 3024 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 3025 return N1; 3026 break; 3027 case ISD::OR: 3028 case ISD::XOR: 3029 case ISD::ADD: 3030 case ISD::SUB: 3031 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3032 assert(N1.getValueType() == N2.getValueType() && 3033 N1.getValueType() == VT && "Binary operator types must match!"); 3034 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 3035 // it's worth handling here. 3036 if (N2C && N2C->isNullValue()) 3037 return N1; 3038 break; 3039 case ISD::UDIV: 3040 case ISD::UREM: 3041 case ISD::MULHU: 3042 case ISD::MULHS: 3043 case ISD::MUL: 3044 case ISD::SDIV: 3045 case ISD::SREM: 3046 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3047 assert(N1.getValueType() == N2.getValueType() && 3048 N1.getValueType() == VT && "Binary operator types must match!"); 3049 break; 3050 case ISD::FADD: 3051 case ISD::FSUB: 3052 case ISD::FMUL: 3053 case ISD::FDIV: 3054 case ISD::FREM: 3055 if (getTarget().Options.UnsafeFPMath) { 3056 if (Opcode == ISD::FADD) { 3057 // 0+x --> x 3058 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) 3059 if (CFP->getValueAPF().isZero()) 3060 return N2; 3061 // x+0 --> x 3062 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2)) 3063 if (CFP->getValueAPF().isZero()) 3064 return N1; 3065 } else if (Opcode == ISD::FSUB) { 3066 // x-0 --> x 3067 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2)) 3068 if (CFP->getValueAPF().isZero()) 3069 return N1; 3070 } else if (Opcode == ISD::FMUL) { 3071 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1); 3072 SDValue V = N2; 3073 3074 // If the first operand isn't the constant, try the second 3075 if (!CFP) { 3076 CFP = dyn_cast<ConstantFPSDNode>(N2); 3077 V = N1; 3078 } 3079 3080 if (CFP) { 3081 // 0*x --> 0 3082 if (CFP->isZero()) 3083 return SDValue(CFP,0); 3084 // 1*x --> x 3085 if (CFP->isExactlyValue(1.0)) 3086 return V; 3087 } 3088 } 3089 } 3090 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 3091 assert(N1.getValueType() == N2.getValueType() && 3092 N1.getValueType() == VT && "Binary operator types must match!"); 3093 break; 3094 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 3095 assert(N1.getValueType() == VT && 3096 N1.getValueType().isFloatingPoint() && 3097 N2.getValueType().isFloatingPoint() && 3098 "Invalid FCOPYSIGN!"); 3099 break; 3100 case ISD::SHL: 3101 case ISD::SRA: 3102 case ISD::SRL: 3103 case ISD::ROTL: 3104 case ISD::ROTR: 3105 assert(VT == N1.getValueType() && 3106 "Shift operators return type must be the same as their first arg"); 3107 assert(VT.isInteger() && N2.getValueType().isInteger() && 3108 "Shifts only work on integers"); 3109 assert((!VT.isVector() || VT == N2.getValueType()) && 3110 "Vector shift amounts must be in the same as their first arg"); 3111 // Verify that the shift amount VT is bit enough to hold valid shift 3112 // amounts. This catches things like trying to shift an i1024 value by an 3113 // i8, which is easy to fall into in generic code that uses 3114 // TLI.getShiftAmount(). 3115 assert(N2.getValueType().getSizeInBits() >= 3116 Log2_32_Ceil(N1.getValueType().getSizeInBits()) && 3117 "Invalid use of small shift amount with oversized value!"); 3118 3119 // Always fold shifts of i1 values so the code generator doesn't need to 3120 // handle them. Since we know the size of the shift has to be less than the 3121 // size of the value, the shift/rotate count is guaranteed to be zero. 3122 if (VT == MVT::i1) 3123 return N1; 3124 if (N2C && N2C->isNullValue()) 3125 return N1; 3126 break; 3127 case ISD::FP_ROUND_INREG: { 3128 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3129 assert(VT == N1.getValueType() && "Not an inreg round!"); 3130 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() && 3131 "Cannot FP_ROUND_INREG integer types"); 3132 assert(EVT.isVector() == VT.isVector() && 3133 "FP_ROUND_INREG type should be vector iff the operand " 3134 "type is vector!"); 3135 assert((!EVT.isVector() || 3136 EVT.getVectorNumElements() == VT.getVectorNumElements()) && 3137 "Vector element counts must match in FP_ROUND_INREG"); 3138 assert(EVT.bitsLE(VT) && "Not rounding down!"); 3139 (void)EVT; 3140 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding. 3141 break; 3142 } 3143 case ISD::FP_ROUND: 3144 assert(VT.isFloatingPoint() && 3145 N1.getValueType().isFloatingPoint() && 3146 VT.bitsLE(N1.getValueType()) && 3147 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!"); 3148 if (N1.getValueType() == VT) return N1; // noop conversion. 3149 break; 3150 case ISD::AssertSext: 3151 case ISD::AssertZext: { 3152 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3153 assert(VT == N1.getValueType() && "Not an inreg extend!"); 3154 assert(VT.isInteger() && EVT.isInteger() && 3155 "Cannot *_EXTEND_INREG FP types"); 3156 assert(!EVT.isVector() && 3157 "AssertSExt/AssertZExt type should be the vector element type " 3158 "rather than the vector type!"); 3159 assert(EVT.bitsLE(VT) && "Not extending!"); 3160 if (VT == EVT) return N1; // noop assertion. 3161 break; 3162 } 3163 case ISD::SIGN_EXTEND_INREG: { 3164 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3165 assert(VT == N1.getValueType() && "Not an inreg extend!"); 3166 assert(VT.isInteger() && EVT.isInteger() && 3167 "Cannot *_EXTEND_INREG FP types"); 3168 assert(EVT.isVector() == VT.isVector() && 3169 "SIGN_EXTEND_INREG type should be vector iff the operand " 3170 "type is vector!"); 3171 assert((!EVT.isVector() || 3172 EVT.getVectorNumElements() == VT.getVectorNumElements()) && 3173 "Vector element counts must match in SIGN_EXTEND_INREG"); 3174 assert(EVT.bitsLE(VT) && "Not extending!"); 3175 if (EVT == VT) return N1; // Not actually extending 3176 3177 if (N1C) { 3178 APInt Val = N1C->getAPIntValue(); 3179 unsigned FromBits = EVT.getScalarType().getSizeInBits(); 3180 Val <<= Val.getBitWidth()-FromBits; 3181 Val = Val.ashr(Val.getBitWidth()-FromBits); 3182 return getConstant(Val, VT); 3183 } 3184 break; 3185 } 3186 case ISD::EXTRACT_VECTOR_ELT: 3187 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF. 3188 if (N1.getOpcode() == ISD::UNDEF) 3189 return getUNDEF(VT); 3190 3191 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 3192 // expanding copies of large vectors from registers. 3193 if (N2C && 3194 N1.getOpcode() == ISD::CONCAT_VECTORS && 3195 N1.getNumOperands() > 0) { 3196 unsigned Factor = 3197 N1.getOperand(0).getValueType().getVectorNumElements(); 3198 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 3199 N1.getOperand(N2C->getZExtValue() / Factor), 3200 getConstant(N2C->getZExtValue() % Factor, 3201 N2.getValueType())); 3202 } 3203 3204 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is 3205 // expanding large vector constants. 3206 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) { 3207 SDValue Elt = N1.getOperand(N2C->getZExtValue()); 3208 3209 if (VT != Elt.getValueType()) 3210 // If the vector element type is not legal, the BUILD_VECTOR operands 3211 // are promoted and implicitly truncated, and the result implicitly 3212 // extended. Make that explicit here. 3213 Elt = getAnyExtOrTrunc(Elt, DL, VT); 3214 3215 return Elt; 3216 } 3217 3218 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 3219 // operations are lowered to scalars. 3220 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 3221 // If the indices are the same, return the inserted element else 3222 // if the indices are known different, extract the element from 3223 // the original vector. 3224 SDValue N1Op2 = N1.getOperand(2); 3225 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2.getNode()); 3226 3227 if (N1Op2C && N2C) { 3228 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 3229 if (VT == N1.getOperand(1).getValueType()) 3230 return N1.getOperand(1); 3231 else 3232 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 3233 } 3234 3235 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 3236 } 3237 } 3238 break; 3239 case ISD::EXTRACT_ELEMENT: 3240 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 3241 assert(!N1.getValueType().isVector() && !VT.isVector() && 3242 (N1.getValueType().isInteger() == VT.isInteger()) && 3243 N1.getValueType() != VT && 3244 "Wrong types for EXTRACT_ELEMENT!"); 3245 3246 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 3247 // 64-bit integers into 32-bit parts. Instead of building the extract of 3248 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 3249 if (N1.getOpcode() == ISD::BUILD_PAIR) 3250 return N1.getOperand(N2C->getZExtValue()); 3251 3252 // EXTRACT_ELEMENT of a constant int is also very common. 3253 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3254 unsigned ElementSize = VT.getSizeInBits(); 3255 unsigned Shift = ElementSize * N2C->getZExtValue(); 3256 APInt ShiftedVal = C->getAPIntValue().lshr(Shift); 3257 return getConstant(ShiftedVal.trunc(ElementSize), VT); 3258 } 3259 break; 3260 case ISD::EXTRACT_SUBVECTOR: { 3261 SDValue Index = N2; 3262 if (VT.isSimple() && N1.getValueType().isSimple()) { 3263 assert(VT.isVector() && N1.getValueType().isVector() && 3264 "Extract subvector VTs must be a vectors!"); 3265 assert(VT.getVectorElementType() == 3266 N1.getValueType().getVectorElementType() && 3267 "Extract subvector VTs must have the same element type!"); 3268 assert(VT.getSimpleVT() <= N1.getSimpleValueType() && 3269 "Extract subvector must be from larger vector to smaller vector!"); 3270 3271 if (isa<ConstantSDNode>(Index.getNode())) { 3272 assert((VT.getVectorNumElements() + 3273 cast<ConstantSDNode>(Index.getNode())->getZExtValue() 3274 <= N1.getValueType().getVectorNumElements()) 3275 && "Extract subvector overflow!"); 3276 } 3277 3278 // Trivial extraction. 3279 if (VT.getSimpleVT() == N1.getSimpleValueType()) 3280 return N1; 3281 } 3282 break; 3283 } 3284 } 3285 3286 // Perform trivial constant folding. 3287 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1.getNode(), N2.getNode()); 3288 if (SV.getNode()) return SV; 3289 3290 // Canonicalize constant to RHS if commutative. 3291 if (N1C && !N2C && isCommutativeBinOp(Opcode)) { 3292 std::swap(N1C, N2C); 3293 std::swap(N1, N2); 3294 } 3295 3296 // Constant fold FP operations. 3297 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 3298 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 3299 if (N1CFP) { 3300 if (!N2CFP && isCommutativeBinOp(Opcode)) { 3301 // Canonicalize constant to RHS if commutative. 3302 std::swap(N1CFP, N2CFP); 3303 std::swap(N1, N2); 3304 } else if (N2CFP) { 3305 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF(); 3306 APFloat::opStatus s; 3307 switch (Opcode) { 3308 case ISD::FADD: 3309 s = V1.add(V2, APFloat::rmNearestTiesToEven); 3310 if (s != APFloat::opInvalidOp) 3311 return getConstantFP(V1, VT); 3312 break; 3313 case ISD::FSUB: 3314 s = V1.subtract(V2, APFloat::rmNearestTiesToEven); 3315 if (s!=APFloat::opInvalidOp) 3316 return getConstantFP(V1, VT); 3317 break; 3318 case ISD::FMUL: 3319 s = V1.multiply(V2, APFloat::rmNearestTiesToEven); 3320 if (s!=APFloat::opInvalidOp) 3321 return getConstantFP(V1, VT); 3322 break; 3323 case ISD::FDIV: 3324 s = V1.divide(V2, APFloat::rmNearestTiesToEven); 3325 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero) 3326 return getConstantFP(V1, VT); 3327 break; 3328 case ISD::FREM : 3329 s = V1.mod(V2, APFloat::rmNearestTiesToEven); 3330 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero) 3331 return getConstantFP(V1, VT); 3332 break; 3333 case ISD::FCOPYSIGN: 3334 V1.copySign(V2); 3335 return getConstantFP(V1, VT); 3336 default: break; 3337 } 3338 } 3339 3340 if (Opcode == ISD::FP_ROUND) { 3341 APFloat V = N1CFP->getValueAPF(); // make copy 3342 bool ignored; 3343 // This can return overflow, underflow, or inexact; we don't care. 3344 // FIXME need to be more flexible about rounding mode. 3345 (void)V.convert(EVTToAPFloatSemantics(VT), 3346 APFloat::rmNearestTiesToEven, &ignored); 3347 return getConstantFP(V, VT); 3348 } 3349 } 3350 3351 // Canonicalize an UNDEF to the RHS, even over a constant. 3352 if (N1.getOpcode() == ISD::UNDEF) { 3353 if (isCommutativeBinOp(Opcode)) { 3354 std::swap(N1, N2); 3355 } else { 3356 switch (Opcode) { 3357 case ISD::FP_ROUND_INREG: 3358 case ISD::SIGN_EXTEND_INREG: 3359 case ISD::SUB: 3360 case ISD::FSUB: 3361 case ISD::FDIV: 3362 case ISD::FREM: 3363 case ISD::SRA: 3364 return N1; // fold op(undef, arg2) -> undef 3365 case ISD::UDIV: 3366 case ISD::SDIV: 3367 case ISD::UREM: 3368 case ISD::SREM: 3369 case ISD::SRL: 3370 case ISD::SHL: 3371 if (!VT.isVector()) 3372 return getConstant(0, VT); // fold op(undef, arg2) -> 0 3373 // For vectors, we can't easily build an all zero vector, just return 3374 // the LHS. 3375 return N2; 3376 } 3377 } 3378 } 3379 3380 // Fold a bunch of operators when the RHS is undef. 3381 if (N2.getOpcode() == ISD::UNDEF) { 3382 switch (Opcode) { 3383 case ISD::XOR: 3384 if (N1.getOpcode() == ISD::UNDEF) 3385 // Handle undef ^ undef -> 0 special case. This is a common 3386 // idiom (misuse). 3387 return getConstant(0, VT); 3388 // fallthrough 3389 case ISD::ADD: 3390 case ISD::ADDC: 3391 case ISD::ADDE: 3392 case ISD::SUB: 3393 case ISD::UDIV: 3394 case ISD::SDIV: 3395 case ISD::UREM: 3396 case ISD::SREM: 3397 return N2; // fold op(arg1, undef) -> undef 3398 case ISD::FADD: 3399 case ISD::FSUB: 3400 case ISD::FMUL: 3401 case ISD::FDIV: 3402 case ISD::FREM: 3403 if (getTarget().Options.UnsafeFPMath) 3404 return N2; 3405 break; 3406 case ISD::MUL: 3407 case ISD::AND: 3408 case ISD::SRL: 3409 case ISD::SHL: 3410 if (!VT.isVector()) 3411 return getConstant(0, VT); // fold op(arg1, undef) -> 0 3412 // For vectors, we can't easily build an all zero vector, just return 3413 // the LHS. 3414 return N1; 3415 case ISD::OR: 3416 if (!VT.isVector()) 3417 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT); 3418 // For vectors, we can't easily build an all one vector, just return 3419 // the LHS. 3420 return N1; 3421 case ISD::SRA: 3422 return N1; 3423 } 3424 } 3425 3426 // Memoize this node if possible. 3427 BinarySDNode *N; 3428 SDVTList VTs = getVTList(VT); 3429 const bool BinOpHasFlags = isBinOpWithFlags(Opcode); 3430 if (VT != MVT::Glue) { 3431 SDValue Ops[] = {N1, N2}; 3432 FoldingSetNodeID ID; 3433 AddNodeIDNode(ID, Opcode, VTs, Ops); 3434 if (BinOpHasFlags) 3435 AddBinaryNodeIDCustom(ID, Opcode, nuw, nsw, exact); 3436 void *IP = nullptr; 3437 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3438 return SDValue(E, 0); 3439 3440 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, nuw, nsw, exact); 3441 3442 CSEMap.InsertNode(N, IP); 3443 } else { 3444 3445 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, nuw, nsw, exact); 3446 } 3447 3448 AllNodes.push_back(N); 3449 #ifndef NDEBUG 3450 VerifySDNode(N); 3451 #endif 3452 return SDValue(N, 0); 3453 } 3454 3455 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, 3456 SDValue N1, SDValue N2, SDValue N3) { 3457 // Perform various simplifications. 3458 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 3459 switch (Opcode) { 3460 case ISD::FMA: { 3461 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3462 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 3463 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 3464 if (N1CFP && N2CFP && N3CFP) { 3465 APFloat V1 = N1CFP->getValueAPF(); 3466 const APFloat &V2 = N2CFP->getValueAPF(); 3467 const APFloat &V3 = N3CFP->getValueAPF(); 3468 APFloat::opStatus s = 3469 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 3470 if (s != APFloat::opInvalidOp) 3471 return getConstantFP(V1, VT); 3472 } 3473 break; 3474 } 3475 case ISD::CONCAT_VECTORS: 3476 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to 3477 // one big BUILD_VECTOR. 3478 if (N1.getOpcode() == ISD::BUILD_VECTOR && 3479 N2.getOpcode() == ISD::BUILD_VECTOR && 3480 N3.getOpcode() == ISD::BUILD_VECTOR) { 3481 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), 3482 N1.getNode()->op_end()); 3483 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end()); 3484 Elts.append(N3.getNode()->op_begin(), N3.getNode()->op_end()); 3485 return getNode(ISD::BUILD_VECTOR, DL, VT, Elts); 3486 } 3487 break; 3488 case ISD::SETCC: { 3489 // Use FoldSetCC to simplify SETCC's. 3490 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL); 3491 if (Simp.getNode()) return Simp; 3492 break; 3493 } 3494 case ISD::SELECT: 3495 if (N1C) { 3496 if (N1C->getZExtValue()) 3497 return N2; // select true, X, Y -> X 3498 return N3; // select false, X, Y -> Y 3499 } 3500 3501 if (N2 == N3) return N2; // select C, X, X -> X 3502 break; 3503 case ISD::VECTOR_SHUFFLE: 3504 llvm_unreachable("should use getVectorShuffle constructor!"); 3505 case ISD::INSERT_SUBVECTOR: { 3506 SDValue Index = N3; 3507 if (VT.isSimple() && N1.getValueType().isSimple() 3508 && N2.getValueType().isSimple()) { 3509 assert(VT.isVector() && N1.getValueType().isVector() && 3510 N2.getValueType().isVector() && 3511 "Insert subvector VTs must be a vectors"); 3512 assert(VT == N1.getValueType() && 3513 "Dest and insert subvector source types must match!"); 3514 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() && 3515 "Insert subvector must be from smaller vector to larger vector!"); 3516 if (isa<ConstantSDNode>(Index.getNode())) { 3517 assert((N2.getValueType().getVectorNumElements() + 3518 cast<ConstantSDNode>(Index.getNode())->getZExtValue() 3519 <= VT.getVectorNumElements()) 3520 && "Insert subvector overflow!"); 3521 } 3522 3523 // Trivial insertion. 3524 if (VT.getSimpleVT() == N2.getSimpleValueType()) 3525 return N2; 3526 } 3527 break; 3528 } 3529 case ISD::BITCAST: 3530 // Fold bit_convert nodes from a type to themselves. 3531 if (N1.getValueType() == VT) 3532 return N1; 3533 break; 3534 } 3535 3536 // Memoize node if it doesn't produce a flag. 3537 SDNode *N; 3538 SDVTList VTs = getVTList(VT); 3539 if (VT != MVT::Glue) { 3540 SDValue Ops[] = { N1, N2, N3 }; 3541 FoldingSetNodeID ID; 3542 AddNodeIDNode(ID, Opcode, VTs, Ops); 3543 void *IP = nullptr; 3544 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3545 return SDValue(E, 0); 3546 3547 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), 3548 DL.getDebugLoc(), VTs, N1, N2, N3); 3549 CSEMap.InsertNode(N, IP); 3550 } else { 3551 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), 3552 DL.getDebugLoc(), VTs, N1, N2, N3); 3553 } 3554 3555 AllNodes.push_back(N); 3556 #ifndef NDEBUG 3557 VerifySDNode(N); 3558 #endif 3559 return SDValue(N, 0); 3560 } 3561 3562 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, 3563 SDValue N1, SDValue N2, SDValue N3, 3564 SDValue N4) { 3565 SDValue Ops[] = { N1, N2, N3, N4 }; 3566 return getNode(Opcode, DL, VT, Ops); 3567 } 3568 3569 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, 3570 SDValue N1, SDValue N2, SDValue N3, 3571 SDValue N4, SDValue N5) { 3572 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 3573 return getNode(Opcode, DL, VT, Ops); 3574 } 3575 3576 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 3577 /// the incoming stack arguments to be loaded from the stack. 3578 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 3579 SmallVector<SDValue, 8> ArgChains; 3580 3581 // Include the original chain at the beginning of the list. When this is 3582 // used by target LowerCall hooks, this helps legalize find the 3583 // CALLSEQ_BEGIN node. 3584 ArgChains.push_back(Chain); 3585 3586 // Add a chain value for each stack argument. 3587 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 3588 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 3589 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 3590 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 3591 if (FI->getIndex() < 0) 3592 ArgChains.push_back(SDValue(L, 1)); 3593 3594 // Build a tokenfactor for all the chains. 3595 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 3596 } 3597 3598 /// getMemsetValue - Vectorized representation of the memset value 3599 /// operand. 3600 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 3601 SDLoc dl) { 3602 assert(Value.getOpcode() != ISD::UNDEF); 3603 3604 unsigned NumBits = VT.getScalarType().getSizeInBits(); 3605 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 3606 assert(C->getAPIntValue().getBitWidth() == 8); 3607 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 3608 if (VT.isInteger()) 3609 return DAG.getConstant(Val, VT); 3610 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), VT); 3611 } 3612 3613 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value); 3614 if (NumBits > 8) { 3615 // Use a multiplication with 0x010101... to extend the input to the 3616 // required length. 3617 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 3618 Value = DAG.getNode(ISD::MUL, dl, VT, Value, DAG.getConstant(Magic, VT)); 3619 } 3620 3621 return Value; 3622 } 3623 3624 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 3625 /// used when a memcpy is turned into a memset when the source is a constant 3626 /// string ptr. 3627 static SDValue getMemsetStringVal(EVT VT, SDLoc dl, SelectionDAG &DAG, 3628 const TargetLowering &TLI, StringRef Str) { 3629 // Handle vector with all elements zero. 3630 if (Str.empty()) { 3631 if (VT.isInteger()) 3632 return DAG.getConstant(0, VT); 3633 else if (VT == MVT::f32 || VT == MVT::f64) 3634 return DAG.getConstantFP(0.0, VT); 3635 else if (VT.isVector()) { 3636 unsigned NumElts = VT.getVectorNumElements(); 3637 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 3638 return DAG.getNode(ISD::BITCAST, dl, VT, 3639 DAG.getConstant(0, EVT::getVectorVT(*DAG.getContext(), 3640 EltVT, NumElts))); 3641 } else 3642 llvm_unreachable("Expected type!"); 3643 } 3644 3645 assert(!VT.isVector() && "Can't handle vector type here!"); 3646 unsigned NumVTBits = VT.getSizeInBits(); 3647 unsigned NumVTBytes = NumVTBits / 8; 3648 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size())); 3649 3650 APInt Val(NumVTBits, 0); 3651 if (TLI.isLittleEndian()) { 3652 for (unsigned i = 0; i != NumBytes; ++i) 3653 Val |= (uint64_t)(unsigned char)Str[i] << i*8; 3654 } else { 3655 for (unsigned i = 0; i != NumBytes; ++i) 3656 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8; 3657 } 3658 3659 // If the "cost" of materializing the integer immediate is less than the cost 3660 // of a load, then it is cost effective to turn the load into the immediate. 3661 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 3662 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 3663 return DAG.getConstant(Val, VT); 3664 return SDValue(nullptr, 0); 3665 } 3666 3667 /// getMemBasePlusOffset - Returns base and offset node for the 3668 /// 3669 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset, SDLoc dl, 3670 SelectionDAG &DAG) { 3671 EVT VT = Base.getValueType(); 3672 return DAG.getNode(ISD::ADD, dl, 3673 VT, Base, DAG.getConstant(Offset, VT)); 3674 } 3675 3676 /// isMemSrcFromString - Returns true if memcpy source is a string constant. 3677 /// 3678 static bool isMemSrcFromString(SDValue Src, StringRef &Str) { 3679 unsigned SrcDelta = 0; 3680 GlobalAddressSDNode *G = nullptr; 3681 if (Src.getOpcode() == ISD::GlobalAddress) 3682 G = cast<GlobalAddressSDNode>(Src); 3683 else if (Src.getOpcode() == ISD::ADD && 3684 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 3685 Src.getOperand(1).getOpcode() == ISD::Constant) { 3686 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 3687 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 3688 } 3689 if (!G) 3690 return false; 3691 3692 return getConstantStringInfo(G->getGlobal(), Str, SrcDelta, false); 3693 } 3694 3695 /// FindOptimalMemOpLowering - Determines the optimial series memory ops 3696 /// to replace the memset / memcpy. Return true if the number of memory ops 3697 /// is below the threshold. It returns the types of the sequence of 3698 /// memory ops to perform memset / memcpy by reference. 3699 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps, 3700 unsigned Limit, uint64_t Size, 3701 unsigned DstAlign, unsigned SrcAlign, 3702 bool IsMemset, 3703 bool ZeroMemset, 3704 bool MemcpyStrSrc, 3705 bool AllowOverlap, 3706 SelectionDAG &DAG, 3707 const TargetLowering &TLI) { 3708 assert((SrcAlign == 0 || SrcAlign >= DstAlign) && 3709 "Expecting memcpy / memset source to meet alignment requirement!"); 3710 // If 'SrcAlign' is zero, that means the memory operation does not need to 3711 // load the value, i.e. memset or memcpy from constant string. Otherwise, 3712 // it's the inferred alignment of the source. 'DstAlign', on the other hand, 3713 // is the specified alignment of the memory operation. If it is zero, that 3714 // means it's possible to change the alignment of the destination. 3715 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does 3716 // not need to be loaded. 3717 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign, 3718 IsMemset, ZeroMemset, MemcpyStrSrc, 3719 DAG.getMachineFunction()); 3720 3721 if (VT == MVT::Other) { 3722 unsigned AS = 0; 3723 if (DstAlign >= TLI.getDataLayout()->getPointerPrefAlignment(AS) || 3724 TLI.allowsUnalignedMemoryAccesses(VT, AS)) { 3725 VT = TLI.getPointerTy(); 3726 } else { 3727 switch (DstAlign & 7) { 3728 case 0: VT = MVT::i64; break; 3729 case 4: VT = MVT::i32; break; 3730 case 2: VT = MVT::i16; break; 3731 default: VT = MVT::i8; break; 3732 } 3733 } 3734 3735 MVT LVT = MVT::i64; 3736 while (!TLI.isTypeLegal(LVT)) 3737 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 3738 assert(LVT.isInteger()); 3739 3740 if (VT.bitsGT(LVT)) 3741 VT = LVT; 3742 } 3743 3744 unsigned NumMemOps = 0; 3745 while (Size != 0) { 3746 unsigned VTSize = VT.getSizeInBits() / 8; 3747 while (VTSize > Size) { 3748 // For now, only use non-vector load / store's for the left-over pieces. 3749 EVT NewVT = VT; 3750 unsigned NewVTSize; 3751 3752 bool Found = false; 3753 if (VT.isVector() || VT.isFloatingPoint()) { 3754 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 3755 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) && 3756 TLI.isSafeMemOpType(NewVT.getSimpleVT())) 3757 Found = true; 3758 else if (NewVT == MVT::i64 && 3759 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 3760 TLI.isSafeMemOpType(MVT::f64)) { 3761 // i64 is usually not legal on 32-bit targets, but f64 may be. 3762 NewVT = MVT::f64; 3763 Found = true; 3764 } 3765 } 3766 3767 if (!Found) { 3768 do { 3769 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 3770 if (NewVT == MVT::i8) 3771 break; 3772 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT())); 3773 } 3774 NewVTSize = NewVT.getSizeInBits() / 8; 3775 3776 // If the new VT cannot cover all of the remaining bits, then consider 3777 // issuing a (or a pair of) unaligned and overlapping load / store. 3778 // FIXME: Only does this for 64-bit or more since we don't have proper 3779 // cost model for unaligned load / store. 3780 bool Fast; 3781 unsigned AS = 0; 3782 if (NumMemOps && AllowOverlap && 3783 VTSize >= 8 && NewVTSize < Size && 3784 TLI.allowsUnalignedMemoryAccesses(VT, AS, &Fast) && Fast) 3785 VTSize = Size; 3786 else { 3787 VT = NewVT; 3788 VTSize = NewVTSize; 3789 } 3790 } 3791 3792 if (++NumMemOps > Limit) 3793 return false; 3794 3795 MemOps.push_back(VT); 3796 Size -= VTSize; 3797 } 3798 3799 return true; 3800 } 3801 3802 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, SDLoc dl, 3803 SDValue Chain, SDValue Dst, 3804 SDValue Src, uint64_t Size, 3805 unsigned Align, bool isVol, 3806 bool AlwaysInline, 3807 MachinePointerInfo DstPtrInfo, 3808 MachinePointerInfo SrcPtrInfo) { 3809 // Turn a memcpy of undef to nop. 3810 if (Src.getOpcode() == ISD::UNDEF) 3811 return Chain; 3812 3813 // Expand memcpy to a series of load and store ops if the size operand falls 3814 // below a certain threshold. 3815 // TODO: In the AlwaysInline case, if the size is big then generate a loop 3816 // rather than maybe a humongous number of loads and stores. 3817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3818 std::vector<EVT> MemOps; 3819 bool DstAlignCanChange = false; 3820 MachineFunction &MF = DAG.getMachineFunction(); 3821 MachineFrameInfo *MFI = MF.getFrameInfo(); 3822 bool OptSize = 3823 MF.getFunction()->getAttributes(). 3824 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize); 3825 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 3826 if (FI && !MFI->isFixedObjectIndex(FI->getIndex())) 3827 DstAlignCanChange = true; 3828 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 3829 if (Align > SrcAlign) 3830 SrcAlign = Align; 3831 StringRef Str; 3832 bool CopyFromStr = isMemSrcFromString(Src, Str); 3833 bool isZeroStr = CopyFromStr && Str.empty(); 3834 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 3835 3836 if (!FindOptimalMemOpLowering(MemOps, Limit, Size, 3837 (DstAlignCanChange ? 0 : Align), 3838 (isZeroStr ? 0 : SrcAlign), 3839 false, false, CopyFromStr, true, DAG, TLI)) 3840 return SDValue(); 3841 3842 if (DstAlignCanChange) { 3843 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 3844 unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty); 3845 3846 // Don't promote to an alignment that would require dynamic stack 3847 // realignment. 3848 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo(); 3849 if (!TRI->needsStackRealignment(MF)) 3850 while (NewAlign > Align && 3851 TLI.getDataLayout()->exceedsNaturalStackAlignment(NewAlign)) 3852 NewAlign /= 2; 3853 3854 if (NewAlign > Align) { 3855 // Give the stack frame object a larger alignment if needed. 3856 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign) 3857 MFI->setObjectAlignment(FI->getIndex(), NewAlign); 3858 Align = NewAlign; 3859 } 3860 } 3861 3862 SmallVector<SDValue, 8> OutChains; 3863 unsigned NumMemOps = MemOps.size(); 3864 uint64_t SrcOff = 0, DstOff = 0; 3865 for (unsigned i = 0; i != NumMemOps; ++i) { 3866 EVT VT = MemOps[i]; 3867 unsigned VTSize = VT.getSizeInBits() / 8; 3868 SDValue Value, Store; 3869 3870 if (VTSize > Size) { 3871 // Issuing an unaligned load / store pair that overlaps with the previous 3872 // pair. Adjust the offset accordingly. 3873 assert(i == NumMemOps-1 && i != 0); 3874 SrcOff -= VTSize - Size; 3875 DstOff -= VTSize - Size; 3876 } 3877 3878 if (CopyFromStr && 3879 (isZeroStr || (VT.isInteger() && !VT.isVector()))) { 3880 // It's unlikely a store of a vector immediate can be done in a single 3881 // instruction. It would require a load from a constantpool first. 3882 // We only handle zero vectors here. 3883 // FIXME: Handle other cases where store of vector immediate is done in 3884 // a single instruction. 3885 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff)); 3886 if (Value.getNode()) 3887 Store = DAG.getStore(Chain, dl, Value, 3888 getMemBasePlusOffset(Dst, DstOff, dl, DAG), 3889 DstPtrInfo.getWithOffset(DstOff), isVol, 3890 false, Align); 3891 } 3892 3893 if (!Store.getNode()) { 3894 // The type might not be legal for the target. This should only happen 3895 // if the type is smaller than a legal type, as on PPC, so the right 3896 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 3897 // to Load/Store if NVT==VT. 3898 // FIXME does the case above also need this? 3899 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 3900 assert(NVT.bitsGE(VT)); 3901 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain, 3902 getMemBasePlusOffset(Src, SrcOff, dl, DAG), 3903 SrcPtrInfo.getWithOffset(SrcOff), VT, isVol, false, 3904 MinAlign(SrcAlign, SrcOff)); 3905 Store = DAG.getTruncStore(Chain, dl, Value, 3906 getMemBasePlusOffset(Dst, DstOff, dl, DAG), 3907 DstPtrInfo.getWithOffset(DstOff), VT, isVol, 3908 false, Align); 3909 } 3910 OutChains.push_back(Store); 3911 SrcOff += VTSize; 3912 DstOff += VTSize; 3913 Size -= VTSize; 3914 } 3915 3916 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 3917 } 3918 3919 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, SDLoc dl, 3920 SDValue Chain, SDValue Dst, 3921 SDValue Src, uint64_t Size, 3922 unsigned Align, bool isVol, 3923 bool AlwaysInline, 3924 MachinePointerInfo DstPtrInfo, 3925 MachinePointerInfo SrcPtrInfo) { 3926 // Turn a memmove of undef to nop. 3927 if (Src.getOpcode() == ISD::UNDEF) 3928 return Chain; 3929 3930 // Expand memmove to a series of load and store ops if the size operand falls 3931 // below a certain threshold. 3932 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3933 std::vector<EVT> MemOps; 3934 bool DstAlignCanChange = false; 3935 MachineFunction &MF = DAG.getMachineFunction(); 3936 MachineFrameInfo *MFI = MF.getFrameInfo(); 3937 bool OptSize = MF.getFunction()->getAttributes(). 3938 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize); 3939 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 3940 if (FI && !MFI->isFixedObjectIndex(FI->getIndex())) 3941 DstAlignCanChange = true; 3942 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 3943 if (Align > SrcAlign) 3944 SrcAlign = Align; 3945 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 3946 3947 if (!FindOptimalMemOpLowering(MemOps, Limit, Size, 3948 (DstAlignCanChange ? 0 : Align), SrcAlign, 3949 false, false, false, false, DAG, TLI)) 3950 return SDValue(); 3951 3952 if (DstAlignCanChange) { 3953 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 3954 unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty); 3955 if (NewAlign > Align) { 3956 // Give the stack frame object a larger alignment if needed. 3957 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign) 3958 MFI->setObjectAlignment(FI->getIndex(), NewAlign); 3959 Align = NewAlign; 3960 } 3961 } 3962 3963 uint64_t SrcOff = 0, DstOff = 0; 3964 SmallVector<SDValue, 8> LoadValues; 3965 SmallVector<SDValue, 8> LoadChains; 3966 SmallVector<SDValue, 8> OutChains; 3967 unsigned NumMemOps = MemOps.size(); 3968 for (unsigned i = 0; i < NumMemOps; i++) { 3969 EVT VT = MemOps[i]; 3970 unsigned VTSize = VT.getSizeInBits() / 8; 3971 SDValue Value; 3972 3973 Value = DAG.getLoad(VT, dl, Chain, 3974 getMemBasePlusOffset(Src, SrcOff, dl, DAG), 3975 SrcPtrInfo.getWithOffset(SrcOff), isVol, 3976 false, false, SrcAlign); 3977 LoadValues.push_back(Value); 3978 LoadChains.push_back(Value.getValue(1)); 3979 SrcOff += VTSize; 3980 } 3981 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 3982 OutChains.clear(); 3983 for (unsigned i = 0; i < NumMemOps; i++) { 3984 EVT VT = MemOps[i]; 3985 unsigned VTSize = VT.getSizeInBits() / 8; 3986 SDValue Store; 3987 3988 Store = DAG.getStore(Chain, dl, LoadValues[i], 3989 getMemBasePlusOffset(Dst, DstOff, dl, DAG), 3990 DstPtrInfo.getWithOffset(DstOff), isVol, false, Align); 3991 OutChains.push_back(Store); 3992 DstOff += VTSize; 3993 } 3994 3995 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 3996 } 3997 3998 /// \brief Lower the call to 'memset' intrinsic function into a series of store 3999 /// operations. 4000 /// 4001 /// \param DAG Selection DAG where lowered code is placed. 4002 /// \param dl Link to corresponding IR location. 4003 /// \param Chain Control flow dependency. 4004 /// \param Dst Pointer to destination memory location. 4005 /// \param Src Value of byte to write into the memory. 4006 /// \param Size Number of bytes to write. 4007 /// \param Align Alignment of the destination in bytes. 4008 /// \param isVol True if destination is volatile. 4009 /// \param DstPtrInfo IR information on the memory pointer. 4010 /// \returns New head in the control flow, if lowering was successful, empty 4011 /// SDValue otherwise. 4012 /// 4013 /// The function tries to replace 'llvm.memset' intrinsic with several store 4014 /// operations and value calculation code. This is usually profitable for small 4015 /// memory size. 4016 static SDValue getMemsetStores(SelectionDAG &DAG, SDLoc dl, 4017 SDValue Chain, SDValue Dst, 4018 SDValue Src, uint64_t Size, 4019 unsigned Align, bool isVol, 4020 MachinePointerInfo DstPtrInfo) { 4021 // Turn a memset of undef to nop. 4022 if (Src.getOpcode() == ISD::UNDEF) 4023 return Chain; 4024 4025 // Expand memset to a series of load/store ops if the size operand 4026 // falls below a certain threshold. 4027 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4028 std::vector<EVT> MemOps; 4029 bool DstAlignCanChange = false; 4030 MachineFunction &MF = DAG.getMachineFunction(); 4031 MachineFrameInfo *MFI = MF.getFrameInfo(); 4032 bool OptSize = MF.getFunction()->getAttributes(). 4033 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize); 4034 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 4035 if (FI && !MFI->isFixedObjectIndex(FI->getIndex())) 4036 DstAlignCanChange = true; 4037 bool IsZeroVal = 4038 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 4039 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize), 4040 Size, (DstAlignCanChange ? 0 : Align), 0, 4041 true, IsZeroVal, false, true, DAG, TLI)) 4042 return SDValue(); 4043 4044 if (DstAlignCanChange) { 4045 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 4046 unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty); 4047 if (NewAlign > Align) { 4048 // Give the stack frame object a larger alignment if needed. 4049 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign) 4050 MFI->setObjectAlignment(FI->getIndex(), NewAlign); 4051 Align = NewAlign; 4052 } 4053 } 4054 4055 SmallVector<SDValue, 8> OutChains; 4056 uint64_t DstOff = 0; 4057 unsigned NumMemOps = MemOps.size(); 4058 4059 // Find the largest store and generate the bit pattern for it. 4060 EVT LargestVT = MemOps[0]; 4061 for (unsigned i = 1; i < NumMemOps; i++) 4062 if (MemOps[i].bitsGT(LargestVT)) 4063 LargestVT = MemOps[i]; 4064 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 4065 4066 for (unsigned i = 0; i < NumMemOps; i++) { 4067 EVT VT = MemOps[i]; 4068 unsigned VTSize = VT.getSizeInBits() / 8; 4069 if (VTSize > Size) { 4070 // Issuing an unaligned load / store pair that overlaps with the previous 4071 // pair. Adjust the offset accordingly. 4072 assert(i == NumMemOps-1 && i != 0); 4073 DstOff -= VTSize - Size; 4074 } 4075 4076 // If this store is smaller than the largest store see whether we can get 4077 // the smaller value for free with a truncate. 4078 SDValue Value = MemSetValue; 4079 if (VT.bitsLT(LargestVT)) { 4080 if (!LargestVT.isVector() && !VT.isVector() && 4081 TLI.isTruncateFree(LargestVT, VT)) 4082 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 4083 else 4084 Value = getMemsetValue(Src, VT, DAG, dl); 4085 } 4086 assert(Value.getValueType() == VT && "Value with wrong type."); 4087 SDValue Store = DAG.getStore(Chain, dl, Value, 4088 getMemBasePlusOffset(Dst, DstOff, dl, DAG), 4089 DstPtrInfo.getWithOffset(DstOff), 4090 isVol, false, Align); 4091 OutChains.push_back(Store); 4092 DstOff += VT.getSizeInBits() / 8; 4093 Size -= VTSize; 4094 } 4095 4096 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 4097 } 4098 4099 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDLoc dl, SDValue Dst, 4100 SDValue Src, SDValue Size, 4101 unsigned Align, bool isVol, bool AlwaysInline, 4102 MachinePointerInfo DstPtrInfo, 4103 MachinePointerInfo SrcPtrInfo) { 4104 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4105 4106 // Check to see if we should lower the memcpy to loads and stores first. 4107 // For cases within the target-specified limits, this is the best choice. 4108 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4109 if (ConstantSize) { 4110 // Memcpy with size zero? Just return the original chain. 4111 if (ConstantSize->isNullValue()) 4112 return Chain; 4113 4114 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 4115 ConstantSize->getZExtValue(),Align, 4116 isVol, false, DstPtrInfo, SrcPtrInfo); 4117 if (Result.getNode()) 4118 return Result; 4119 } 4120 4121 // Then check to see if we should lower the memcpy with target-specific 4122 // code. If the target chooses to do this, this is the next best. 4123 SDValue Result = 4124 TSI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align, 4125 isVol, AlwaysInline, 4126 DstPtrInfo, SrcPtrInfo); 4127 if (Result.getNode()) 4128 return Result; 4129 4130 // If we really need inline code and the target declined to provide it, 4131 // use a (potentially long) sequence of loads and stores. 4132 if (AlwaysInline) { 4133 assert(ConstantSize && "AlwaysInline requires a constant size!"); 4134 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 4135 ConstantSize->getZExtValue(), Align, isVol, 4136 true, DstPtrInfo, SrcPtrInfo); 4137 } 4138 4139 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 4140 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 4141 // respect volatile, so they may do things like read or write memory 4142 // beyond the given memory regions. But fixing this isn't easy, and most 4143 // people don't care. 4144 4145 const TargetLowering *TLI = TM.getTargetLowering(); 4146 4147 // Emit a library call. 4148 TargetLowering::ArgListTy Args; 4149 TargetLowering::ArgListEntry Entry; 4150 Entry.Ty = TLI->getDataLayout()->getIntPtrType(*getContext()); 4151 Entry.Node = Dst; Args.push_back(Entry); 4152 Entry.Node = Src; Args.push_back(Entry); 4153 Entry.Node = Size; Args.push_back(Entry); 4154 // FIXME: pass in SDLoc 4155 TargetLowering::CallLoweringInfo CLI(*this); 4156 CLI.setDebugLoc(dl).setChain(Chain) 4157 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 4158 Type::getVoidTy(*getContext()), 4159 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 4160 TLI->getPointerTy()), &Args, 0) 4161 .setDiscardResult(); 4162 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4163 4164 return CallResult.second; 4165 } 4166 4167 SDValue SelectionDAG::getMemmove(SDValue Chain, SDLoc dl, SDValue Dst, 4168 SDValue Src, SDValue Size, 4169 unsigned Align, bool isVol, 4170 MachinePointerInfo DstPtrInfo, 4171 MachinePointerInfo SrcPtrInfo) { 4172 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4173 4174 // Check to see if we should lower the memmove to loads and stores first. 4175 // For cases within the target-specified limits, this is the best choice. 4176 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4177 if (ConstantSize) { 4178 // Memmove with size zero? Just return the original chain. 4179 if (ConstantSize->isNullValue()) 4180 return Chain; 4181 4182 SDValue Result = 4183 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src, 4184 ConstantSize->getZExtValue(), Align, isVol, 4185 false, DstPtrInfo, SrcPtrInfo); 4186 if (Result.getNode()) 4187 return Result; 4188 } 4189 4190 // Then check to see if we should lower the memmove with target-specific 4191 // code. If the target chooses to do this, this is the next best. 4192 SDValue Result = 4193 TSI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align, isVol, 4194 DstPtrInfo, SrcPtrInfo); 4195 if (Result.getNode()) 4196 return Result; 4197 4198 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 4199 // not be safe. See memcpy above for more details. 4200 4201 const TargetLowering *TLI = TM.getTargetLowering(); 4202 4203 // Emit a library call. 4204 TargetLowering::ArgListTy Args; 4205 TargetLowering::ArgListEntry Entry; 4206 Entry.Ty = TLI->getDataLayout()->getIntPtrType(*getContext()); 4207 Entry.Node = Dst; Args.push_back(Entry); 4208 Entry.Node = Src; Args.push_back(Entry); 4209 Entry.Node = Size; Args.push_back(Entry); 4210 // FIXME: pass in SDLoc 4211 TargetLowering::CallLoweringInfo CLI(*this); 4212 CLI.setDebugLoc(dl).setChain(Chain) 4213 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 4214 Type::getVoidTy(*getContext()), 4215 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 4216 TLI->getPointerTy()), &Args, 0) 4217 .setDiscardResult(); 4218 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4219 4220 return CallResult.second; 4221 } 4222 4223 SDValue SelectionDAG::getMemset(SDValue Chain, SDLoc dl, SDValue Dst, 4224 SDValue Src, SDValue Size, 4225 unsigned Align, bool isVol, 4226 MachinePointerInfo DstPtrInfo) { 4227 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4228 4229 // Check to see if we should lower the memset to stores first. 4230 // For cases within the target-specified limits, this is the best choice. 4231 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4232 if (ConstantSize) { 4233 // Memset with size zero? Just return the original chain. 4234 if (ConstantSize->isNullValue()) 4235 return Chain; 4236 4237 SDValue Result = 4238 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), 4239 Align, isVol, DstPtrInfo); 4240 4241 if (Result.getNode()) 4242 return Result; 4243 } 4244 4245 // Then check to see if we should lower the memset with target-specific 4246 // code. If the target chooses to do this, this is the next best. 4247 SDValue Result = 4248 TSI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align, isVol, 4249 DstPtrInfo); 4250 if (Result.getNode()) 4251 return Result; 4252 4253 // Emit a library call. 4254 const TargetLowering *TLI = TM.getTargetLowering(); 4255 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(*getContext()); 4256 TargetLowering::ArgListTy Args; 4257 TargetLowering::ArgListEntry Entry; 4258 Entry.Node = Dst; Entry.Ty = IntPtrTy; 4259 Args.push_back(Entry); 4260 // Extend or truncate the argument to be an i32 value for the call. 4261 if (Src.getValueType().bitsGT(MVT::i32)) 4262 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src); 4263 else 4264 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src); 4265 Entry.Node = Src; 4266 Entry.Ty = Type::getInt32Ty(*getContext()); 4267 Entry.isSExt = true; 4268 Args.push_back(Entry); 4269 Entry.Node = Size; 4270 Entry.Ty = IntPtrTy; 4271 Entry.isSExt = false; 4272 Args.push_back(Entry); 4273 4274 // FIXME: pass in SDLoc 4275 TargetLowering::CallLoweringInfo CLI(*this); 4276 CLI.setDebugLoc(dl).setChain(Chain) 4277 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 4278 Type::getVoidTy(*getContext()), 4279 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 4280 TLI->getPointerTy()), &Args, 0) 4281 .setDiscardResult(); 4282 4283 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4284 return CallResult.second; 4285 } 4286 4287 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, 4288 SDVTList VTList, ArrayRef<SDValue> Ops, 4289 MachineMemOperand *MMO, 4290 AtomicOrdering SuccessOrdering, 4291 AtomicOrdering FailureOrdering, 4292 SynchronizationScope SynchScope) { 4293 FoldingSetNodeID ID; 4294 ID.AddInteger(MemVT.getRawBits()); 4295 AddNodeIDNode(ID, Opcode, VTList, Ops); 4296 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 4297 void* IP = nullptr; 4298 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) { 4299 cast<AtomicSDNode>(E)->refineAlignment(MMO); 4300 return SDValue(E, 0); 4301 } 4302 4303 // Allocate the operands array for the node out of the BumpPtrAllocator, since 4304 // SDNode doesn't have access to it. This memory will be "leaked" when 4305 // the node is deallocated, but recovered when the allocator is released. 4306 // If the number of operands is less than 5 we use AtomicSDNode's internal 4307 // storage. 4308 unsigned NumOps = Ops.size(); 4309 SDUse *DynOps = NumOps > 4 ? OperandAllocator.Allocate<SDUse>(NumOps) 4310 : nullptr; 4311 4312 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(), 4313 dl.getDebugLoc(), VTList, MemVT, 4314 Ops.data(), DynOps, NumOps, MMO, 4315 SuccessOrdering, FailureOrdering, 4316 SynchScope); 4317 CSEMap.InsertNode(N, IP); 4318 AllNodes.push_back(N); 4319 return SDValue(N, 0); 4320 } 4321 4322 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, 4323 SDVTList VTList, ArrayRef<SDValue> Ops, 4324 MachineMemOperand *MMO, 4325 AtomicOrdering Ordering, 4326 SynchronizationScope SynchScope) { 4327 return getAtomic(Opcode, dl, MemVT, VTList, Ops, MMO, Ordering, 4328 Ordering, SynchScope); 4329 } 4330 4331 SDValue SelectionDAG::getAtomicCmpSwap( 4332 unsigned Opcode, SDLoc dl, EVT MemVT, SDVTList VTs, SDValue Chain, 4333 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo, 4334 unsigned Alignment, AtomicOrdering SuccessOrdering, 4335 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) { 4336 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 4337 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 4338 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 4339 4340 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4341 Alignment = getEVTAlignment(MemVT); 4342 4343 MachineFunction &MF = getMachineFunction(); 4344 4345 // FIXME: Volatile isn't really correct; we should keep track of atomic 4346 // orderings in the memoperand. 4347 unsigned Flags = MachineMemOperand::MOVolatile; 4348 Flags |= MachineMemOperand::MOLoad; 4349 Flags |= MachineMemOperand::MOStore; 4350 4351 MachineMemOperand *MMO = 4352 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment); 4353 4354 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO, 4355 SuccessOrdering, FailureOrdering, SynchScope); 4356 } 4357 4358 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, SDLoc dl, EVT MemVT, 4359 SDVTList VTs, SDValue Chain, SDValue Ptr, 4360 SDValue Cmp, SDValue Swp, 4361 MachineMemOperand *MMO, 4362 AtomicOrdering SuccessOrdering, 4363 AtomicOrdering FailureOrdering, 4364 SynchronizationScope SynchScope) { 4365 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 4366 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 4367 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 4368 4369 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 4370 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, 4371 SuccessOrdering, FailureOrdering, SynchScope); 4372 } 4373 4374 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, 4375 SDValue Chain, 4376 SDValue Ptr, SDValue Val, 4377 const Value* PtrVal, 4378 unsigned Alignment, 4379 AtomicOrdering Ordering, 4380 SynchronizationScope SynchScope) { 4381 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4382 Alignment = getEVTAlignment(MemVT); 4383 4384 MachineFunction &MF = getMachineFunction(); 4385 // An atomic store does not load. An atomic load does not store. 4386 // (An atomicrmw obviously both loads and stores.) 4387 // For now, atomics are considered to be volatile always, and they are 4388 // chained as such. 4389 // FIXME: Volatile isn't really correct; we should keep track of atomic 4390 // orderings in the memoperand. 4391 unsigned Flags = MachineMemOperand::MOVolatile; 4392 if (Opcode != ISD::ATOMIC_STORE) 4393 Flags |= MachineMemOperand::MOLoad; 4394 if (Opcode != ISD::ATOMIC_LOAD) 4395 Flags |= MachineMemOperand::MOStore; 4396 4397 MachineMemOperand *MMO = 4398 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags, 4399 MemVT.getStoreSize(), Alignment); 4400 4401 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO, 4402 Ordering, SynchScope); 4403 } 4404 4405 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, 4406 SDValue Chain, 4407 SDValue Ptr, SDValue Val, 4408 MachineMemOperand *MMO, 4409 AtomicOrdering Ordering, 4410 SynchronizationScope SynchScope) { 4411 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 4412 Opcode == ISD::ATOMIC_LOAD_SUB || 4413 Opcode == ISD::ATOMIC_LOAD_AND || 4414 Opcode == ISD::ATOMIC_LOAD_OR || 4415 Opcode == ISD::ATOMIC_LOAD_XOR || 4416 Opcode == ISD::ATOMIC_LOAD_NAND || 4417 Opcode == ISD::ATOMIC_LOAD_MIN || 4418 Opcode == ISD::ATOMIC_LOAD_MAX || 4419 Opcode == ISD::ATOMIC_LOAD_UMIN || 4420 Opcode == ISD::ATOMIC_LOAD_UMAX || 4421 Opcode == ISD::ATOMIC_SWAP || 4422 Opcode == ISD::ATOMIC_STORE) && 4423 "Invalid Atomic Op"); 4424 4425 EVT VT = Val.getValueType(); 4426 4427 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 4428 getVTList(VT, MVT::Other); 4429 SDValue Ops[] = {Chain, Ptr, Val}; 4430 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope); 4431 } 4432 4433 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, 4434 EVT VT, SDValue Chain, 4435 SDValue Ptr, 4436 MachineMemOperand *MMO, 4437 AtomicOrdering Ordering, 4438 SynchronizationScope SynchScope) { 4439 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 4440 4441 SDVTList VTs = getVTList(VT, MVT::Other); 4442 SDValue Ops[] = {Chain, Ptr}; 4443 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope); 4444 } 4445 4446 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 4447 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, SDLoc dl) { 4448 if (Ops.size() == 1) 4449 return Ops[0]; 4450 4451 SmallVector<EVT, 4> VTs; 4452 VTs.reserve(Ops.size()); 4453 for (unsigned i = 0; i < Ops.size(); ++i) 4454 VTs.push_back(Ops[i].getValueType()); 4455 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 4456 } 4457 4458 SDValue 4459 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList, 4460 ArrayRef<SDValue> Ops, 4461 EVT MemVT, MachinePointerInfo PtrInfo, 4462 unsigned Align, bool Vol, 4463 bool ReadMem, bool WriteMem) { 4464 if (Align == 0) // Ensure that codegen never sees alignment 0 4465 Align = getEVTAlignment(MemVT); 4466 4467 MachineFunction &MF = getMachineFunction(); 4468 unsigned Flags = 0; 4469 if (WriteMem) 4470 Flags |= MachineMemOperand::MOStore; 4471 if (ReadMem) 4472 Flags |= MachineMemOperand::MOLoad; 4473 if (Vol) 4474 Flags |= MachineMemOperand::MOVolatile; 4475 MachineMemOperand *MMO = 4476 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Align); 4477 4478 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 4479 } 4480 4481 SDValue 4482 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList, 4483 ArrayRef<SDValue> Ops, EVT MemVT, 4484 MachineMemOperand *MMO) { 4485 assert((Opcode == ISD::INTRINSIC_VOID || 4486 Opcode == ISD::INTRINSIC_W_CHAIN || 4487 Opcode == ISD::PREFETCH || 4488 Opcode == ISD::LIFETIME_START || 4489 Opcode == ISD::LIFETIME_END || 4490 (Opcode <= INT_MAX && 4491 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 4492 "Opcode is not a memory-accessing opcode!"); 4493 4494 // Memoize the node unless it returns a flag. 4495 MemIntrinsicSDNode *N; 4496 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 4497 FoldingSetNodeID ID; 4498 AddNodeIDNode(ID, Opcode, VTList, Ops); 4499 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 4500 void *IP = nullptr; 4501 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) { 4502 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 4503 return SDValue(E, 0); 4504 } 4505 4506 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(), 4507 dl.getDebugLoc(), VTList, Ops, 4508 MemVT, MMO); 4509 CSEMap.InsertNode(N, IP); 4510 } else { 4511 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(), 4512 dl.getDebugLoc(), VTList, Ops, 4513 MemVT, MMO); 4514 } 4515 AllNodes.push_back(N); 4516 return SDValue(N, 0); 4517 } 4518 4519 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 4520 /// MachinePointerInfo record from it. This is particularly useful because the 4521 /// code generator has many cases where it doesn't bother passing in a 4522 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 4523 static MachinePointerInfo InferPointerInfo(SDValue Ptr, int64_t Offset = 0) { 4524 // If this is FI+Offset, we can model it. 4525 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 4526 return MachinePointerInfo::getFixedStack(FI->getIndex(), Offset); 4527 4528 // If this is (FI+Offset1)+Offset2, we can model it. 4529 if (Ptr.getOpcode() != ISD::ADD || 4530 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 4531 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 4532 return MachinePointerInfo(); 4533 4534 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 4535 return MachinePointerInfo::getFixedStack(FI, Offset+ 4536 cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 4537 } 4538 4539 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 4540 /// MachinePointerInfo record from it. This is particularly useful because the 4541 /// code generator has many cases where it doesn't bother passing in a 4542 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 4543 static MachinePointerInfo InferPointerInfo(SDValue Ptr, SDValue OffsetOp) { 4544 // If the 'Offset' value isn't a constant, we can't handle this. 4545 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 4546 return InferPointerInfo(Ptr, OffsetNode->getSExtValue()); 4547 if (OffsetOp.getOpcode() == ISD::UNDEF) 4548 return InferPointerInfo(Ptr); 4549 return MachinePointerInfo(); 4550 } 4551 4552 4553 SDValue 4554 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 4555 EVT VT, SDLoc dl, SDValue Chain, 4556 SDValue Ptr, SDValue Offset, 4557 MachinePointerInfo PtrInfo, EVT MemVT, 4558 bool isVolatile, bool isNonTemporal, bool isInvariant, 4559 unsigned Alignment, const MDNode *TBAAInfo, 4560 const MDNode *Ranges) { 4561 assert(Chain.getValueType() == MVT::Other && 4562 "Invalid chain type"); 4563 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4564 Alignment = getEVTAlignment(VT); 4565 4566 unsigned Flags = MachineMemOperand::MOLoad; 4567 if (isVolatile) 4568 Flags |= MachineMemOperand::MOVolatile; 4569 if (isNonTemporal) 4570 Flags |= MachineMemOperand::MONonTemporal; 4571 if (isInvariant) 4572 Flags |= MachineMemOperand::MOInvariant; 4573 4574 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 4575 // clients. 4576 if (PtrInfo.V.isNull()) 4577 PtrInfo = InferPointerInfo(Ptr, Offset); 4578 4579 MachineFunction &MF = getMachineFunction(); 4580 MachineMemOperand *MMO = 4581 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment, 4582 TBAAInfo, Ranges); 4583 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 4584 } 4585 4586 SDValue 4587 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 4588 EVT VT, SDLoc dl, SDValue Chain, 4589 SDValue Ptr, SDValue Offset, EVT MemVT, 4590 MachineMemOperand *MMO) { 4591 if (VT == MemVT) { 4592 ExtType = ISD::NON_EXTLOAD; 4593 } else if (ExtType == ISD::NON_EXTLOAD) { 4594 assert(VT == MemVT && "Non-extending load from different memory type!"); 4595 } else { 4596 // Extending load. 4597 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 4598 "Should only be an extending load, not truncating!"); 4599 assert(VT.isInteger() == MemVT.isInteger() && 4600 "Cannot convert from FP to Int or Int -> FP!"); 4601 assert(VT.isVector() == MemVT.isVector() && 4602 "Cannot use trunc store to convert to or from a vector!"); 4603 assert((!VT.isVector() || 4604 VT.getVectorNumElements() == MemVT.getVectorNumElements()) && 4605 "Cannot use trunc store to change the number of vector elements!"); 4606 } 4607 4608 bool Indexed = AM != ISD::UNINDEXED; 4609 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) && 4610 "Unindexed load with an offset!"); 4611 4612 SDVTList VTs = Indexed ? 4613 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 4614 SDValue Ops[] = { Chain, Ptr, Offset }; 4615 FoldingSetNodeID ID; 4616 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 4617 ID.AddInteger(MemVT.getRawBits()); 4618 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(), 4619 MMO->isNonTemporal(), 4620 MMO->isInvariant())); 4621 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 4622 void *IP = nullptr; 4623 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) { 4624 cast<LoadSDNode>(E)->refineAlignment(MMO); 4625 return SDValue(E, 0); 4626 } 4627 SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl.getIROrder(), 4628 dl.getDebugLoc(), VTs, AM, ExtType, 4629 MemVT, MMO); 4630 CSEMap.InsertNode(N, IP); 4631 AllNodes.push_back(N); 4632 return SDValue(N, 0); 4633 } 4634 4635 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl, 4636 SDValue Chain, SDValue Ptr, 4637 MachinePointerInfo PtrInfo, 4638 bool isVolatile, bool isNonTemporal, 4639 bool isInvariant, unsigned Alignment, 4640 const MDNode *TBAAInfo, 4641 const MDNode *Ranges) { 4642 SDValue Undef = getUNDEF(Ptr.getValueType()); 4643 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 4644 PtrInfo, VT, isVolatile, isNonTemporal, isInvariant, Alignment, 4645 TBAAInfo, Ranges); 4646 } 4647 4648 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl, 4649 SDValue Chain, SDValue Ptr, 4650 MachineMemOperand *MMO) { 4651 SDValue Undef = getUNDEF(Ptr.getValueType()); 4652 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 4653 VT, MMO); 4654 } 4655 4656 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT, 4657 SDValue Chain, SDValue Ptr, 4658 MachinePointerInfo PtrInfo, EVT MemVT, 4659 bool isVolatile, bool isNonTemporal, 4660 unsigned Alignment, const MDNode *TBAAInfo) { 4661 SDValue Undef = getUNDEF(Ptr.getValueType()); 4662 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 4663 PtrInfo, MemVT, isVolatile, isNonTemporal, false, Alignment, 4664 TBAAInfo); 4665 } 4666 4667 4668 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT, 4669 SDValue Chain, SDValue Ptr, EVT MemVT, 4670 MachineMemOperand *MMO) { 4671 SDValue Undef = getUNDEF(Ptr.getValueType()); 4672 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 4673 MemVT, MMO); 4674 } 4675 4676 SDValue 4677 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDLoc dl, SDValue Base, 4678 SDValue Offset, ISD::MemIndexedMode AM) { 4679 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 4680 assert(LD->getOffset().getOpcode() == ISD::UNDEF && 4681 "Load is already a indexed load!"); 4682 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 4683 LD->getChain(), Base, Offset, LD->getPointerInfo(), 4684 LD->getMemoryVT(), LD->isVolatile(), LD->isNonTemporal(), 4685 false, LD->getAlignment()); 4686 } 4687 4688 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val, 4689 SDValue Ptr, MachinePointerInfo PtrInfo, 4690 bool isVolatile, bool isNonTemporal, 4691 unsigned Alignment, const MDNode *TBAAInfo) { 4692 assert(Chain.getValueType() == MVT::Other && 4693 "Invalid chain type"); 4694 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4695 Alignment = getEVTAlignment(Val.getValueType()); 4696 4697 unsigned Flags = MachineMemOperand::MOStore; 4698 if (isVolatile) 4699 Flags |= MachineMemOperand::MOVolatile; 4700 if (isNonTemporal) 4701 Flags |= MachineMemOperand::MONonTemporal; 4702 4703 if (PtrInfo.V.isNull()) 4704 PtrInfo = InferPointerInfo(Ptr); 4705 4706 MachineFunction &MF = getMachineFunction(); 4707 MachineMemOperand *MMO = 4708 MF.getMachineMemOperand(PtrInfo, Flags, 4709 Val.getValueType().getStoreSize(), Alignment, 4710 TBAAInfo); 4711 4712 return getStore(Chain, dl, Val, Ptr, MMO); 4713 } 4714 4715 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val, 4716 SDValue Ptr, MachineMemOperand *MMO) { 4717 assert(Chain.getValueType() == MVT::Other && 4718 "Invalid chain type"); 4719 EVT VT = Val.getValueType(); 4720 SDVTList VTs = getVTList(MVT::Other); 4721 SDValue Undef = getUNDEF(Ptr.getValueType()); 4722 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 4723 FoldingSetNodeID ID; 4724 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 4725 ID.AddInteger(VT.getRawBits()); 4726 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(), 4727 MMO->isNonTemporal(), MMO->isInvariant())); 4728 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 4729 void *IP = nullptr; 4730 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) { 4731 cast<StoreSDNode>(E)->refineAlignment(MMO); 4732 return SDValue(E, 0); 4733 } 4734 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), 4735 dl.getDebugLoc(), VTs, 4736 ISD::UNINDEXED, false, VT, MMO); 4737 CSEMap.InsertNode(N, IP); 4738 AllNodes.push_back(N); 4739 return SDValue(N, 0); 4740 } 4741 4742 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val, 4743 SDValue Ptr, MachinePointerInfo PtrInfo, 4744 EVT SVT,bool isVolatile, bool isNonTemporal, 4745 unsigned Alignment, 4746 const MDNode *TBAAInfo) { 4747 assert(Chain.getValueType() == MVT::Other && 4748 "Invalid chain type"); 4749 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4750 Alignment = getEVTAlignment(SVT); 4751 4752 unsigned Flags = MachineMemOperand::MOStore; 4753 if (isVolatile) 4754 Flags |= MachineMemOperand::MOVolatile; 4755 if (isNonTemporal) 4756 Flags |= MachineMemOperand::MONonTemporal; 4757 4758 if (PtrInfo.V.isNull()) 4759 PtrInfo = InferPointerInfo(Ptr); 4760 4761 MachineFunction &MF = getMachineFunction(); 4762 MachineMemOperand *MMO = 4763 MF.getMachineMemOperand(PtrInfo, Flags, SVT.getStoreSize(), Alignment, 4764 TBAAInfo); 4765 4766 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 4767 } 4768 4769 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val, 4770 SDValue Ptr, EVT SVT, 4771 MachineMemOperand *MMO) { 4772 EVT VT = Val.getValueType(); 4773 4774 assert(Chain.getValueType() == MVT::Other && 4775 "Invalid chain type"); 4776 if (VT == SVT) 4777 return getStore(Chain, dl, Val, Ptr, MMO); 4778 4779 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 4780 "Should only be a truncating store, not extending!"); 4781 assert(VT.isInteger() == SVT.isInteger() && 4782 "Can't do FP-INT conversion!"); 4783 assert(VT.isVector() == SVT.isVector() && 4784 "Cannot use trunc store to convert to or from a vector!"); 4785 assert((!VT.isVector() || 4786 VT.getVectorNumElements() == SVT.getVectorNumElements()) && 4787 "Cannot use trunc store to change the number of vector elements!"); 4788 4789 SDVTList VTs = getVTList(MVT::Other); 4790 SDValue Undef = getUNDEF(Ptr.getValueType()); 4791 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 4792 FoldingSetNodeID ID; 4793 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 4794 ID.AddInteger(SVT.getRawBits()); 4795 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(), 4796 MMO->isNonTemporal(), MMO->isInvariant())); 4797 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 4798 void *IP = nullptr; 4799 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) { 4800 cast<StoreSDNode>(E)->refineAlignment(MMO); 4801 return SDValue(E, 0); 4802 } 4803 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), 4804 dl.getDebugLoc(), VTs, 4805 ISD::UNINDEXED, true, SVT, MMO); 4806 CSEMap.InsertNode(N, IP); 4807 AllNodes.push_back(N); 4808 return SDValue(N, 0); 4809 } 4810 4811 SDValue 4812 SelectionDAG::getIndexedStore(SDValue OrigStore, SDLoc dl, SDValue Base, 4813 SDValue Offset, ISD::MemIndexedMode AM) { 4814 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 4815 assert(ST->getOffset().getOpcode() == ISD::UNDEF && 4816 "Store is already a indexed store!"); 4817 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 4818 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 4819 FoldingSetNodeID ID; 4820 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 4821 ID.AddInteger(ST->getMemoryVT().getRawBits()); 4822 ID.AddInteger(ST->getRawSubclassData()); 4823 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 4824 void *IP = nullptr; 4825 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 4826 return SDValue(E, 0); 4827 4828 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), 4829 dl.getDebugLoc(), VTs, AM, 4830 ST->isTruncatingStore(), 4831 ST->getMemoryVT(), 4832 ST->getMemOperand()); 4833 CSEMap.InsertNode(N, IP); 4834 AllNodes.push_back(N); 4835 return SDValue(N, 0); 4836 } 4837 4838 SDValue SelectionDAG::getVAArg(EVT VT, SDLoc dl, 4839 SDValue Chain, SDValue Ptr, 4840 SDValue SV, 4841 unsigned Align) { 4842 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, MVT::i32) }; 4843 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 4844 } 4845 4846 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, 4847 ArrayRef<SDUse> Ops) { 4848 switch (Ops.size()) { 4849 case 0: return getNode(Opcode, DL, VT); 4850 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 4851 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 4852 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 4853 default: break; 4854 } 4855 4856 // Copy from an SDUse array into an SDValue array for use with 4857 // the regular getNode logic. 4858 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 4859 return getNode(Opcode, DL, VT, NewOps); 4860 } 4861 4862 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, 4863 ArrayRef<SDValue> Ops) { 4864 unsigned NumOps = Ops.size(); 4865 switch (NumOps) { 4866 case 0: return getNode(Opcode, DL, VT); 4867 case 1: return getNode(Opcode, DL, VT, Ops[0]); 4868 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 4869 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 4870 default: break; 4871 } 4872 4873 switch (Opcode) { 4874 default: break; 4875 case ISD::SELECT_CC: { 4876 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 4877 assert(Ops[0].getValueType() == Ops[1].getValueType() && 4878 "LHS and RHS of condition must have same type!"); 4879 assert(Ops[2].getValueType() == Ops[3].getValueType() && 4880 "True and False arms of SelectCC must have same type!"); 4881 assert(Ops[2].getValueType() == VT && 4882 "select_cc node must be of same type as true and false value!"); 4883 break; 4884 } 4885 case ISD::BR_CC: { 4886 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 4887 assert(Ops[2].getValueType() == Ops[3].getValueType() && 4888 "LHS/RHS of comparison should match types!"); 4889 break; 4890 } 4891 } 4892 4893 // Memoize nodes. 4894 SDNode *N; 4895 SDVTList VTs = getVTList(VT); 4896 4897 if (VT != MVT::Glue) { 4898 FoldingSetNodeID ID; 4899 AddNodeIDNode(ID, Opcode, VTs, Ops); 4900 void *IP = nullptr; 4901 4902 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 4903 return SDValue(E, 0); 4904 4905 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4906 VTs, Ops); 4907 CSEMap.InsertNode(N, IP); 4908 } else { 4909 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4910 VTs, Ops); 4911 } 4912 4913 AllNodes.push_back(N); 4914 #ifndef NDEBUG 4915 VerifySDNode(N); 4916 #endif 4917 return SDValue(N, 0); 4918 } 4919 4920 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, 4921 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 4922 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 4923 } 4924 4925 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 4926 ArrayRef<SDValue> Ops) { 4927 if (VTList.NumVTs == 1) 4928 return getNode(Opcode, DL, VTList.VTs[0], Ops); 4929 4930 #if 0 4931 switch (Opcode) { 4932 // FIXME: figure out how to safely handle things like 4933 // int foo(int x) { return 1 << (x & 255); } 4934 // int bar() { return foo(256); } 4935 case ISD::SRA_PARTS: 4936 case ISD::SRL_PARTS: 4937 case ISD::SHL_PARTS: 4938 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 4939 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 4940 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 4941 else if (N3.getOpcode() == ISD::AND) 4942 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 4943 // If the and is only masking out bits that cannot effect the shift, 4944 // eliminate the and. 4945 unsigned NumBits = VT.getScalarType().getSizeInBits()*2; 4946 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 4947 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 4948 } 4949 break; 4950 } 4951 #endif 4952 4953 // Memoize the node unless it returns a flag. 4954 SDNode *N; 4955 unsigned NumOps = Ops.size(); 4956 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 4957 FoldingSetNodeID ID; 4958 AddNodeIDNode(ID, Opcode, VTList, Ops); 4959 void *IP = nullptr; 4960 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 4961 return SDValue(E, 0); 4962 4963 if (NumOps == 1) { 4964 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), 4965 DL.getDebugLoc(), VTList, Ops[0]); 4966 } else if (NumOps == 2) { 4967 N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), 4968 DL.getDebugLoc(), VTList, Ops[0], 4969 Ops[1]); 4970 } else if (NumOps == 3) { 4971 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), 4972 DL.getDebugLoc(), VTList, Ops[0], 4973 Ops[1], Ops[2]); 4974 } else { 4975 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4976 VTList, Ops); 4977 } 4978 CSEMap.InsertNode(N, IP); 4979 } else { 4980 if (NumOps == 1) { 4981 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), 4982 DL.getDebugLoc(), VTList, Ops[0]); 4983 } else if (NumOps == 2) { 4984 N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), 4985 DL.getDebugLoc(), VTList, Ops[0], 4986 Ops[1]); 4987 } else if (NumOps == 3) { 4988 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), 4989 DL.getDebugLoc(), VTList, Ops[0], 4990 Ops[1], Ops[2]); 4991 } else { 4992 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4993 VTList, Ops); 4994 } 4995 } 4996 AllNodes.push_back(N); 4997 #ifndef NDEBUG 4998 VerifySDNode(N); 4999 #endif 5000 return SDValue(N, 0); 5001 } 5002 5003 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList) { 5004 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>()); 5005 } 5006 5007 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5008 SDValue N1) { 5009 SDValue Ops[] = { N1 }; 5010 return getNode(Opcode, DL, VTList, Ops); 5011 } 5012 5013 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5014 SDValue N1, SDValue N2) { 5015 SDValue Ops[] = { N1, N2 }; 5016 return getNode(Opcode, DL, VTList, Ops); 5017 } 5018 5019 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5020 SDValue N1, SDValue N2, SDValue N3) { 5021 SDValue Ops[] = { N1, N2, N3 }; 5022 return getNode(Opcode, DL, VTList, Ops); 5023 } 5024 5025 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5026 SDValue N1, SDValue N2, SDValue N3, 5027 SDValue N4) { 5028 SDValue Ops[] = { N1, N2, N3, N4 }; 5029 return getNode(Opcode, DL, VTList, Ops); 5030 } 5031 5032 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList, 5033 SDValue N1, SDValue N2, SDValue N3, 5034 SDValue N4, SDValue N5) { 5035 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 5036 return getNode(Opcode, DL, VTList, Ops); 5037 } 5038 5039 SDVTList SelectionDAG::getVTList(EVT VT) { 5040 return makeVTList(SDNode::getValueTypeList(VT), 1); 5041 } 5042 5043 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 5044 FoldingSetNodeID ID; 5045 ID.AddInteger(2U); 5046 ID.AddInteger(VT1.getRawBits()); 5047 ID.AddInteger(VT2.getRawBits()); 5048 5049 void *IP = nullptr; 5050 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5051 if (!Result) { 5052 EVT *Array = Allocator.Allocate<EVT>(2); 5053 Array[0] = VT1; 5054 Array[1] = VT2; 5055 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 5056 VTListMap.InsertNode(Result, IP); 5057 } 5058 return Result->getSDVTList(); 5059 } 5060 5061 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 5062 FoldingSetNodeID ID; 5063 ID.AddInteger(3U); 5064 ID.AddInteger(VT1.getRawBits()); 5065 ID.AddInteger(VT2.getRawBits()); 5066 ID.AddInteger(VT3.getRawBits()); 5067 5068 void *IP = nullptr; 5069 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5070 if (!Result) { 5071 EVT *Array = Allocator.Allocate<EVT>(3); 5072 Array[0] = VT1; 5073 Array[1] = VT2; 5074 Array[2] = VT3; 5075 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 5076 VTListMap.InsertNode(Result, IP); 5077 } 5078 return Result->getSDVTList(); 5079 } 5080 5081 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 5082 FoldingSetNodeID ID; 5083 ID.AddInteger(4U); 5084 ID.AddInteger(VT1.getRawBits()); 5085 ID.AddInteger(VT2.getRawBits()); 5086 ID.AddInteger(VT3.getRawBits()); 5087 ID.AddInteger(VT4.getRawBits()); 5088 5089 void *IP = nullptr; 5090 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5091 if (!Result) { 5092 EVT *Array = Allocator.Allocate<EVT>(4); 5093 Array[0] = VT1; 5094 Array[1] = VT2; 5095 Array[2] = VT3; 5096 Array[3] = VT4; 5097 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 5098 VTListMap.InsertNode(Result, IP); 5099 } 5100 return Result->getSDVTList(); 5101 } 5102 5103 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 5104 unsigned NumVTs = VTs.size(); 5105 FoldingSetNodeID ID; 5106 ID.AddInteger(NumVTs); 5107 for (unsigned index = 0; index < NumVTs; index++) { 5108 ID.AddInteger(VTs[index].getRawBits()); 5109 } 5110 5111 void *IP = nullptr; 5112 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5113 if (!Result) { 5114 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 5115 std::copy(VTs.begin(), VTs.end(), Array); 5116 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 5117 VTListMap.InsertNode(Result, IP); 5118 } 5119 return Result->getSDVTList(); 5120 } 5121 5122 5123 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 5124 /// specified operands. If the resultant node already exists in the DAG, 5125 /// this does not modify the specified node, instead it returns the node that 5126 /// already exists. If the resultant node does not exist in the DAG, the 5127 /// input node is returned. As a degenerate case, if you specify the same 5128 /// input operands as the node already has, the input node is returned. 5129 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 5130 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 5131 5132 // Check to see if there is no change. 5133 if (Op == N->getOperand(0)) return N; 5134 5135 // See if the modified node already exists. 5136 void *InsertPos = nullptr; 5137 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 5138 return Existing; 5139 5140 // Nope it doesn't. Remove the node from its current place in the maps. 5141 if (InsertPos) 5142 if (!RemoveNodeFromCSEMaps(N)) 5143 InsertPos = nullptr; 5144 5145 // Now we update the operands. 5146 N->OperandList[0].set(Op); 5147 5148 // If this gets put into a CSE map, add it. 5149 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5150 return N; 5151 } 5152 5153 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 5154 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 5155 5156 // Check to see if there is no change. 5157 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 5158 return N; // No operands changed, just return the input node. 5159 5160 // See if the modified node already exists. 5161 void *InsertPos = nullptr; 5162 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 5163 return Existing; 5164 5165 // Nope it doesn't. Remove the node from its current place in the maps. 5166 if (InsertPos) 5167 if (!RemoveNodeFromCSEMaps(N)) 5168 InsertPos = nullptr; 5169 5170 // Now we update the operands. 5171 if (N->OperandList[0] != Op1) 5172 N->OperandList[0].set(Op1); 5173 if (N->OperandList[1] != Op2) 5174 N->OperandList[1].set(Op2); 5175 5176 // If this gets put into a CSE map, add it. 5177 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5178 return N; 5179 } 5180 5181 SDNode *SelectionDAG:: 5182 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 5183 SDValue Ops[] = { Op1, Op2, Op3 }; 5184 return UpdateNodeOperands(N, Ops); 5185 } 5186 5187 SDNode *SelectionDAG:: 5188 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 5189 SDValue Op3, SDValue Op4) { 5190 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 5191 return UpdateNodeOperands(N, Ops); 5192 } 5193 5194 SDNode *SelectionDAG:: 5195 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 5196 SDValue Op3, SDValue Op4, SDValue Op5) { 5197 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 5198 return UpdateNodeOperands(N, Ops); 5199 } 5200 5201 SDNode *SelectionDAG:: 5202 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 5203 unsigned NumOps = Ops.size(); 5204 assert(N->getNumOperands() == NumOps && 5205 "Update with wrong number of operands"); 5206 5207 // Check to see if there is no change. 5208 bool AnyChange = false; 5209 for (unsigned i = 0; i != NumOps; ++i) { 5210 if (Ops[i] != N->getOperand(i)) { 5211 AnyChange = true; 5212 break; 5213 } 5214 } 5215 5216 // No operands changed, just return the input node. 5217 if (!AnyChange) return N; 5218 5219 // See if the modified node already exists. 5220 void *InsertPos = nullptr; 5221 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 5222 return Existing; 5223 5224 // Nope it doesn't. Remove the node from its current place in the maps. 5225 if (InsertPos) 5226 if (!RemoveNodeFromCSEMaps(N)) 5227 InsertPos = nullptr; 5228 5229 // Now we update the operands. 5230 for (unsigned i = 0; i != NumOps; ++i) 5231 if (N->OperandList[i] != Ops[i]) 5232 N->OperandList[i].set(Ops[i]); 5233 5234 // If this gets put into a CSE map, add it. 5235 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5236 return N; 5237 } 5238 5239 /// DropOperands - Release the operands and set this node to have 5240 /// zero operands. 5241 void SDNode::DropOperands() { 5242 // Unlike the code in MorphNodeTo that does this, we don't need to 5243 // watch for dead nodes here. 5244 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 5245 SDUse &Use = *I++; 5246 Use.set(SDValue()); 5247 } 5248 } 5249 5250 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 5251 /// machine opcode. 5252 /// 5253 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5254 EVT VT) { 5255 SDVTList VTs = getVTList(VT); 5256 return SelectNodeTo(N, MachineOpc, VTs, None); 5257 } 5258 5259 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5260 EVT VT, SDValue Op1) { 5261 SDVTList VTs = getVTList(VT); 5262 SDValue Ops[] = { Op1 }; 5263 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5264 } 5265 5266 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5267 EVT VT, SDValue Op1, 5268 SDValue Op2) { 5269 SDVTList VTs = getVTList(VT); 5270 SDValue Ops[] = { Op1, Op2 }; 5271 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5272 } 5273 5274 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5275 EVT VT, SDValue Op1, 5276 SDValue Op2, SDValue Op3) { 5277 SDVTList VTs = getVTList(VT); 5278 SDValue Ops[] = { Op1, Op2, Op3 }; 5279 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5280 } 5281 5282 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5283 EVT VT, ArrayRef<SDValue> Ops) { 5284 SDVTList VTs = getVTList(VT); 5285 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5286 } 5287 5288 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5289 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 5290 SDVTList VTs = getVTList(VT1, VT2); 5291 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5292 } 5293 5294 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5295 EVT VT1, EVT VT2) { 5296 SDVTList VTs = getVTList(VT1, VT2); 5297 return SelectNodeTo(N, MachineOpc, VTs, None); 5298 } 5299 5300 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5301 EVT VT1, EVT VT2, EVT VT3, 5302 ArrayRef<SDValue> Ops) { 5303 SDVTList VTs = getVTList(VT1, VT2, VT3); 5304 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5305 } 5306 5307 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5308 EVT VT1, EVT VT2, EVT VT3, EVT VT4, 5309 ArrayRef<SDValue> Ops) { 5310 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4); 5311 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5312 } 5313 5314 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5315 EVT VT1, EVT VT2, 5316 SDValue Op1) { 5317 SDVTList VTs = getVTList(VT1, VT2); 5318 SDValue Ops[] = { Op1 }; 5319 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5320 } 5321 5322 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5323 EVT VT1, EVT VT2, 5324 SDValue Op1, SDValue Op2) { 5325 SDVTList VTs = getVTList(VT1, VT2); 5326 SDValue Ops[] = { Op1, Op2 }; 5327 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5328 } 5329 5330 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5331 EVT VT1, EVT VT2, 5332 SDValue Op1, SDValue Op2, 5333 SDValue Op3) { 5334 SDVTList VTs = getVTList(VT1, VT2); 5335 SDValue Ops[] = { Op1, Op2, Op3 }; 5336 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5337 } 5338 5339 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5340 EVT VT1, EVT VT2, EVT VT3, 5341 SDValue Op1, SDValue Op2, 5342 SDValue Op3) { 5343 SDVTList VTs = getVTList(VT1, VT2, VT3); 5344 SDValue Ops[] = { Op1, Op2, Op3 }; 5345 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5346 } 5347 5348 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5349 SDVTList VTs,ArrayRef<SDValue> Ops) { 5350 N = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 5351 // Reset the NodeID to -1. 5352 N->setNodeId(-1); 5353 return N; 5354 } 5355 5356 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away 5357 /// the line number information on the merged node since it is not possible to 5358 /// preserve the information that operation is associated with multiple lines. 5359 /// This will make the debugger working better at -O0, were there is a higher 5360 /// probability having other instructions associated with that line. 5361 /// 5362 /// For IROrder, we keep the smaller of the two 5363 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, SDLoc OLoc) { 5364 DebugLoc NLoc = N->getDebugLoc(); 5365 if (!(NLoc.isUnknown()) && (OptLevel == CodeGenOpt::None) && 5366 (OLoc.getDebugLoc() != NLoc)) { 5367 N->setDebugLoc(DebugLoc()); 5368 } 5369 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 5370 N->setIROrder(Order); 5371 return N; 5372 } 5373 5374 /// MorphNodeTo - This *mutates* the specified node to have the specified 5375 /// return type, opcode, and operands. 5376 /// 5377 /// Note that MorphNodeTo returns the resultant node. If there is already a 5378 /// node of the specified opcode and operands, it returns that node instead of 5379 /// the current one. Note that the SDLoc need not be the same. 5380 /// 5381 /// Using MorphNodeTo is faster than creating a new node and swapping it in 5382 /// with ReplaceAllUsesWith both because it often avoids allocating a new 5383 /// node, and because it doesn't require CSE recalculation for any of 5384 /// the node's users. 5385 /// 5386 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 5387 SDVTList VTs, ArrayRef<SDValue> Ops) { 5388 unsigned NumOps = Ops.size(); 5389 // If an identical node already exists, use it. 5390 void *IP = nullptr; 5391 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 5392 FoldingSetNodeID ID; 5393 AddNodeIDNode(ID, Opc, VTs, Ops); 5394 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) 5395 return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N)); 5396 } 5397 5398 if (!RemoveNodeFromCSEMaps(N)) 5399 IP = nullptr; 5400 5401 // Start the morphing. 5402 N->NodeType = Opc; 5403 N->ValueList = VTs.VTs; 5404 N->NumValues = VTs.NumVTs; 5405 5406 // Clear the operands list, updating used nodes to remove this from their 5407 // use list. Keep track of any operands that become dead as a result. 5408 SmallPtrSet<SDNode*, 16> DeadNodeSet; 5409 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 5410 SDUse &Use = *I++; 5411 SDNode *Used = Use.getNode(); 5412 Use.set(SDValue()); 5413 if (Used->use_empty()) 5414 DeadNodeSet.insert(Used); 5415 } 5416 5417 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) { 5418 // Initialize the memory references information. 5419 MN->setMemRefs(nullptr, nullptr); 5420 // If NumOps is larger than the # of operands we can have in a 5421 // MachineSDNode, reallocate the operand list. 5422 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) { 5423 if (MN->OperandsNeedDelete) 5424 delete[] MN->OperandList; 5425 if (NumOps > array_lengthof(MN->LocalOperands)) 5426 // We're creating a final node that will live unmorphed for the 5427 // remainder of the current SelectionDAG iteration, so we can allocate 5428 // the operands directly out of a pool with no recycling metadata. 5429 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps), 5430 Ops.data(), NumOps); 5431 else 5432 MN->InitOperands(MN->LocalOperands, Ops.data(), NumOps); 5433 MN->OperandsNeedDelete = false; 5434 } else 5435 MN->InitOperands(MN->OperandList, Ops.data(), NumOps); 5436 } else { 5437 // If NumOps is larger than the # of operands we currently have, reallocate 5438 // the operand list. 5439 if (NumOps > N->NumOperands) { 5440 if (N->OperandsNeedDelete) 5441 delete[] N->OperandList; 5442 N->InitOperands(new SDUse[NumOps], Ops.data(), NumOps); 5443 N->OperandsNeedDelete = true; 5444 } else 5445 N->InitOperands(N->OperandList, Ops.data(), NumOps); 5446 } 5447 5448 // Delete any nodes that are still dead after adding the uses for the 5449 // new operands. 5450 if (!DeadNodeSet.empty()) { 5451 SmallVector<SDNode *, 16> DeadNodes; 5452 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(), 5453 E = DeadNodeSet.end(); I != E; ++I) 5454 if ((*I)->use_empty()) 5455 DeadNodes.push_back(*I); 5456 RemoveDeadNodes(DeadNodes); 5457 } 5458 5459 if (IP) 5460 CSEMap.InsertNode(N, IP); // Memoize the new node. 5461 return N; 5462 } 5463 5464 5465 /// getMachineNode - These are used for target selectors to create a new node 5466 /// with specified return type(s), MachineInstr opcode, and operands. 5467 /// 5468 /// Note that getMachineNode returns the resultant node. If there is already a 5469 /// node of the specified opcode and operands, it returns that node instead of 5470 /// the current one. 5471 MachineSDNode * 5472 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT) { 5473 SDVTList VTs = getVTList(VT); 5474 return getMachineNode(Opcode, dl, VTs, None); 5475 } 5476 5477 MachineSDNode * 5478 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, SDValue Op1) { 5479 SDVTList VTs = getVTList(VT); 5480 SDValue Ops[] = { Op1 }; 5481 return getMachineNode(Opcode, dl, VTs, Ops); 5482 } 5483 5484 MachineSDNode * 5485 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, 5486 SDValue Op1, SDValue Op2) { 5487 SDVTList VTs = getVTList(VT); 5488 SDValue Ops[] = { Op1, Op2 }; 5489 return getMachineNode(Opcode, dl, VTs, Ops); 5490 } 5491 5492 MachineSDNode * 5493 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, 5494 SDValue Op1, SDValue Op2, SDValue Op3) { 5495 SDVTList VTs = getVTList(VT); 5496 SDValue Ops[] = { Op1, Op2, Op3 }; 5497 return getMachineNode(Opcode, dl, VTs, Ops); 5498 } 5499 5500 MachineSDNode * 5501 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, 5502 ArrayRef<SDValue> Ops) { 5503 SDVTList VTs = getVTList(VT); 5504 return getMachineNode(Opcode, dl, VTs, Ops); 5505 } 5506 5507 MachineSDNode * 5508 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2) { 5509 SDVTList VTs = getVTList(VT1, VT2); 5510 return getMachineNode(Opcode, dl, VTs, None); 5511 } 5512 5513 MachineSDNode * 5514 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 5515 EVT VT1, EVT VT2, SDValue Op1) { 5516 SDVTList VTs = getVTList(VT1, VT2); 5517 SDValue Ops[] = { Op1 }; 5518 return getMachineNode(Opcode, dl, VTs, Ops); 5519 } 5520 5521 MachineSDNode * 5522 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 5523 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) { 5524 SDVTList VTs = getVTList(VT1, VT2); 5525 SDValue Ops[] = { Op1, Op2 }; 5526 return getMachineNode(Opcode, dl, VTs, Ops); 5527 } 5528 5529 MachineSDNode * 5530 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 5531 EVT VT1, EVT VT2, SDValue Op1, 5532 SDValue Op2, SDValue Op3) { 5533 SDVTList VTs = getVTList(VT1, VT2); 5534 SDValue Ops[] = { Op1, Op2, Op3 }; 5535 return getMachineNode(Opcode, dl, VTs, Ops); 5536 } 5537 5538 MachineSDNode * 5539 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 5540 EVT VT1, EVT VT2, 5541 ArrayRef<SDValue> Ops) { 5542 SDVTList VTs = getVTList(VT1, VT2); 5543 return getMachineNode(Opcode, dl, VTs, Ops); 5544 } 5545 5546 MachineSDNode * 5547 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 5548 EVT VT1, EVT VT2, EVT VT3, 5549 SDValue Op1, SDValue Op2) { 5550 SDVTList VTs = getVTList(VT1, VT2, VT3); 5551 SDValue Ops[] = { Op1, Op2 }; 5552 return getMachineNode(Opcode, dl, VTs, Ops); 5553 } 5554 5555 MachineSDNode * 5556 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 5557 EVT VT1, EVT VT2, EVT VT3, 5558 SDValue Op1, SDValue Op2, SDValue Op3) { 5559 SDVTList VTs = getVTList(VT1, VT2, VT3); 5560 SDValue Ops[] = { Op1, Op2, Op3 }; 5561 return getMachineNode(Opcode, dl, VTs, Ops); 5562 } 5563 5564 MachineSDNode * 5565 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 5566 EVT VT1, EVT VT2, EVT VT3, 5567 ArrayRef<SDValue> Ops) { 5568 SDVTList VTs = getVTList(VT1, VT2, VT3); 5569 return getMachineNode(Opcode, dl, VTs, Ops); 5570 } 5571 5572 MachineSDNode * 5573 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, 5574 EVT VT2, EVT VT3, EVT VT4, 5575 ArrayRef<SDValue> Ops) { 5576 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4); 5577 return getMachineNode(Opcode, dl, VTs, Ops); 5578 } 5579 5580 MachineSDNode * 5581 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, 5582 ArrayRef<EVT> ResultTys, 5583 ArrayRef<SDValue> Ops) { 5584 SDVTList VTs = getVTList(ResultTys); 5585 return getMachineNode(Opcode, dl, VTs, Ops); 5586 } 5587 5588 MachineSDNode * 5589 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc DL, SDVTList VTs, 5590 ArrayRef<SDValue> OpsArray) { 5591 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 5592 MachineSDNode *N; 5593 void *IP = nullptr; 5594 const SDValue *Ops = OpsArray.data(); 5595 unsigned NumOps = OpsArray.size(); 5596 5597 if (DoCSE) { 5598 FoldingSetNodeID ID; 5599 AddNodeIDNode(ID, ~Opcode, VTs, OpsArray); 5600 IP = nullptr; 5601 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) { 5602 return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL)); 5603 } 5604 } 5605 5606 // Allocate a new MachineSDNode. 5607 N = new (NodeAllocator) MachineSDNode(~Opcode, DL.getIROrder(), 5608 DL.getDebugLoc(), VTs); 5609 5610 // Initialize the operands list. 5611 if (NumOps > array_lengthof(N->LocalOperands)) 5612 // We're creating a final node that will live unmorphed for the 5613 // remainder of the current SelectionDAG iteration, so we can allocate 5614 // the operands directly out of a pool with no recycling metadata. 5615 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps), 5616 Ops, NumOps); 5617 else 5618 N->InitOperands(N->LocalOperands, Ops, NumOps); 5619 N->OperandsNeedDelete = false; 5620 5621 if (DoCSE) 5622 CSEMap.InsertNode(N, IP); 5623 5624 AllNodes.push_back(N); 5625 #ifndef NDEBUG 5626 VerifyMachineNode(N); 5627 #endif 5628 return N; 5629 } 5630 5631 /// getTargetExtractSubreg - A convenience function for creating 5632 /// TargetOpcode::EXTRACT_SUBREG nodes. 5633 SDValue 5634 SelectionDAG::getTargetExtractSubreg(int SRIdx, SDLoc DL, EVT VT, 5635 SDValue Operand) { 5636 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32); 5637 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 5638 VT, Operand, SRIdxVal); 5639 return SDValue(Subreg, 0); 5640 } 5641 5642 /// getTargetInsertSubreg - A convenience function for creating 5643 /// TargetOpcode::INSERT_SUBREG nodes. 5644 SDValue 5645 SelectionDAG::getTargetInsertSubreg(int SRIdx, SDLoc DL, EVT VT, 5646 SDValue Operand, SDValue Subreg) { 5647 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32); 5648 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 5649 VT, Operand, Subreg, SRIdxVal); 5650 return SDValue(Result, 0); 5651 } 5652 5653 /// getNodeIfExists - Get the specified node if it's already available, or 5654 /// else return NULL. 5655 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 5656 ArrayRef<SDValue> Ops, bool nuw, bool nsw, 5657 bool exact) { 5658 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 5659 FoldingSetNodeID ID; 5660 AddNodeIDNode(ID, Opcode, VTList, Ops); 5661 if (isBinOpWithFlags(Opcode)) 5662 AddBinaryNodeIDCustom(ID, nuw, nsw, exact); 5663 void *IP = nullptr; 5664 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 5665 return E; 5666 } 5667 return nullptr; 5668 } 5669 5670 /// getDbgValue - Creates a SDDbgValue node. 5671 /// 5672 /// SDNode 5673 SDDbgValue * 5674 SelectionDAG::getDbgValue(MDNode *MDPtr, SDNode *N, unsigned R, 5675 bool IsIndirect, uint64_t Off, 5676 DebugLoc DL, unsigned O) { 5677 return new (Allocator) SDDbgValue(MDPtr, N, R, IsIndirect, Off, DL, O); 5678 } 5679 5680 /// Constant 5681 SDDbgValue * 5682 SelectionDAG::getConstantDbgValue(MDNode *MDPtr, const Value *C, 5683 uint64_t Off, 5684 DebugLoc DL, unsigned O) { 5685 return new (Allocator) SDDbgValue(MDPtr, C, Off, DL, O); 5686 } 5687 5688 /// FrameIndex 5689 SDDbgValue * 5690 SelectionDAG::getFrameIndexDbgValue(MDNode *MDPtr, unsigned FI, uint64_t Off, 5691 DebugLoc DL, unsigned O) { 5692 return new (Allocator) SDDbgValue(MDPtr, FI, Off, DL, O); 5693 } 5694 5695 namespace { 5696 5697 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 5698 /// pointed to by a use iterator is deleted, increment the use iterator 5699 /// so that it doesn't dangle. 5700 /// 5701 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 5702 SDNode::use_iterator &UI; 5703 SDNode::use_iterator &UE; 5704 5705 void NodeDeleted(SDNode *N, SDNode *E) override { 5706 // Increment the iterator as needed. 5707 while (UI != UE && N == *UI) 5708 ++UI; 5709 } 5710 5711 public: 5712 RAUWUpdateListener(SelectionDAG &d, 5713 SDNode::use_iterator &ui, 5714 SDNode::use_iterator &ue) 5715 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 5716 }; 5717 5718 } 5719 5720 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 5721 /// This can cause recursive merging of nodes in the DAG. 5722 /// 5723 /// This version assumes From has a single result value. 5724 /// 5725 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 5726 SDNode *From = FromN.getNode(); 5727 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 5728 "Cannot replace with this method!"); 5729 assert(From != To.getNode() && "Cannot replace uses of with self"); 5730 5731 // Iterate over all the existing uses of From. New uses will be added 5732 // to the beginning of the use list, which we avoid visiting. 5733 // This specifically avoids visiting uses of From that arise while the 5734 // replacement is happening, because any such uses would be the result 5735 // of CSE: If an existing node looks like From after one of its operands 5736 // is replaced by To, we don't want to replace of all its users with To 5737 // too. See PR3018 for more info. 5738 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 5739 RAUWUpdateListener Listener(*this, UI, UE); 5740 while (UI != UE) { 5741 SDNode *User = *UI; 5742 5743 // This node is about to morph, remove its old self from the CSE maps. 5744 RemoveNodeFromCSEMaps(User); 5745 5746 // A user can appear in a use list multiple times, and when this 5747 // happens the uses are usually next to each other in the list. 5748 // To help reduce the number of CSE recomputations, process all 5749 // the uses of this user that we can find this way. 5750 do { 5751 SDUse &Use = UI.getUse(); 5752 ++UI; 5753 Use.set(To); 5754 } while (UI != UE && *UI == User); 5755 5756 // Now that we have modified User, add it back to the CSE maps. If it 5757 // already exists there, recursively merge the results together. 5758 AddModifiedNodeToCSEMaps(User); 5759 } 5760 5761 // If we just RAUW'd the root, take note. 5762 if (FromN == getRoot()) 5763 setRoot(To); 5764 } 5765 5766 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 5767 /// This can cause recursive merging of nodes in the DAG. 5768 /// 5769 /// This version assumes that for each value of From, there is a 5770 /// corresponding value in To in the same position with the same type. 5771 /// 5772 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 5773 #ifndef NDEBUG 5774 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 5775 assert((!From->hasAnyUseOfValue(i) || 5776 From->getValueType(i) == To->getValueType(i)) && 5777 "Cannot use this version of ReplaceAllUsesWith!"); 5778 #endif 5779 5780 // Handle the trivial case. 5781 if (From == To) 5782 return; 5783 5784 // Iterate over just the existing users of From. See the comments in 5785 // the ReplaceAllUsesWith above. 5786 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 5787 RAUWUpdateListener Listener(*this, UI, UE); 5788 while (UI != UE) { 5789 SDNode *User = *UI; 5790 5791 // This node is about to morph, remove its old self from the CSE maps. 5792 RemoveNodeFromCSEMaps(User); 5793 5794 // A user can appear in a use list multiple times, and when this 5795 // happens the uses are usually next to each other in the list. 5796 // To help reduce the number of CSE recomputations, process all 5797 // the uses of this user that we can find this way. 5798 do { 5799 SDUse &Use = UI.getUse(); 5800 ++UI; 5801 Use.setNode(To); 5802 } while (UI != UE && *UI == User); 5803 5804 // Now that we have modified User, add it back to the CSE maps. If it 5805 // already exists there, recursively merge the results together. 5806 AddModifiedNodeToCSEMaps(User); 5807 } 5808 5809 // If we just RAUW'd the root, take note. 5810 if (From == getRoot().getNode()) 5811 setRoot(SDValue(To, getRoot().getResNo())); 5812 } 5813 5814 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 5815 /// This can cause recursive merging of nodes in the DAG. 5816 /// 5817 /// This version can replace From with any result values. To must match the 5818 /// number and types of values returned by From. 5819 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 5820 if (From->getNumValues() == 1) // Handle the simple case efficiently. 5821 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 5822 5823 // Iterate over just the existing users of From. See the comments in 5824 // the ReplaceAllUsesWith above. 5825 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 5826 RAUWUpdateListener Listener(*this, UI, UE); 5827 while (UI != UE) { 5828 SDNode *User = *UI; 5829 5830 // This node is about to morph, remove its old self from the CSE maps. 5831 RemoveNodeFromCSEMaps(User); 5832 5833 // A user can appear in a use list multiple times, and when this 5834 // happens the uses are usually next to each other in the list. 5835 // To help reduce the number of CSE recomputations, process all 5836 // the uses of this user that we can find this way. 5837 do { 5838 SDUse &Use = UI.getUse(); 5839 const SDValue &ToOp = To[Use.getResNo()]; 5840 ++UI; 5841 Use.set(ToOp); 5842 } while (UI != UE && *UI == User); 5843 5844 // Now that we have modified User, add it back to the CSE maps. If it 5845 // already exists there, recursively merge the results together. 5846 AddModifiedNodeToCSEMaps(User); 5847 } 5848 5849 // If we just RAUW'd the root, take note. 5850 if (From == getRoot().getNode()) 5851 setRoot(SDValue(To[getRoot().getResNo()])); 5852 } 5853 5854 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 5855 /// uses of other values produced by From.getNode() alone. The Deleted 5856 /// vector is handled the same way as for ReplaceAllUsesWith. 5857 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 5858 // Handle the really simple, really trivial case efficiently. 5859 if (From == To) return; 5860 5861 // Handle the simple, trivial, case efficiently. 5862 if (From.getNode()->getNumValues() == 1) { 5863 ReplaceAllUsesWith(From, To); 5864 return; 5865 } 5866 5867 // Iterate over just the existing users of From. See the comments in 5868 // the ReplaceAllUsesWith above. 5869 SDNode::use_iterator UI = From.getNode()->use_begin(), 5870 UE = From.getNode()->use_end(); 5871 RAUWUpdateListener Listener(*this, UI, UE); 5872 while (UI != UE) { 5873 SDNode *User = *UI; 5874 bool UserRemovedFromCSEMaps = false; 5875 5876 // A user can appear in a use list multiple times, and when this 5877 // happens the uses are usually next to each other in the list. 5878 // To help reduce the number of CSE recomputations, process all 5879 // the uses of this user that we can find this way. 5880 do { 5881 SDUse &Use = UI.getUse(); 5882 5883 // Skip uses of different values from the same node. 5884 if (Use.getResNo() != From.getResNo()) { 5885 ++UI; 5886 continue; 5887 } 5888 5889 // If this node hasn't been modified yet, it's still in the CSE maps, 5890 // so remove its old self from the CSE maps. 5891 if (!UserRemovedFromCSEMaps) { 5892 RemoveNodeFromCSEMaps(User); 5893 UserRemovedFromCSEMaps = true; 5894 } 5895 5896 ++UI; 5897 Use.set(To); 5898 } while (UI != UE && *UI == User); 5899 5900 // We are iterating over all uses of the From node, so if a use 5901 // doesn't use the specific value, no changes are made. 5902 if (!UserRemovedFromCSEMaps) 5903 continue; 5904 5905 // Now that we have modified User, add it back to the CSE maps. If it 5906 // already exists there, recursively merge the results together. 5907 AddModifiedNodeToCSEMaps(User); 5908 } 5909 5910 // If we just RAUW'd the root, take note. 5911 if (From == getRoot()) 5912 setRoot(To); 5913 } 5914 5915 namespace { 5916 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 5917 /// to record information about a use. 5918 struct UseMemo { 5919 SDNode *User; 5920 unsigned Index; 5921 SDUse *Use; 5922 }; 5923 5924 /// operator< - Sort Memos by User. 5925 bool operator<(const UseMemo &L, const UseMemo &R) { 5926 return (intptr_t)L.User < (intptr_t)R.User; 5927 } 5928 } 5929 5930 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 5931 /// uses of other values produced by From.getNode() alone. The same value 5932 /// may appear in both the From and To list. The Deleted vector is 5933 /// handled the same way as for ReplaceAllUsesWith. 5934 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 5935 const SDValue *To, 5936 unsigned Num){ 5937 // Handle the simple, trivial case efficiently. 5938 if (Num == 1) 5939 return ReplaceAllUsesOfValueWith(*From, *To); 5940 5941 // Read up all the uses and make records of them. This helps 5942 // processing new uses that are introduced during the 5943 // replacement process. 5944 SmallVector<UseMemo, 4> Uses; 5945 for (unsigned i = 0; i != Num; ++i) { 5946 unsigned FromResNo = From[i].getResNo(); 5947 SDNode *FromNode = From[i].getNode(); 5948 for (SDNode::use_iterator UI = FromNode->use_begin(), 5949 E = FromNode->use_end(); UI != E; ++UI) { 5950 SDUse &Use = UI.getUse(); 5951 if (Use.getResNo() == FromResNo) { 5952 UseMemo Memo = { *UI, i, &Use }; 5953 Uses.push_back(Memo); 5954 } 5955 } 5956 } 5957 5958 // Sort the uses, so that all the uses from a given User are together. 5959 std::sort(Uses.begin(), Uses.end()); 5960 5961 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 5962 UseIndex != UseIndexEnd; ) { 5963 // We know that this user uses some value of From. If it is the right 5964 // value, update it. 5965 SDNode *User = Uses[UseIndex].User; 5966 5967 // This node is about to morph, remove its old self from the CSE maps. 5968 RemoveNodeFromCSEMaps(User); 5969 5970 // The Uses array is sorted, so all the uses for a given User 5971 // are next to each other in the list. 5972 // To help reduce the number of CSE recomputations, process all 5973 // the uses of this user that we can find this way. 5974 do { 5975 unsigned i = Uses[UseIndex].Index; 5976 SDUse &Use = *Uses[UseIndex].Use; 5977 ++UseIndex; 5978 5979 Use.set(To[i]); 5980 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 5981 5982 // Now that we have modified User, add it back to the CSE maps. If it 5983 // already exists there, recursively merge the results together. 5984 AddModifiedNodeToCSEMaps(User); 5985 } 5986 } 5987 5988 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 5989 /// based on their topological order. It returns the maximum id and a vector 5990 /// of the SDNodes* in assigned order by reference. 5991 unsigned SelectionDAG::AssignTopologicalOrder() { 5992 5993 unsigned DAGSize = 0; 5994 5995 // SortedPos tracks the progress of the algorithm. Nodes before it are 5996 // sorted, nodes after it are unsorted. When the algorithm completes 5997 // it is at the end of the list. 5998 allnodes_iterator SortedPos = allnodes_begin(); 5999 6000 // Visit all the nodes. Move nodes with no operands to the front of 6001 // the list immediately. Annotate nodes that do have operands with their 6002 // operand count. Before we do this, the Node Id fields of the nodes 6003 // may contain arbitrary values. After, the Node Id fields for nodes 6004 // before SortedPos will contain the topological sort index, and the 6005 // Node Id fields for nodes At SortedPos and after will contain the 6006 // count of outstanding operands. 6007 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 6008 SDNode *N = I++; 6009 checkForCycles(N, this); 6010 unsigned Degree = N->getNumOperands(); 6011 if (Degree == 0) { 6012 // A node with no uses, add it to the result array immediately. 6013 N->setNodeId(DAGSize++); 6014 allnodes_iterator Q = N; 6015 if (Q != SortedPos) 6016 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 6017 assert(SortedPos != AllNodes.end() && "Overran node list"); 6018 ++SortedPos; 6019 } else { 6020 // Temporarily use the Node Id as scratch space for the degree count. 6021 N->setNodeId(Degree); 6022 } 6023 } 6024 6025 // Visit all the nodes. As we iterate, move nodes into sorted order, 6026 // such that by the time the end is reached all nodes will be sorted. 6027 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) { 6028 SDNode *N = I; 6029 checkForCycles(N, this); 6030 // N is in sorted position, so all its uses have one less operand 6031 // that needs to be sorted. 6032 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6033 UI != UE; ++UI) { 6034 SDNode *P = *UI; 6035 unsigned Degree = P->getNodeId(); 6036 assert(Degree != 0 && "Invalid node degree"); 6037 --Degree; 6038 if (Degree == 0) { 6039 // All of P's operands are sorted, so P may sorted now. 6040 P->setNodeId(DAGSize++); 6041 if (P != SortedPos) 6042 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 6043 assert(SortedPos != AllNodes.end() && "Overran node list"); 6044 ++SortedPos; 6045 } else { 6046 // Update P's outstanding operand count. 6047 P->setNodeId(Degree); 6048 } 6049 } 6050 if (I == SortedPos) { 6051 #ifndef NDEBUG 6052 SDNode *S = ++I; 6053 dbgs() << "Overran sorted position:\n"; 6054 S->dumprFull(this); dbgs() << "\n"; 6055 dbgs() << "Checking if this is due to cycles\n"; 6056 checkForCycles(this, true); 6057 #endif 6058 llvm_unreachable(nullptr); 6059 } 6060 } 6061 6062 assert(SortedPos == AllNodes.end() && 6063 "Topological sort incomplete!"); 6064 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 6065 "First node in topological sort is not the entry token!"); 6066 assert(AllNodes.front().getNodeId() == 0 && 6067 "First node in topological sort has non-zero id!"); 6068 assert(AllNodes.front().getNumOperands() == 0 && 6069 "First node in topological sort has operands!"); 6070 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 6071 "Last node in topologic sort has unexpected id!"); 6072 assert(AllNodes.back().use_empty() && 6073 "Last node in topologic sort has users!"); 6074 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 6075 return DAGSize; 6076 } 6077 6078 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 6079 /// value is produced by SD. 6080 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) { 6081 DbgInfo->add(DB, SD, isParameter); 6082 if (SD) 6083 SD->setHasDebugValue(true); 6084 } 6085 6086 /// TransferDbgValues - Transfer SDDbgValues. 6087 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) { 6088 if (From == To || !From.getNode()->getHasDebugValue()) 6089 return; 6090 SDNode *FromNode = From.getNode(); 6091 SDNode *ToNode = To.getNode(); 6092 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode); 6093 SmallVector<SDDbgValue *, 2> ClonedDVs; 6094 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end(); 6095 I != E; ++I) { 6096 SDDbgValue *Dbg = *I; 6097 if (Dbg->getKind() == SDDbgValue::SDNODE) { 6098 SDDbgValue *Clone = getDbgValue(Dbg->getMDPtr(), ToNode, To.getResNo(), 6099 Dbg->isIndirect(), 6100 Dbg->getOffset(), Dbg->getDebugLoc(), 6101 Dbg->getOrder()); 6102 ClonedDVs.push_back(Clone); 6103 } 6104 } 6105 for (SmallVectorImpl<SDDbgValue *>::iterator I = ClonedDVs.begin(), 6106 E = ClonedDVs.end(); I != E; ++I) 6107 AddDbgValue(*I, ToNode, false); 6108 } 6109 6110 //===----------------------------------------------------------------------===// 6111 // SDNode Class 6112 //===----------------------------------------------------------------------===// 6113 6114 HandleSDNode::~HandleSDNode() { 6115 DropOperands(); 6116 } 6117 6118 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 6119 DebugLoc DL, const GlobalValue *GA, 6120 EVT VT, int64_t o, unsigned char TF) 6121 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 6122 TheGlobal = GA; 6123 } 6124 6125 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, DebugLoc dl, EVT VT, 6126 SDValue X, unsigned SrcAS, 6127 unsigned DestAS) 6128 : UnarySDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT), X), 6129 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 6130 6131 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs, 6132 EVT memvt, MachineMemOperand *mmo) 6133 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 6134 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(), 6135 MMO->isNonTemporal(), MMO->isInvariant()); 6136 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!"); 6137 assert(isNonTemporal() == MMO->isNonTemporal() && 6138 "Non-temporal encoding error!"); 6139 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!"); 6140 } 6141 6142 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs, 6143 ArrayRef<SDValue> Ops, EVT memvt, MachineMemOperand *mmo) 6144 : SDNode(Opc, Order, dl, VTs, Ops), 6145 MemoryVT(memvt), MMO(mmo) { 6146 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(), 6147 MMO->isNonTemporal(), MMO->isInvariant()); 6148 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!"); 6149 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!"); 6150 } 6151 6152 /// Profile - Gather unique data for the node. 6153 /// 6154 void SDNode::Profile(FoldingSetNodeID &ID) const { 6155 AddNodeIDNode(ID, this); 6156 } 6157 6158 namespace { 6159 struct EVTArray { 6160 std::vector<EVT> VTs; 6161 6162 EVTArray() { 6163 VTs.reserve(MVT::LAST_VALUETYPE); 6164 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 6165 VTs.push_back(MVT((MVT::SimpleValueType)i)); 6166 } 6167 }; 6168 } 6169 6170 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs; 6171 static ManagedStatic<EVTArray> SimpleVTArray; 6172 static ManagedStatic<sys::SmartMutex<true> > VTMutex; 6173 6174 /// getValueTypeList - Return a pointer to the specified value type. 6175 /// 6176 const EVT *SDNode::getValueTypeList(EVT VT) { 6177 if (VT.isExtended()) { 6178 sys::SmartScopedLock<true> Lock(*VTMutex); 6179 return &(*EVTs->insert(VT).first); 6180 } else { 6181 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 6182 "Value type out of range!"); 6183 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 6184 } 6185 } 6186 6187 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 6188 /// indicated value. This method ignores uses of other values defined by this 6189 /// operation. 6190 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 6191 assert(Value < getNumValues() && "Bad value!"); 6192 6193 // TODO: Only iterate over uses of a given value of the node 6194 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 6195 if (UI.getUse().getResNo() == Value) { 6196 if (NUses == 0) 6197 return false; 6198 --NUses; 6199 } 6200 } 6201 6202 // Found exactly the right number of uses? 6203 return NUses == 0; 6204 } 6205 6206 6207 /// hasAnyUseOfValue - Return true if there are any use of the indicated 6208 /// value. This method ignores uses of other values defined by this operation. 6209 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 6210 assert(Value < getNumValues() && "Bad value!"); 6211 6212 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 6213 if (UI.getUse().getResNo() == Value) 6214 return true; 6215 6216 return false; 6217 } 6218 6219 6220 /// isOnlyUserOf - Return true if this node is the only use of N. 6221 /// 6222 bool SDNode::isOnlyUserOf(SDNode *N) const { 6223 bool Seen = false; 6224 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 6225 SDNode *User = *I; 6226 if (User == this) 6227 Seen = true; 6228 else 6229 return false; 6230 } 6231 6232 return Seen; 6233 } 6234 6235 /// isOperand - Return true if this node is an operand of N. 6236 /// 6237 bool SDValue::isOperandOf(SDNode *N) const { 6238 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 6239 if (*this == N->getOperand(i)) 6240 return true; 6241 return false; 6242 } 6243 6244 bool SDNode::isOperandOf(SDNode *N) const { 6245 for (unsigned i = 0, e = N->NumOperands; i != e; ++i) 6246 if (this == N->OperandList[i].getNode()) 6247 return true; 6248 return false; 6249 } 6250 6251 /// reachesChainWithoutSideEffects - Return true if this operand (which must 6252 /// be a chain) reaches the specified operand without crossing any 6253 /// side-effecting instructions on any chain path. In practice, this looks 6254 /// through token factors and non-volatile loads. In order to remain efficient, 6255 /// this only looks a couple of nodes in, it does not do an exhaustive search. 6256 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 6257 unsigned Depth) const { 6258 if (*this == Dest) return true; 6259 6260 // Don't search too deeply, we just want to be able to see through 6261 // TokenFactor's etc. 6262 if (Depth == 0) return false; 6263 6264 // If this is a token factor, all inputs to the TF happen in parallel. If any 6265 // of the operands of the TF does not reach dest, then we cannot do the xform. 6266 if (getOpcode() == ISD::TokenFactor) { 6267 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 6268 if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1)) 6269 return false; 6270 return true; 6271 } 6272 6273 // Loads don't have side effects, look through them. 6274 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 6275 if (!Ld->isVolatile()) 6276 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 6277 } 6278 return false; 6279 } 6280 6281 /// hasPredecessor - Return true if N is a predecessor of this node. 6282 /// N is either an operand of this node, or can be reached by recursively 6283 /// traversing up the operands. 6284 /// NOTE: This is an expensive method. Use it carefully. 6285 bool SDNode::hasPredecessor(const SDNode *N) const { 6286 SmallPtrSet<const SDNode *, 32> Visited; 6287 SmallVector<const SDNode *, 16> Worklist; 6288 return hasPredecessorHelper(N, Visited, Worklist); 6289 } 6290 6291 bool 6292 SDNode::hasPredecessorHelper(const SDNode *N, 6293 SmallPtrSet<const SDNode *, 32> &Visited, 6294 SmallVectorImpl<const SDNode *> &Worklist) const { 6295 if (Visited.empty()) { 6296 Worklist.push_back(this); 6297 } else { 6298 // Take a look in the visited set. If we've already encountered this node 6299 // we needn't search further. 6300 if (Visited.count(N)) 6301 return true; 6302 } 6303 6304 // Haven't visited N yet. Continue the search. 6305 while (!Worklist.empty()) { 6306 const SDNode *M = Worklist.pop_back_val(); 6307 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 6308 SDNode *Op = M->getOperand(i).getNode(); 6309 if (Visited.insert(Op)) 6310 Worklist.push_back(Op); 6311 if (Op == N) 6312 return true; 6313 } 6314 } 6315 6316 return false; 6317 } 6318 6319 uint64_t SDNode::getConstantOperandVal(unsigned Num) const { 6320 assert(Num < NumOperands && "Invalid child # of SDNode!"); 6321 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue(); 6322 } 6323 6324 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 6325 assert(N->getNumValues() == 1 && 6326 "Can't unroll a vector with multiple results!"); 6327 6328 EVT VT = N->getValueType(0); 6329 unsigned NE = VT.getVectorNumElements(); 6330 EVT EltVT = VT.getVectorElementType(); 6331 SDLoc dl(N); 6332 6333 SmallVector<SDValue, 8> Scalars; 6334 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 6335 6336 // If ResNE is 0, fully unroll the vector op. 6337 if (ResNE == 0) 6338 ResNE = NE; 6339 else if (NE > ResNE) 6340 NE = ResNE; 6341 6342 unsigned i; 6343 for (i= 0; i != NE; ++i) { 6344 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 6345 SDValue Operand = N->getOperand(j); 6346 EVT OperandVT = Operand.getValueType(); 6347 if (OperandVT.isVector()) { 6348 // A vector operand; extract a single element. 6349 const TargetLowering *TLI = TM.getTargetLowering(); 6350 EVT OperandEltVT = OperandVT.getVectorElementType(); 6351 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, 6352 OperandEltVT, 6353 Operand, 6354 getConstant(i, TLI->getVectorIdxTy())); 6355 } else { 6356 // A scalar operand; just use it as is. 6357 Operands[j] = Operand; 6358 } 6359 } 6360 6361 switch (N->getOpcode()) { 6362 default: 6363 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands)); 6364 break; 6365 case ISD::VSELECT: 6366 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 6367 break; 6368 case ISD::SHL: 6369 case ISD::SRA: 6370 case ISD::SRL: 6371 case ISD::ROTL: 6372 case ISD::ROTR: 6373 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 6374 getShiftAmountOperand(Operands[0].getValueType(), 6375 Operands[1]))); 6376 break; 6377 case ISD::SIGN_EXTEND_INREG: 6378 case ISD::FP_ROUND_INREG: { 6379 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 6380 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 6381 Operands[0], 6382 getValueType(ExtVT))); 6383 } 6384 } 6385 } 6386 6387 for (; i < ResNE; ++i) 6388 Scalars.push_back(getUNDEF(EltVT)); 6389 6390 return getNode(ISD::BUILD_VECTOR, dl, 6391 EVT::getVectorVT(*getContext(), EltVT, ResNE), Scalars); 6392 } 6393 6394 6395 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a 6396 /// location that is 'Dist' units away from the location that the 'Base' load 6397 /// is loading from. 6398 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base, 6399 unsigned Bytes, int Dist) const { 6400 if (LD->getChain() != Base->getChain()) 6401 return false; 6402 EVT VT = LD->getValueType(0); 6403 if (VT.getSizeInBits() / 8 != Bytes) 6404 return false; 6405 6406 SDValue Loc = LD->getOperand(1); 6407 SDValue BaseLoc = Base->getOperand(1); 6408 if (Loc.getOpcode() == ISD::FrameIndex) { 6409 if (BaseLoc.getOpcode() != ISD::FrameIndex) 6410 return false; 6411 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo(); 6412 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 6413 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 6414 int FS = MFI->getObjectSize(FI); 6415 int BFS = MFI->getObjectSize(BFI); 6416 if (FS != BFS || FS != (int)Bytes) return false; 6417 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes); 6418 } 6419 6420 // Handle X+C 6421 if (isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc && 6422 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes) 6423 return true; 6424 6425 const GlobalValue *GV1 = nullptr; 6426 const GlobalValue *GV2 = nullptr; 6427 int64_t Offset1 = 0; 6428 int64_t Offset2 = 0; 6429 const TargetLowering *TLI = TM.getTargetLowering(); 6430 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1); 6431 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 6432 if (isGA1 && isGA2 && GV1 == GV2) 6433 return Offset1 == (Offset2 + Dist*Bytes); 6434 return false; 6435 } 6436 6437 6438 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if 6439 /// it cannot be inferred. 6440 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const { 6441 // If this is a GlobalAddress + cst, return the alignment. 6442 const GlobalValue *GV; 6443 int64_t GVOffset = 0; 6444 const TargetLowering *TLI = TM.getTargetLowering(); 6445 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 6446 unsigned PtrWidth = TLI->getPointerTypeSizeInBits(GV->getType()); 6447 APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0); 6448 llvm::computeKnownBits(const_cast<GlobalValue*>(GV), KnownZero, KnownOne, 6449 TLI->getDataLayout()); 6450 unsigned AlignBits = KnownZero.countTrailingOnes(); 6451 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0; 6452 if (Align) 6453 return MinAlign(Align, GVOffset); 6454 } 6455 6456 // If this is a direct reference to a stack slot, use information about the 6457 // stack slot's alignment. 6458 int FrameIdx = 1 << 31; 6459 int64_t FrameOffset = 0; 6460 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 6461 FrameIdx = FI->getIndex(); 6462 } else if (isBaseWithConstantOffset(Ptr) && 6463 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 6464 // Handle FI+Cst 6465 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 6466 FrameOffset = Ptr.getConstantOperandVal(1); 6467 } 6468 6469 if (FrameIdx != (1 << 31)) { 6470 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo(); 6471 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx), 6472 FrameOffset); 6473 return FIInfoAlign; 6474 } 6475 6476 return 0; 6477 } 6478 6479 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 6480 /// which is split (or expanded) into two not necessarily identical pieces. 6481 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 6482 // Currently all types are split in half. 6483 EVT LoVT, HiVT; 6484 if (!VT.isVector()) { 6485 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 6486 } else { 6487 unsigned NumElements = VT.getVectorNumElements(); 6488 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 6489 LoVT = HiVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 6490 NumElements/2); 6491 } 6492 return std::make_pair(LoVT, HiVT); 6493 } 6494 6495 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 6496 /// low/high part. 6497 std::pair<SDValue, SDValue> 6498 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 6499 const EVT &HiVT) { 6500 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <= 6501 N.getValueType().getVectorNumElements() && 6502 "More vector elements requested than available!"); 6503 SDValue Lo, Hi; 6504 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, 6505 getConstant(0, TLI->getVectorIdxTy())); 6506 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 6507 getConstant(LoVT.getVectorNumElements(), TLI->getVectorIdxTy())); 6508 return std::make_pair(Lo, Hi); 6509 } 6510 6511 void SelectionDAG::ExtractVectorElements(SDValue Op, 6512 SmallVectorImpl<SDValue> &Args, 6513 unsigned Start, unsigned Count) { 6514 EVT VT = Op.getValueType(); 6515 if (Count == 0) 6516 Count = VT.getVectorNumElements(); 6517 6518 EVT EltVT = VT.getVectorElementType(); 6519 EVT IdxTy = TLI->getVectorIdxTy(); 6520 SDLoc SL(Op); 6521 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 6522 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 6523 Op, getConstant(i, IdxTy))); 6524 } 6525 } 6526 6527 // getAddressSpace - Return the address space this GlobalAddress belongs to. 6528 unsigned GlobalAddressSDNode::getAddressSpace() const { 6529 return getGlobal()->getType()->getAddressSpace(); 6530 } 6531 6532 6533 Type *ConstantPoolSDNode::getType() const { 6534 if (isMachineConstantPoolEntry()) 6535 return Val.MachineCPVal->getType(); 6536 return Val.ConstVal->getType(); 6537 } 6538 6539 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, 6540 APInt &SplatUndef, 6541 unsigned &SplatBitSize, 6542 bool &HasAnyUndefs, 6543 unsigned MinSplatBits, 6544 bool isBigEndian) const { 6545 EVT VT = getValueType(0); 6546 assert(VT.isVector() && "Expected a vector type"); 6547 unsigned sz = VT.getSizeInBits(); 6548 if (MinSplatBits > sz) 6549 return false; 6550 6551 SplatValue = APInt(sz, 0); 6552 SplatUndef = APInt(sz, 0); 6553 6554 // Get the bits. Bits with undefined values (when the corresponding element 6555 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 6556 // in SplatValue. If any of the values are not constant, give up and return 6557 // false. 6558 unsigned int nOps = getNumOperands(); 6559 assert(nOps > 0 && "isConstantSplat has 0-size build vector"); 6560 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits(); 6561 6562 for (unsigned j = 0; j < nOps; ++j) { 6563 unsigned i = isBigEndian ? nOps-1-j : j; 6564 SDValue OpVal = getOperand(i); 6565 unsigned BitPos = j * EltBitSize; 6566 6567 if (OpVal.getOpcode() == ISD::UNDEF) 6568 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize); 6569 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) 6570 SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize). 6571 zextOrTrunc(sz) << BitPos; 6572 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 6573 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos; 6574 else 6575 return false; 6576 } 6577 6578 // The build_vector is all constants or undefs. Find the smallest element 6579 // size that splats the vector. 6580 6581 HasAnyUndefs = (SplatUndef != 0); 6582 while (sz > 8) { 6583 6584 unsigned HalfSize = sz / 2; 6585 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 6586 APInt LowValue = SplatValue.trunc(HalfSize); 6587 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 6588 APInt LowUndef = SplatUndef.trunc(HalfSize); 6589 6590 // If the two halves do not match (ignoring undef bits), stop here. 6591 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 6592 MinSplatBits > HalfSize) 6593 break; 6594 6595 SplatValue = HighValue | LowValue; 6596 SplatUndef = HighUndef & LowUndef; 6597 6598 sz = HalfSize; 6599 } 6600 6601 SplatBitSize = sz; 6602 return true; 6603 } 6604 6605 ConstantSDNode *BuildVectorSDNode::getConstantSplatValue() const { 6606 SDValue Op0 = getOperand(0); 6607 if (Op0.getOpcode() != ISD::Constant) 6608 return nullptr; 6609 6610 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) 6611 if (getOperand(i) != Op0) 6612 return nullptr; 6613 6614 return cast<ConstantSDNode>(Op0); 6615 } 6616 6617 bool BuildVectorSDNode::isConstant() const { 6618 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 6619 unsigned Opc = getOperand(i).getOpcode(); 6620 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 6621 return false; 6622 } 6623 return true; 6624 } 6625 6626 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 6627 // Find the first non-undef value in the shuffle mask. 6628 unsigned i, e; 6629 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 6630 /* search */; 6631 6632 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!"); 6633 6634 // Make sure all remaining elements are either undef or the same as the first 6635 // non-undef value. 6636 for (int Idx = Mask[i]; i != e; ++i) 6637 if (Mask[i] >= 0 && Mask[i] != Idx) 6638 return false; 6639 return true; 6640 } 6641 6642 #ifndef NDEBUG 6643 static void checkForCyclesHelper(const SDNode *N, 6644 SmallPtrSet<const SDNode*, 32> &Visited, 6645 SmallPtrSet<const SDNode*, 32> &Checked, 6646 const llvm::SelectionDAG *DAG) { 6647 // If this node has already been checked, don't check it again. 6648 if (Checked.count(N)) 6649 return; 6650 6651 // If a node has already been visited on this depth-first walk, reject it as 6652 // a cycle. 6653 if (!Visited.insert(N)) { 6654 errs() << "Detected cycle in SelectionDAG\n"; 6655 dbgs() << "Offending node:\n"; 6656 N->dumprFull(DAG); dbgs() << "\n"; 6657 abort(); 6658 } 6659 6660 for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 6661 checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked, DAG); 6662 6663 Checked.insert(N); 6664 Visited.erase(N); 6665 } 6666 #endif 6667 6668 void llvm::checkForCycles(const llvm::SDNode *N, 6669 const llvm::SelectionDAG *DAG, 6670 bool force) { 6671 #ifndef NDEBUG 6672 bool check = force; 6673 #ifdef XDEBUG 6674 check = true; 6675 #endif // XDEBUG 6676 if (check) { 6677 assert(N && "Checking nonexistent SDNode"); 6678 SmallPtrSet<const SDNode*, 32> visited; 6679 SmallPtrSet<const SDNode*, 32> checked; 6680 checkForCyclesHelper(N, visited, checked, DAG); 6681 } 6682 #endif // !NDEBUG 6683 } 6684 6685 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 6686 checkForCycles(DAG->getRoot().getNode(), DAG, force); 6687 } 6688