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