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).getVectorElementType().getSizeInBits(); 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).getVectorElementType().getSizeInBits(); 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.getValueType().getScalarType().getSizeInBits(); 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.getValueType().getSizeInBits() && 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.getValueType().getSizeInBits() && 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.getValueType().getSizeInBits() && 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 // This predicate is not safe for vector operations. 1984 if (Op.getValueType().isVector()) 1985 return false; 1986 1987 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 1988 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth); 1989 } 1990 1991 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 1992 /// this predicate to simplify operations downstream. Mask is known to be zero 1993 /// for bits that V cannot have. 1994 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask, 1995 unsigned Depth) const { 1996 APInt KnownZero, KnownOne; 1997 computeKnownBits(Op, KnownZero, KnownOne, Depth); 1998 return (KnownZero & Mask) == Mask; 1999 } 2000 2001 /// Determine which bits of Op are known to be either zero or one and return 2002 /// them in the KnownZero/KnownOne bitsets. 2003 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero, 2004 APInt &KnownOne, unsigned Depth) const { 2005 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 2006 2007 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything. 2008 if (Depth == 6) 2009 return; // Limit search depth. 2010 2011 APInt KnownZero2, KnownOne2; 2012 2013 switch (Op.getOpcode()) { 2014 case ISD::Constant: 2015 // We know all of the bits for a constant! 2016 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue(); 2017 KnownZero = ~KnownOne; 2018 break; 2019 case ISD::BUILD_VECTOR: 2020 // Collect the known bits that are shared by every vector element. 2021 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth); 2022 for (SDValue SrcOp : Op->ops()) { 2023 computeKnownBits(SrcOp, KnownZero2, KnownOne2, Depth + 1); 2024 2025 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2026 if (SrcOp.getValueSizeInBits() != BitWidth) { 2027 assert(SrcOp.getValueSizeInBits() > BitWidth && 2028 "Expected BUILD_VECTOR implicit truncation"); 2029 KnownOne2 = KnownOne2.trunc(BitWidth); 2030 KnownZero2 = KnownZero2.trunc(BitWidth); 2031 } 2032 2033 // Known bits are the values that are shared by every element. 2034 // TODO: support per-element known bits. 2035 KnownOne &= KnownOne2; 2036 KnownZero &= KnownZero2; 2037 } 2038 break; 2039 case ISD::AND: 2040 // If either the LHS or the RHS are Zero, the result is zero. 2041 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2042 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2043 2044 // Output known-1 bits are only known if set in both the LHS & RHS. 2045 KnownOne &= KnownOne2; 2046 // Output known-0 are known to be clear if zero in either the LHS | RHS. 2047 KnownZero |= KnownZero2; 2048 break; 2049 case ISD::OR: 2050 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2051 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2052 2053 // Output known-0 bits are only known if clear in both the LHS & RHS. 2054 KnownZero &= KnownZero2; 2055 // Output known-1 are known to be set if set in either the LHS | RHS. 2056 KnownOne |= KnownOne2; 2057 break; 2058 case ISD::XOR: { 2059 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2060 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2061 2062 // Output known-0 bits are known if clear or set in both the LHS & RHS. 2063 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 2064 // Output known-1 are known to be set if set in only one of the LHS, RHS. 2065 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 2066 KnownZero = KnownZeroOut; 2067 break; 2068 } 2069 case ISD::MUL: { 2070 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2071 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2072 2073 // If low bits are zero in either operand, output low known-0 bits. 2074 // Also compute a conserative estimate for high known-0 bits. 2075 // More trickiness is possible, but this is sufficient for the 2076 // interesting case of alignment computation. 2077 KnownOne.clearAllBits(); 2078 unsigned TrailZ = KnownZero.countTrailingOnes() + 2079 KnownZero2.countTrailingOnes(); 2080 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() + 2081 KnownZero2.countLeadingOnes(), 2082 BitWidth) - BitWidth; 2083 2084 TrailZ = std::min(TrailZ, BitWidth); 2085 LeadZ = std::min(LeadZ, BitWidth); 2086 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) | 2087 APInt::getHighBitsSet(BitWidth, LeadZ); 2088 break; 2089 } 2090 case ISD::UDIV: { 2091 // For the purposes of computing leading zeros we can conservatively 2092 // treat a udiv as a logical right shift by the power of 2 known to 2093 // be less than the denominator. 2094 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2095 unsigned LeadZ = KnownZero2.countLeadingOnes(); 2096 2097 KnownOne2.clearAllBits(); 2098 KnownZero2.clearAllBits(); 2099 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2100 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros(); 2101 if (RHSUnknownLeadingOnes != BitWidth) 2102 LeadZ = std::min(BitWidth, 2103 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); 2104 2105 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ); 2106 break; 2107 } 2108 case ISD::SELECT: 2109 computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1); 2110 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2111 2112 // Only known if known in both the LHS and RHS. 2113 KnownOne &= KnownOne2; 2114 KnownZero &= KnownZero2; 2115 break; 2116 case ISD::SELECT_CC: 2117 computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1); 2118 computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1); 2119 2120 // Only known if known in both the LHS and RHS. 2121 KnownOne &= KnownOne2; 2122 KnownZero &= KnownZero2; 2123 break; 2124 case ISD::SADDO: 2125 case ISD::UADDO: 2126 case ISD::SSUBO: 2127 case ISD::USUBO: 2128 case ISD::SMULO: 2129 case ISD::UMULO: 2130 if (Op.getResNo() != 1) 2131 break; 2132 // The boolean result conforms to getBooleanContents. 2133 // If we know the result of a setcc has the top bits zero, use this info. 2134 // We know that we have an integer-based boolean since these operations 2135 // are only available for integer. 2136 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 2137 TargetLowering::ZeroOrOneBooleanContent && 2138 BitWidth > 1) 2139 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2140 break; 2141 case ISD::SETCC: 2142 // If we know the result of a setcc has the top bits zero, use this info. 2143 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 2144 TargetLowering::ZeroOrOneBooleanContent && 2145 BitWidth > 1) 2146 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2147 break; 2148 case ISD::SHL: 2149 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0 2150 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2151 unsigned ShAmt = SA->getZExtValue(); 2152 2153 // If the shift count is an invalid immediate, don't do anything. 2154 if (ShAmt >= BitWidth) 2155 break; 2156 2157 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2158 KnownZero <<= ShAmt; 2159 KnownOne <<= ShAmt; 2160 // low bits known zero. 2161 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt); 2162 } 2163 break; 2164 case ISD::SRL: 2165 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 2166 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2167 unsigned ShAmt = SA->getZExtValue(); 2168 2169 // If the shift count is an invalid immediate, don't do anything. 2170 if (ShAmt >= BitWidth) 2171 break; 2172 2173 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2174 KnownZero = KnownZero.lshr(ShAmt); 2175 KnownOne = KnownOne.lshr(ShAmt); 2176 2177 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 2178 KnownZero |= HighBits; // High bits known zero. 2179 } 2180 break; 2181 case ISD::SRA: 2182 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2183 unsigned ShAmt = SA->getZExtValue(); 2184 2185 // If the shift count is an invalid immediate, don't do anything. 2186 if (ShAmt >= BitWidth) 2187 break; 2188 2189 // If any of the demanded bits are produced by the sign extension, we also 2190 // demand the input sign bit. 2191 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 2192 2193 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2194 KnownZero = KnownZero.lshr(ShAmt); 2195 KnownOne = KnownOne.lshr(ShAmt); 2196 2197 // Handle the sign bits. 2198 APInt SignBit = APInt::getSignBit(BitWidth); 2199 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask. 2200 2201 if (KnownZero.intersects(SignBit)) { 2202 KnownZero |= HighBits; // New bits are known zero. 2203 } else if (KnownOne.intersects(SignBit)) { 2204 KnownOne |= HighBits; // New bits are known one. 2205 } 2206 } 2207 break; 2208 case ISD::SIGN_EXTEND_INREG: { 2209 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2210 unsigned EBits = EVT.getScalarType().getSizeInBits(); 2211 2212 // Sign extension. Compute the demanded bits in the result that are not 2213 // present in the input. 2214 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits); 2215 2216 APInt InSignBit = APInt::getSignBit(EBits); 2217 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits); 2218 2219 // If the sign extended bits are demanded, we know that the sign 2220 // bit is demanded. 2221 InSignBit = InSignBit.zext(BitWidth); 2222 if (NewBits.getBoolValue()) 2223 InputDemandedBits |= InSignBit; 2224 2225 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2226 KnownOne &= InputDemandedBits; 2227 KnownZero &= InputDemandedBits; 2228 2229 // If the sign bit of the input is known set or clear, then we know the 2230 // top bits of the result. 2231 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear 2232 KnownZero |= NewBits; 2233 KnownOne &= ~NewBits; 2234 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 2235 KnownOne |= NewBits; 2236 KnownZero &= ~NewBits; 2237 } else { // Input sign bit unknown 2238 KnownZero &= ~NewBits; 2239 KnownOne &= ~NewBits; 2240 } 2241 break; 2242 } 2243 case ISD::CTTZ: 2244 case ISD::CTTZ_ZERO_UNDEF: 2245 case ISD::CTLZ: 2246 case ISD::CTLZ_ZERO_UNDEF: 2247 case ISD::CTPOP: { 2248 unsigned LowBits = Log2_32(BitWidth)+1; 2249 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits); 2250 KnownOne.clearAllBits(); 2251 break; 2252 } 2253 case ISD::LOAD: { 2254 LoadSDNode *LD = cast<LoadSDNode>(Op); 2255 // If this is a ZEXTLoad and we are looking at the loaded value. 2256 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 2257 EVT VT = LD->getMemoryVT(); 2258 unsigned MemBits = VT.getScalarType().getSizeInBits(); 2259 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 2260 } else if (const MDNode *Ranges = LD->getRanges()) { 2261 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 2262 computeKnownBitsFromRangeMetadata(*Ranges, KnownZero, KnownOne); 2263 } 2264 break; 2265 } 2266 case ISD::ZERO_EXTEND: { 2267 EVT InVT = Op.getOperand(0).getValueType(); 2268 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2269 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits); 2270 KnownZero = KnownZero.trunc(InBits); 2271 KnownOne = KnownOne.trunc(InBits); 2272 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2273 KnownZero = KnownZero.zext(BitWidth); 2274 KnownOne = KnownOne.zext(BitWidth); 2275 KnownZero |= NewBits; 2276 break; 2277 } 2278 case ISD::SIGN_EXTEND: { 2279 EVT InVT = Op.getOperand(0).getValueType(); 2280 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2281 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits); 2282 2283 KnownZero = KnownZero.trunc(InBits); 2284 KnownOne = KnownOne.trunc(InBits); 2285 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2286 2287 // Note if the sign bit is known to be zero or one. 2288 bool SignBitKnownZero = KnownZero.isNegative(); 2289 bool SignBitKnownOne = KnownOne.isNegative(); 2290 2291 KnownZero = KnownZero.zext(BitWidth); 2292 KnownOne = KnownOne.zext(BitWidth); 2293 2294 // If the sign bit is known zero or one, the top bits match. 2295 if (SignBitKnownZero) 2296 KnownZero |= NewBits; 2297 else if (SignBitKnownOne) 2298 KnownOne |= NewBits; 2299 break; 2300 } 2301 case ISD::ANY_EXTEND: { 2302 EVT InVT = Op.getOperand(0).getValueType(); 2303 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2304 KnownZero = KnownZero.trunc(InBits); 2305 KnownOne = KnownOne.trunc(InBits); 2306 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2307 KnownZero = KnownZero.zext(BitWidth); 2308 KnownOne = KnownOne.zext(BitWidth); 2309 break; 2310 } 2311 case ISD::TRUNCATE: { 2312 EVT InVT = Op.getOperand(0).getValueType(); 2313 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2314 KnownZero = KnownZero.zext(InBits); 2315 KnownOne = KnownOne.zext(InBits); 2316 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2317 KnownZero = KnownZero.trunc(BitWidth); 2318 KnownOne = KnownOne.trunc(BitWidth); 2319 break; 2320 } 2321 case ISD::AssertZext: { 2322 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2323 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 2324 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2325 KnownZero |= (~InMask); 2326 KnownOne &= (~KnownZero); 2327 break; 2328 } 2329 case ISD::FGETSIGN: 2330 // All bits are zero except the low bit. 2331 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2332 break; 2333 2334 case ISD::SUB: { 2335 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) { 2336 // We know that the top bits of C-X are clear if X contains less bits 2337 // than C (i.e. no wrap-around can happen). For example, 20-X is 2338 // positive if we can prove that X is >= 0 and < 16. 2339 if (CLHS->getAPIntValue().isNonNegative()) { 2340 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros(); 2341 // NLZ can't be BitWidth with no sign bit 2342 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1); 2343 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2344 2345 // If all of the MaskV bits are known to be zero, then we know the 2346 // output top bits are zero, because we now know that the output is 2347 // from [0-C]. 2348 if ((KnownZero2 & MaskV) == MaskV) { 2349 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros(); 2350 // Top bits known zero. 2351 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2); 2352 } 2353 } 2354 } 2355 LLVM_FALLTHROUGH; 2356 } 2357 case ISD::ADD: 2358 case ISD::ADDE: { 2359 // Output known-0 bits are known if clear or set in both the low clear bits 2360 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the 2361 // low 3 bits clear. 2362 // Output known-0 bits are also known if the top bits of each input are 2363 // known to be clear. For example, if one input has the top 10 bits clear 2364 // and the other has the top 8 bits clear, we know the top 7 bits of the 2365 // output must be clear. 2366 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2367 unsigned KnownZeroHigh = KnownZero2.countLeadingOnes(); 2368 unsigned KnownZeroLow = KnownZero2.countTrailingOnes(); 2369 2370 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2371 KnownZeroHigh = std::min(KnownZeroHigh, 2372 KnownZero2.countLeadingOnes()); 2373 KnownZeroLow = std::min(KnownZeroLow, 2374 KnownZero2.countTrailingOnes()); 2375 2376 if (Op.getOpcode() == ISD::ADD) { 2377 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroLow); 2378 if (KnownZeroHigh > 1) 2379 KnownZero |= APInt::getHighBitsSet(BitWidth, KnownZeroHigh - 1); 2380 break; 2381 } 2382 2383 // With ADDE, a carry bit may be added in, so we can only use this 2384 // information if we know (at least) that the low two bits are clear. We 2385 // then return to the caller that the low bit is unknown but that other bits 2386 // are known zero. 2387 if (KnownZeroLow >= 2) // ADDE 2388 KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroLow); 2389 break; 2390 } 2391 case ISD::SREM: 2392 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2393 const APInt &RA = Rem->getAPIntValue().abs(); 2394 if (RA.isPowerOf2()) { 2395 APInt LowBits = RA - 1; 2396 computeKnownBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1); 2397 2398 // The low bits of the first operand are unchanged by the srem. 2399 KnownZero = KnownZero2 & LowBits; 2400 KnownOne = KnownOne2 & LowBits; 2401 2402 // If the first operand is non-negative or has all low bits zero, then 2403 // the upper bits are all zero. 2404 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits)) 2405 KnownZero |= ~LowBits; 2406 2407 // If the first operand is negative and not all low bits are zero, then 2408 // the upper bits are all one. 2409 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0)) 2410 KnownOne |= ~LowBits; 2411 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 2412 } 2413 } 2414 break; 2415 case ISD::UREM: { 2416 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2417 const APInt &RA = Rem->getAPIntValue(); 2418 if (RA.isPowerOf2()) { 2419 APInt LowBits = (RA - 1); 2420 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth + 1); 2421 2422 // The upper bits are all zero, the lower ones are unchanged. 2423 KnownZero = KnownZero2 | ~LowBits; 2424 KnownOne = KnownOne2 & LowBits; 2425 break; 2426 } 2427 } 2428 2429 // Since the result is less than or equal to either operand, any leading 2430 // zero bits in either operand must also exist in the result. 2431 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2432 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2433 2434 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(), 2435 KnownZero2.countLeadingOnes()); 2436 KnownOne.clearAllBits(); 2437 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders); 2438 break; 2439 } 2440 case ISD::EXTRACT_ELEMENT: { 2441 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2442 const unsigned Index = 2443 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2444 const unsigned BitWidth = Op.getValueType().getSizeInBits(); 2445 2446 // Remove low part of known bits mask 2447 KnownZero = KnownZero.getHiBits(KnownZero.getBitWidth() - Index * BitWidth); 2448 KnownOne = KnownOne.getHiBits(KnownOne.getBitWidth() - Index * BitWidth); 2449 2450 // Remove high part of known bit mask 2451 KnownZero = KnownZero.trunc(BitWidth); 2452 KnownOne = KnownOne.trunc(BitWidth); 2453 break; 2454 } 2455 case ISD::BSWAP: { 2456 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2457 KnownZero = KnownZero2.byteSwap(); 2458 KnownOne = KnownOne2.byteSwap(); 2459 break; 2460 } 2461 case ISD::SMIN: 2462 case ISD::SMAX: 2463 case ISD::UMIN: 2464 case ISD::UMAX: { 2465 APInt Op0Zero, Op0One; 2466 APInt Op1Zero, Op1One; 2467 computeKnownBits(Op.getOperand(0), Op0Zero, Op0One, Depth); 2468 computeKnownBits(Op.getOperand(1), Op1Zero, Op1One, Depth); 2469 2470 KnownZero = Op0Zero & Op1Zero; 2471 KnownOne = Op0One & Op1One; 2472 break; 2473 } 2474 case ISD::FrameIndex: 2475 case ISD::TargetFrameIndex: 2476 if (unsigned Align = InferPtrAlignment(Op)) { 2477 // The low bits are known zero if the pointer is aligned. 2478 KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align)); 2479 break; 2480 } 2481 break; 2482 2483 default: 2484 if (Op.getOpcode() < ISD::BUILTIN_OP_END) 2485 break; 2486 LLVM_FALLTHROUGH; 2487 case ISD::INTRINSIC_WO_CHAIN: 2488 case ISD::INTRINSIC_W_CHAIN: 2489 case ISD::INTRINSIC_VOID: 2490 // Allow the target to implement this method for its nodes. 2491 TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth); 2492 break; 2493 } 2494 2495 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 2496 } 2497 2498 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 2499 // A left-shift of a constant one will have exactly one bit set because 2500 // shifting the bit off the end is undefined. 2501 if (Val.getOpcode() == ISD::SHL) { 2502 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0)); 2503 if (C && C->getAPIntValue() == 1) 2504 return true; 2505 } 2506 2507 // Similarly, a logical right-shift of a constant sign-bit will have exactly 2508 // one bit set. 2509 if (Val.getOpcode() == ISD::SRL) { 2510 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0)); 2511 if (C && C->getAPIntValue().isSignBit()) 2512 return true; 2513 } 2514 2515 // More could be done here, though the above checks are enough 2516 // to handle some common cases. 2517 2518 // Fall back to computeKnownBits to catch other known cases. 2519 EVT OpVT = Val.getValueType(); 2520 unsigned BitWidth = OpVT.getScalarType().getSizeInBits(); 2521 APInt KnownZero, KnownOne; 2522 computeKnownBits(Val, KnownZero, KnownOne); 2523 return (KnownZero.countPopulation() == BitWidth - 1) && 2524 (KnownOne.countPopulation() == 1); 2525 } 2526 2527 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 2528 EVT VT = Op.getValueType(); 2529 assert(VT.isInteger() && "Invalid VT!"); 2530 unsigned VTBits = VT.getScalarType().getSizeInBits(); 2531 unsigned Tmp, Tmp2; 2532 unsigned FirstAnswer = 1; 2533 2534 if (Depth == 6) 2535 return 1; // Limit search depth. 2536 2537 switch (Op.getOpcode()) { 2538 default: break; 2539 case ISD::AssertSext: 2540 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2541 return VTBits-Tmp+1; 2542 case ISD::AssertZext: 2543 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2544 return VTBits-Tmp; 2545 2546 case ISD::Constant: { 2547 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue(); 2548 return Val.getNumSignBits(); 2549 } 2550 2551 case ISD::SIGN_EXTEND: 2552 Tmp = 2553 VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 2554 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp; 2555 2556 case ISD::SIGN_EXTEND_INREG: 2557 // Max of the input and what this extends. 2558 Tmp = 2559 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits(); 2560 Tmp = VTBits-Tmp+1; 2561 2562 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2563 return std::max(Tmp, Tmp2); 2564 2565 case ISD::SRA: 2566 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2567 // SRA X, C -> adds C sign bits. 2568 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2569 Tmp += C->getZExtValue(); 2570 if (Tmp > VTBits) Tmp = VTBits; 2571 } 2572 return Tmp; 2573 case ISD::SHL: 2574 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2575 // shl destroys sign bits. 2576 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2577 if (C->getZExtValue() >= VTBits || // Bad shift. 2578 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out. 2579 return Tmp - C->getZExtValue(); 2580 } 2581 break; 2582 case ISD::AND: 2583 case ISD::OR: 2584 case ISD::XOR: // NOT is handled here. 2585 // Logical binary ops preserve the number of sign bits at the worst. 2586 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2587 if (Tmp != 1) { 2588 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2589 FirstAnswer = std::min(Tmp, Tmp2); 2590 // We computed what we know about the sign bits as our first 2591 // answer. Now proceed to the generic code that uses 2592 // computeKnownBits, and pick whichever answer is better. 2593 } 2594 break; 2595 2596 case ISD::SELECT: 2597 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2598 if (Tmp == 1) return 1; // Early out. 2599 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1); 2600 return std::min(Tmp, Tmp2); 2601 case ISD::SELECT_CC: 2602 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1); 2603 if (Tmp == 1) return 1; // Early out. 2604 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1); 2605 return std::min(Tmp, Tmp2); 2606 case ISD::SMIN: 2607 case ISD::SMAX: 2608 case ISD::UMIN: 2609 case ISD::UMAX: 2610 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 2611 if (Tmp == 1) 2612 return 1; // Early out. 2613 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 2614 return std::min(Tmp, Tmp2); 2615 case ISD::SADDO: 2616 case ISD::UADDO: 2617 case ISD::SSUBO: 2618 case ISD::USUBO: 2619 case ISD::SMULO: 2620 case ISD::UMULO: 2621 if (Op.getResNo() != 1) 2622 break; 2623 // The boolean result conforms to getBooleanContents. Fall through. 2624 // If setcc returns 0/-1, all bits are sign bits. 2625 // We know that we have an integer-based boolean since these operations 2626 // are only available for integer. 2627 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 2628 TargetLowering::ZeroOrNegativeOneBooleanContent) 2629 return VTBits; 2630 break; 2631 case ISD::SETCC: 2632 // If setcc returns 0/-1, all bits are sign bits. 2633 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 2634 TargetLowering::ZeroOrNegativeOneBooleanContent) 2635 return VTBits; 2636 break; 2637 case ISD::ROTL: 2638 case ISD::ROTR: 2639 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2640 unsigned RotAmt = C->getZExtValue() & (VTBits-1); 2641 2642 // Handle rotate right by N like a rotate left by 32-N. 2643 if (Op.getOpcode() == ISD::ROTR) 2644 RotAmt = (VTBits-RotAmt) & (VTBits-1); 2645 2646 // If we aren't rotating out all of the known-in sign bits, return the 2647 // number that are left. This handles rotl(sext(x), 1) for example. 2648 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2649 if (Tmp > RotAmt+1) return Tmp-RotAmt; 2650 } 2651 break; 2652 case ISD::ADD: 2653 // Add can have at most one carry bit. Thus we know that the output 2654 // is, at worst, one more bit than the inputs. 2655 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2656 if (Tmp == 1) return 1; // Early out. 2657 2658 // Special case decrementing a value (ADD X, -1): 2659 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2660 if (CRHS->isAllOnesValue()) { 2661 APInt KnownZero, KnownOne; 2662 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2663 2664 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2665 // sign bits set. 2666 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue()) 2667 return VTBits; 2668 2669 // If we are subtracting one from a positive number, there is no carry 2670 // out of the result. 2671 if (KnownZero.isNegative()) 2672 return Tmp; 2673 } 2674 2675 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2676 if (Tmp2 == 1) return 1; 2677 return std::min(Tmp, Tmp2)-1; 2678 2679 case ISD::SUB: 2680 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2681 if (Tmp2 == 1) return 1; 2682 2683 // Handle NEG. 2684 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) 2685 if (CLHS->isNullValue()) { 2686 APInt KnownZero, KnownOne; 2687 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2688 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2689 // sign bits set. 2690 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue()) 2691 return VTBits; 2692 2693 // If the input is known to be positive (the sign bit is known clear), 2694 // the output of the NEG has the same number of sign bits as the input. 2695 if (KnownZero.isNegative()) 2696 return Tmp2; 2697 2698 // Otherwise, we treat this like a SUB. 2699 } 2700 2701 // Sub can have at most one carry bit. Thus we know that the output 2702 // is, at worst, one more bit than the inputs. 2703 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2704 if (Tmp == 1) return 1; // Early out. 2705 return std::min(Tmp, Tmp2)-1; 2706 case ISD::TRUNCATE: 2707 // FIXME: it's tricky to do anything useful for this, but it is an important 2708 // case for targets like X86. 2709 break; 2710 case ISD::EXTRACT_ELEMENT: { 2711 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2712 const int BitWidth = Op.getValueType().getSizeInBits(); 2713 const int Items = 2714 Op.getOperand(0).getValueType().getSizeInBits() / BitWidth; 2715 2716 // Get reverse index (starting from 1), Op1 value indexes elements from 2717 // little end. Sign starts at big end. 2718 const int rIndex = Items - 1 - 2719 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2720 2721 // If the sign portion ends in our element the subtraction gives correct 2722 // result. Otherwise it gives either negative or > bitwidth result 2723 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 2724 } 2725 } 2726 2727 // If we are looking at the loaded value of the SDNode. 2728 if (Op.getResNo() == 0) { 2729 // Handle LOADX separately here. EXTLOAD case will fallthrough. 2730 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 2731 unsigned ExtType = LD->getExtensionType(); 2732 switch (ExtType) { 2733 default: break; 2734 case ISD::SEXTLOAD: // '17' bits known 2735 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits(); 2736 return VTBits-Tmp+1; 2737 case ISD::ZEXTLOAD: // '16' bits known 2738 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits(); 2739 return VTBits-Tmp; 2740 } 2741 } 2742 } 2743 2744 // Allow the target to implement this method for its nodes. 2745 if (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2746 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2747 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2748 Op.getOpcode() == ISD::INTRINSIC_VOID) { 2749 unsigned NumBits = TLI->ComputeNumSignBitsForTargetNode(Op, *this, Depth); 2750 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits); 2751 } 2752 2753 // Finally, if we can prove that the top bits of the result are 0's or 1's, 2754 // use this information. 2755 APInt KnownZero, KnownOne; 2756 computeKnownBits(Op, KnownZero, KnownOne, Depth); 2757 2758 APInt Mask; 2759 if (KnownZero.isNegative()) { // sign bit is 0 2760 Mask = KnownZero; 2761 } else if (KnownOne.isNegative()) { // sign bit is 1; 2762 Mask = KnownOne; 2763 } else { 2764 // Nothing known. 2765 return FirstAnswer; 2766 } 2767 2768 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine 2769 // the number of identical bits in the top of the input value. 2770 Mask = ~Mask; 2771 Mask <<= Mask.getBitWidth()-VTBits; 2772 // Return # leading zeros. We use 'min' here in case Val was zero before 2773 // shifting. We don't want to return '64' as for an i32 "0". 2774 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros())); 2775 } 2776 2777 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 2778 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 2779 !isa<ConstantSDNode>(Op.getOperand(1))) 2780 return false; 2781 2782 if (Op.getOpcode() == ISD::OR && 2783 !MaskedValueIsZero(Op.getOperand(0), 2784 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue())) 2785 return false; 2786 2787 return true; 2788 } 2789 2790 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const { 2791 // If we're told that NaNs won't happen, assume they won't. 2792 if (getTarget().Options.NoNaNsFPMath) 2793 return true; 2794 2795 // If the value is a constant, we can obviously see if it is a NaN or not. 2796 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 2797 return !C->getValueAPF().isNaN(); 2798 2799 // TODO: Recognize more cases here. 2800 2801 return false; 2802 } 2803 2804 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 2805 // If the value is a constant, we can obviously see if it is a zero or not. 2806 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 2807 return !C->isZero(); 2808 2809 // TODO: Recognize more cases here. 2810 switch (Op.getOpcode()) { 2811 default: break; 2812 case ISD::OR: 2813 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2814 return !C->isNullValue(); 2815 break; 2816 } 2817 2818 return false; 2819 } 2820 2821 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 2822 // Check the obvious case. 2823 if (A == B) return true; 2824 2825 // For for negative and positive zero. 2826 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 2827 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 2828 if (CA->isZero() && CB->isZero()) return true; 2829 2830 // Otherwise they may not be equal. 2831 return false; 2832 } 2833 2834 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 2835 assert(A.getValueType() == B.getValueType() && 2836 "Values must have the same type"); 2837 APInt AZero, AOne; 2838 APInt BZero, BOne; 2839 computeKnownBits(A, AZero, AOne); 2840 computeKnownBits(B, BZero, BOne); 2841 return (AZero | BZero).isAllOnesValue(); 2842 } 2843 2844 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 2845 ArrayRef<SDValue> Ops, 2846 llvm::SelectionDAG &DAG) { 2847 if (Ops.size() == 1) 2848 return Ops[0]; 2849 2850 // Concat of UNDEFs is UNDEF. 2851 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 2852 return DAG.getUNDEF(VT); 2853 2854 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 2855 // simplified to one big BUILD_VECTOR. 2856 // FIXME: Add support for SCALAR_TO_VECTOR as well. 2857 EVT SVT = VT.getScalarType(); 2858 SmallVector<SDValue, 16> Elts; 2859 for (SDValue Op : Ops) { 2860 EVT OpVT = Op.getValueType(); 2861 if (Op.isUndef()) 2862 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 2863 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 2864 Elts.append(Op->op_begin(), Op->op_end()); 2865 else 2866 return SDValue(); 2867 } 2868 2869 // BUILD_VECTOR requires all inputs to be of the same type, find the 2870 // maximum type and extend them all. 2871 for (SDValue Op : Elts) 2872 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 2873 2874 if (SVT.bitsGT(VT.getScalarType())) 2875 for (SDValue &Op : Elts) 2876 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 2877 ? DAG.getZExtOrTrunc(Op, DL, SVT) 2878 : DAG.getSExtOrTrunc(Op, DL, SVT); 2879 2880 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts); 2881 } 2882 2883 /// Gets or creates the specified node. 2884 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 2885 FoldingSetNodeID ID; 2886 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 2887 void *IP = nullptr; 2888 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 2889 return SDValue(E, 0); 2890 2891 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 2892 getVTList(VT)); 2893 CSEMap.InsertNode(N, IP); 2894 2895 InsertNode(N); 2896 return SDValue(N, 0); 2897 } 2898 2899 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 2900 SDValue Operand) { 2901 // Constant fold unary operations with an integer constant operand. Even 2902 // opaque constant will be folded, because the folding of unary operations 2903 // doesn't create new constants with different values. Nevertheless, the 2904 // opaque flag is preserved during folding to prevent future folding with 2905 // other constants. 2906 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 2907 const APInt &Val = C->getAPIntValue(); 2908 switch (Opcode) { 2909 default: break; 2910 case ISD::SIGN_EXTEND: 2911 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 2912 C->isTargetOpcode(), C->isOpaque()); 2913 case ISD::ANY_EXTEND: 2914 case ISD::ZERO_EXTEND: 2915 case ISD::TRUNCATE: 2916 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 2917 C->isTargetOpcode(), C->isOpaque()); 2918 case ISD::UINT_TO_FP: 2919 case ISD::SINT_TO_FP: { 2920 APFloat apf(EVTToAPFloatSemantics(VT), 2921 APInt::getNullValue(VT.getSizeInBits())); 2922 (void)apf.convertFromAPInt(Val, 2923 Opcode==ISD::SINT_TO_FP, 2924 APFloat::rmNearestTiesToEven); 2925 return getConstantFP(apf, DL, VT); 2926 } 2927 case ISD::BITCAST: 2928 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 2929 return getConstantFP(APFloat(APFloat::IEEEhalf, Val), DL, VT); 2930 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 2931 return getConstantFP(APFloat(APFloat::IEEEsingle, Val), DL, VT); 2932 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 2933 return getConstantFP(APFloat(APFloat::IEEEdouble, Val), DL, VT); 2934 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 2935 return getConstantFP(APFloat(APFloat::IEEEquad, Val), DL, VT); 2936 break; 2937 case ISD::BSWAP: 2938 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 2939 C->isOpaque()); 2940 case ISD::CTPOP: 2941 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 2942 C->isOpaque()); 2943 case ISD::CTLZ: 2944 case ISD::CTLZ_ZERO_UNDEF: 2945 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 2946 C->isOpaque()); 2947 case ISD::CTTZ: 2948 case ISD::CTTZ_ZERO_UNDEF: 2949 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 2950 C->isOpaque()); 2951 } 2952 } 2953 2954 // Constant fold unary operations with a floating point constant operand. 2955 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 2956 APFloat V = C->getValueAPF(); // make copy 2957 switch (Opcode) { 2958 case ISD::FNEG: 2959 V.changeSign(); 2960 return getConstantFP(V, DL, VT); 2961 case ISD::FABS: 2962 V.clearSign(); 2963 return getConstantFP(V, DL, VT); 2964 case ISD::FCEIL: { 2965 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 2966 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2967 return getConstantFP(V, DL, VT); 2968 break; 2969 } 2970 case ISD::FTRUNC: { 2971 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 2972 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2973 return getConstantFP(V, DL, VT); 2974 break; 2975 } 2976 case ISD::FFLOOR: { 2977 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 2978 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2979 return getConstantFP(V, DL, VT); 2980 break; 2981 } 2982 case ISD::FP_EXTEND: { 2983 bool ignored; 2984 // This can return overflow, underflow, or inexact; we don't care. 2985 // FIXME need to be more flexible about rounding mode. 2986 (void)V.convert(EVTToAPFloatSemantics(VT), 2987 APFloat::rmNearestTiesToEven, &ignored); 2988 return getConstantFP(V, DL, VT); 2989 } 2990 case ISD::FP_TO_SINT: 2991 case ISD::FP_TO_UINT: { 2992 integerPart x[2]; 2993 bool ignored; 2994 static_assert(integerPartWidth >= 64, "APFloat parts too small!"); 2995 // FIXME need to be more flexible about rounding mode. 2996 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(), 2997 Opcode==ISD::FP_TO_SINT, 2998 APFloat::rmTowardZero, &ignored); 2999 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual 3000 break; 3001 APInt api(VT.getSizeInBits(), x); 3002 return getConstant(api, DL, VT); 3003 } 3004 case ISD::BITCAST: 3005 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 3006 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 3007 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 3008 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 3009 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 3010 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 3011 break; 3012 } 3013 } 3014 3015 // Constant fold unary operations with a vector integer or float operand. 3016 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) { 3017 if (BV->isConstant()) { 3018 switch (Opcode) { 3019 default: 3020 // FIXME: Entirely reasonable to perform folding of other unary 3021 // operations here as the need arises. 3022 break; 3023 case ISD::FNEG: 3024 case ISD::FABS: 3025 case ISD::FCEIL: 3026 case ISD::FTRUNC: 3027 case ISD::FFLOOR: 3028 case ISD::FP_EXTEND: 3029 case ISD::FP_TO_SINT: 3030 case ISD::FP_TO_UINT: 3031 case ISD::TRUNCATE: 3032 case ISD::UINT_TO_FP: 3033 case ISD::SINT_TO_FP: 3034 case ISD::BSWAP: 3035 case ISD::CTLZ: 3036 case ISD::CTLZ_ZERO_UNDEF: 3037 case ISD::CTTZ: 3038 case ISD::CTTZ_ZERO_UNDEF: 3039 case ISD::CTPOP: { 3040 SDValue Ops = { Operand }; 3041 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 3042 return Fold; 3043 } 3044 } 3045 } 3046 } 3047 3048 unsigned OpOpcode = Operand.getNode()->getOpcode(); 3049 switch (Opcode) { 3050 case ISD::TokenFactor: 3051 case ISD::MERGE_VALUES: 3052 case ISD::CONCAT_VECTORS: 3053 return Operand; // Factor, merge or concat of one node? No need. 3054 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 3055 case ISD::FP_EXTEND: 3056 assert(VT.isFloatingPoint() && 3057 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 3058 if (Operand.getValueType() == VT) return Operand; // noop conversion. 3059 assert((!VT.isVector() || 3060 VT.getVectorNumElements() == 3061 Operand.getValueType().getVectorNumElements()) && 3062 "Vector element count mismatch!"); 3063 assert(Operand.getValueType().bitsLT(VT) && 3064 "Invalid fpext node, dst < src!"); 3065 if (Operand.isUndef()) 3066 return getUNDEF(VT); 3067 break; 3068 case ISD::SIGN_EXTEND: 3069 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3070 "Invalid SIGN_EXTEND!"); 3071 if (Operand.getValueType() == VT) return Operand; // noop extension 3072 assert((!VT.isVector() || 3073 VT.getVectorNumElements() == 3074 Operand.getValueType().getVectorNumElements()) && 3075 "Vector element count mismatch!"); 3076 assert(Operand.getValueType().bitsLT(VT) && 3077 "Invalid sext node, dst < src!"); 3078 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 3079 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 3080 else if (OpOpcode == ISD::UNDEF) 3081 // sext(undef) = 0, because the top bits will all be the same. 3082 return getConstant(0, DL, VT); 3083 break; 3084 case ISD::ZERO_EXTEND: 3085 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3086 "Invalid ZERO_EXTEND!"); 3087 if (Operand.getValueType() == VT) return Operand; // noop extension 3088 assert((!VT.isVector() || 3089 VT.getVectorNumElements() == 3090 Operand.getValueType().getVectorNumElements()) && 3091 "Vector element count mismatch!"); 3092 assert(Operand.getValueType().bitsLT(VT) && 3093 "Invalid zext node, dst < src!"); 3094 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 3095 return getNode(ISD::ZERO_EXTEND, DL, VT, 3096 Operand.getNode()->getOperand(0)); 3097 else if (OpOpcode == ISD::UNDEF) 3098 // zext(undef) = 0, because the top bits will be zero. 3099 return getConstant(0, DL, VT); 3100 break; 3101 case ISD::ANY_EXTEND: 3102 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3103 "Invalid ANY_EXTEND!"); 3104 if (Operand.getValueType() == VT) return Operand; // noop extension 3105 assert((!VT.isVector() || 3106 VT.getVectorNumElements() == 3107 Operand.getValueType().getVectorNumElements()) && 3108 "Vector element count mismatch!"); 3109 assert(Operand.getValueType().bitsLT(VT) && 3110 "Invalid anyext node, dst < src!"); 3111 3112 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 3113 OpOpcode == ISD::ANY_EXTEND) 3114 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 3115 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 3116 else if (OpOpcode == ISD::UNDEF) 3117 return getUNDEF(VT); 3118 3119 // (ext (trunx x)) -> x 3120 if (OpOpcode == ISD::TRUNCATE) { 3121 SDValue OpOp = Operand.getNode()->getOperand(0); 3122 if (OpOp.getValueType() == VT) 3123 return OpOp; 3124 } 3125 break; 3126 case ISD::TRUNCATE: 3127 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3128 "Invalid TRUNCATE!"); 3129 if (Operand.getValueType() == VT) return Operand; // noop truncate 3130 assert((!VT.isVector() || 3131 VT.getVectorNumElements() == 3132 Operand.getValueType().getVectorNumElements()) && 3133 "Vector element count mismatch!"); 3134 assert(Operand.getValueType().bitsGT(VT) && 3135 "Invalid truncate node, src < dst!"); 3136 if (OpOpcode == ISD::TRUNCATE) 3137 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 3138 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 3139 OpOpcode == ISD::ANY_EXTEND) { 3140 // If the source is smaller than the dest, we still need an extend. 3141 if (Operand.getNode()->getOperand(0).getValueType().getScalarType() 3142 .bitsLT(VT.getScalarType())) 3143 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 3144 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT)) 3145 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 3146 return Operand.getNode()->getOperand(0); 3147 } 3148 if (OpOpcode == ISD::UNDEF) 3149 return getUNDEF(VT); 3150 break; 3151 case ISD::BSWAP: 3152 assert(VT.isInteger() && VT == Operand.getValueType() && 3153 "Invalid BSWAP!"); 3154 assert((VT.getScalarSizeInBits() % 16 == 0) && 3155 "BSWAP types must be a multiple of 16 bits!"); 3156 if (OpOpcode == ISD::UNDEF) 3157 return getUNDEF(VT); 3158 break; 3159 case ISD::BITREVERSE: 3160 assert(VT.isInteger() && VT == Operand.getValueType() && 3161 "Invalid BITREVERSE!"); 3162 if (OpOpcode == ISD::UNDEF) 3163 return getUNDEF(VT); 3164 break; 3165 case ISD::BITCAST: 3166 // Basic sanity checking. 3167 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits() 3168 && "Cannot BITCAST between types of different sizes!"); 3169 if (VT == Operand.getValueType()) return Operand; // noop conversion. 3170 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 3171 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 3172 if (OpOpcode == ISD::UNDEF) 3173 return getUNDEF(VT); 3174 break; 3175 case ISD::SCALAR_TO_VECTOR: 3176 assert(VT.isVector() && !Operand.getValueType().isVector() && 3177 (VT.getVectorElementType() == Operand.getValueType() || 3178 (VT.getVectorElementType().isInteger() && 3179 Operand.getValueType().isInteger() && 3180 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 3181 "Illegal SCALAR_TO_VECTOR node!"); 3182 if (OpOpcode == ISD::UNDEF) 3183 return getUNDEF(VT); 3184 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 3185 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 3186 isa<ConstantSDNode>(Operand.getOperand(1)) && 3187 Operand.getConstantOperandVal(1) == 0 && 3188 Operand.getOperand(0).getValueType() == VT) 3189 return Operand.getOperand(0); 3190 break; 3191 case ISD::FNEG: 3192 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 3193 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB) 3194 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags? 3195 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1), 3196 Operand.getNode()->getOperand(0), 3197 &cast<BinaryWithFlagsSDNode>(Operand.getNode())->Flags); 3198 if (OpOpcode == ISD::FNEG) // --X -> X 3199 return Operand.getNode()->getOperand(0); 3200 break; 3201 case ISD::FABS: 3202 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 3203 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0)); 3204 break; 3205 } 3206 3207 SDNode *N; 3208 SDVTList VTs = getVTList(VT); 3209 SDValue Ops[] = {Operand}; 3210 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 3211 FoldingSetNodeID ID; 3212 AddNodeIDNode(ID, Opcode, VTs, Ops); 3213 void *IP = nullptr; 3214 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 3215 return SDValue(E, 0); 3216 3217 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 3218 createOperands(N, Ops); 3219 CSEMap.InsertNode(N, IP); 3220 } else { 3221 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 3222 createOperands(N, Ops); 3223 } 3224 3225 InsertNode(N); 3226 return SDValue(N, 0); 3227 } 3228 3229 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1, 3230 const APInt &C2) { 3231 switch (Opcode) { 3232 case ISD::ADD: return std::make_pair(C1 + C2, true); 3233 case ISD::SUB: return std::make_pair(C1 - C2, true); 3234 case ISD::MUL: return std::make_pair(C1 * C2, true); 3235 case ISD::AND: return std::make_pair(C1 & C2, true); 3236 case ISD::OR: return std::make_pair(C1 | C2, true); 3237 case ISD::XOR: return std::make_pair(C1 ^ C2, true); 3238 case ISD::SHL: return std::make_pair(C1 << C2, true); 3239 case ISD::SRL: return std::make_pair(C1.lshr(C2), true); 3240 case ISD::SRA: return std::make_pair(C1.ashr(C2), true); 3241 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true); 3242 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true); 3243 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true); 3244 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true); 3245 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true); 3246 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true); 3247 case ISD::UDIV: 3248 if (!C2.getBoolValue()) 3249 break; 3250 return std::make_pair(C1.udiv(C2), true); 3251 case ISD::UREM: 3252 if (!C2.getBoolValue()) 3253 break; 3254 return std::make_pair(C1.urem(C2), true); 3255 case ISD::SDIV: 3256 if (!C2.getBoolValue()) 3257 break; 3258 return std::make_pair(C1.sdiv(C2), true); 3259 case ISD::SREM: 3260 if (!C2.getBoolValue()) 3261 break; 3262 return std::make_pair(C1.srem(C2), true); 3263 } 3264 return std::make_pair(APInt(1, 0), false); 3265 } 3266 3267 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 3268 EVT VT, const ConstantSDNode *Cst1, 3269 const ConstantSDNode *Cst2) { 3270 if (Cst1->isOpaque() || Cst2->isOpaque()) 3271 return SDValue(); 3272 3273 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(), 3274 Cst2->getAPIntValue()); 3275 if (!Folded.second) 3276 return SDValue(); 3277 return getConstant(Folded.first, DL, VT); 3278 } 3279 3280 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 3281 const GlobalAddressSDNode *GA, 3282 const SDNode *N2) { 3283 if (GA->getOpcode() != ISD::GlobalAddress) 3284 return SDValue(); 3285 if (!TLI->isOffsetFoldingLegal(GA)) 3286 return SDValue(); 3287 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2); 3288 if (!Cst2) 3289 return SDValue(); 3290 int64_t Offset = Cst2->getSExtValue(); 3291 switch (Opcode) { 3292 case ISD::ADD: break; 3293 case ISD::SUB: Offset = -uint64_t(Offset); break; 3294 default: return SDValue(); 3295 } 3296 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT, 3297 GA->getOffset() + uint64_t(Offset)); 3298 } 3299 3300 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 3301 EVT VT, SDNode *Cst1, 3302 SDNode *Cst2) { 3303 // If the opcode is a target-specific ISD node, there's nothing we can 3304 // do here and the operand rules may not line up with the below, so 3305 // bail early. 3306 if (Opcode >= ISD::BUILTIN_OP_END) 3307 return SDValue(); 3308 3309 // Handle the case of two scalars. 3310 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) { 3311 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) { 3312 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2); 3313 assert((!Folded || !VT.isVector()) && 3314 "Can't fold vectors ops with scalar operands"); 3315 return Folded; 3316 } 3317 } 3318 3319 // fold (add Sym, c) -> Sym+c 3320 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1)) 3321 return FoldSymbolOffset(Opcode, VT, GA, Cst2); 3322 if (isCommutativeBinOp(Opcode)) 3323 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2)) 3324 return FoldSymbolOffset(Opcode, VT, GA, Cst1); 3325 3326 // For vectors extract each constant element into Inputs so we can constant 3327 // fold them individually. 3328 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1); 3329 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2); 3330 if (!BV1 || !BV2) 3331 return SDValue(); 3332 3333 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!"); 3334 3335 EVT SVT = VT.getScalarType(); 3336 SmallVector<SDValue, 4> Outputs; 3337 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) { 3338 ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I)); 3339 ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I)); 3340 if (!V1 || !V2) // Not a constant, bail. 3341 return SDValue(); 3342 3343 if (V1->isOpaque() || V2->isOpaque()) 3344 return SDValue(); 3345 3346 // Avoid BUILD_VECTOR nodes that perform implicit truncation. 3347 // FIXME: This is valid and could be handled by truncating the APInts. 3348 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT) 3349 return SDValue(); 3350 3351 // Fold one vector element. 3352 std::pair<APInt, bool> Folded = FoldValue(Opcode, V1->getAPIntValue(), 3353 V2->getAPIntValue()); 3354 if (!Folded.second) 3355 return SDValue(); 3356 Outputs.push_back(getConstant(Folded.first, DL, SVT)); 3357 } 3358 3359 assert(VT.getVectorNumElements() == Outputs.size() && 3360 "Vector size mismatch!"); 3361 3362 // We may have a vector type but a scalar result. Create a splat. 3363 Outputs.resize(VT.getVectorNumElements(), Outputs.back()); 3364 3365 // Build a big vector out of the scalar elements we generated. 3366 return getBuildVector(VT, SDLoc(), Outputs); 3367 } 3368 3369 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 3370 const SDLoc &DL, EVT VT, 3371 ArrayRef<SDValue> Ops, 3372 const SDNodeFlags *Flags) { 3373 // If the opcode is a target-specific ISD node, there's nothing we can 3374 // do here and the operand rules may not line up with the below, so 3375 // bail early. 3376 if (Opcode >= ISD::BUILTIN_OP_END) 3377 return SDValue(); 3378 3379 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 3380 if (!VT.isVector()) 3381 return SDValue(); 3382 3383 unsigned NumElts = VT.getVectorNumElements(); 3384 3385 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) { 3386 return !Op.getValueType().isVector() || 3387 Op.getValueType().getVectorNumElements() == NumElts; 3388 }; 3389 3390 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) { 3391 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 3392 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) || 3393 (BV && BV->isConstant()); 3394 }; 3395 3396 // All operands must be vector types with the same number of elements as 3397 // the result type and must be either UNDEF or a build vector of constant 3398 // or UNDEF scalars. 3399 if (!all_of(Ops, IsConstantBuildVectorOrUndef) || 3400 !all_of(Ops, IsScalarOrSameVectorSize)) 3401 return SDValue(); 3402 3403 // If we are comparing vectors, then the result needs to be a i1 boolean 3404 // that is then sign-extended back to the legal result type. 3405 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 3406 3407 // Find legal integer scalar type for constant promotion and 3408 // ensure that its scalar size is at least as large as source. 3409 EVT LegalSVT = VT.getScalarType(); 3410 if (LegalSVT.isInteger()) { 3411 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 3412 if (LegalSVT.bitsLT(VT.getScalarType())) 3413 return SDValue(); 3414 } 3415 3416 // Constant fold each scalar lane separately. 3417 SmallVector<SDValue, 4> ScalarResults; 3418 for (unsigned i = 0; i != NumElts; i++) { 3419 SmallVector<SDValue, 4> ScalarOps; 3420 for (SDValue Op : Ops) { 3421 EVT InSVT = Op.getValueType().getScalarType(); 3422 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op); 3423 if (!InBV) { 3424 // We've checked that this is UNDEF or a constant of some kind. 3425 if (Op.isUndef()) 3426 ScalarOps.push_back(getUNDEF(InSVT)); 3427 else 3428 ScalarOps.push_back(Op); 3429 continue; 3430 } 3431 3432 SDValue ScalarOp = InBV->getOperand(i); 3433 EVT ScalarVT = ScalarOp.getValueType(); 3434 3435 // Build vector (integer) scalar operands may need implicit 3436 // truncation - do this before constant folding. 3437 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 3438 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 3439 3440 ScalarOps.push_back(ScalarOp); 3441 } 3442 3443 // Constant fold the scalar operands. 3444 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 3445 3446 // Legalize the (integer) scalar constant if necessary. 3447 if (LegalSVT != SVT) 3448 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 3449 3450 // Scalar folding only succeeded if the result is a constant or UNDEF. 3451 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 3452 ScalarResult.getOpcode() != ISD::ConstantFP) 3453 return SDValue(); 3454 ScalarResults.push_back(ScalarResult); 3455 } 3456 3457 return getBuildVector(VT, DL, ScalarResults); 3458 } 3459 3460 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 3461 SDValue N1, SDValue N2, 3462 const SDNodeFlags *Flags) { 3463 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3464 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 3465 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3466 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 3467 3468 // Canonicalize constant to RHS if commutative. 3469 if (isCommutativeBinOp(Opcode)) { 3470 if (N1C && !N2C) { 3471 std::swap(N1C, N2C); 3472 std::swap(N1, N2); 3473 } else if (N1CFP && !N2CFP) { 3474 std::swap(N1CFP, N2CFP); 3475 std::swap(N1, N2); 3476 } 3477 } 3478 3479 switch (Opcode) { 3480 default: break; 3481 case ISD::TokenFactor: 3482 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 3483 N2.getValueType() == MVT::Other && "Invalid token factor!"); 3484 // Fold trivial token factors. 3485 if (N1.getOpcode() == ISD::EntryToken) return N2; 3486 if (N2.getOpcode() == ISD::EntryToken) return N1; 3487 if (N1 == N2) return N1; 3488 break; 3489 case ISD::CONCAT_VECTORS: { 3490 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 3491 SDValue Ops[] = {N1, N2}; 3492 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 3493 return V; 3494 break; 3495 } 3496 case ISD::AND: 3497 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3498 assert(N1.getValueType() == N2.getValueType() && 3499 N1.getValueType() == VT && "Binary operator types must match!"); 3500 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 3501 // worth handling here. 3502 if (N2C && N2C->isNullValue()) 3503 return N2; 3504 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 3505 return N1; 3506 break; 3507 case ISD::OR: 3508 case ISD::XOR: 3509 case ISD::ADD: 3510 case ISD::SUB: 3511 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3512 assert(N1.getValueType() == N2.getValueType() && 3513 N1.getValueType() == VT && "Binary operator types must match!"); 3514 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 3515 // it's worth handling here. 3516 if (N2C && N2C->isNullValue()) 3517 return N1; 3518 break; 3519 case ISD::UDIV: 3520 case ISD::UREM: 3521 case ISD::MULHU: 3522 case ISD::MULHS: 3523 case ISD::MUL: 3524 case ISD::SDIV: 3525 case ISD::SREM: 3526 case ISD::SMIN: 3527 case ISD::SMAX: 3528 case ISD::UMIN: 3529 case ISD::UMAX: 3530 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3531 assert(N1.getValueType() == N2.getValueType() && 3532 N1.getValueType() == VT && "Binary operator types must match!"); 3533 break; 3534 case ISD::FADD: 3535 case ISD::FSUB: 3536 case ISD::FMUL: 3537 case ISD::FDIV: 3538 case ISD::FREM: 3539 if (getTarget().Options.UnsafeFPMath) { 3540 if (Opcode == ISD::FADD) { 3541 // x+0 --> x 3542 if (N2CFP && N2CFP->getValueAPF().isZero()) 3543 return N1; 3544 } else if (Opcode == ISD::FSUB) { 3545 // x-0 --> x 3546 if (N2CFP && N2CFP->getValueAPF().isZero()) 3547 return N1; 3548 } else if (Opcode == ISD::FMUL) { 3549 // x*0 --> 0 3550 if (N2CFP && N2CFP->isZero()) 3551 return N2; 3552 // x*1 --> x 3553 if (N2CFP && N2CFP->isExactlyValue(1.0)) 3554 return N1; 3555 } 3556 } 3557 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 3558 assert(N1.getValueType() == N2.getValueType() && 3559 N1.getValueType() == VT && "Binary operator types must match!"); 3560 break; 3561 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 3562 assert(N1.getValueType() == VT && 3563 N1.getValueType().isFloatingPoint() && 3564 N2.getValueType().isFloatingPoint() && 3565 "Invalid FCOPYSIGN!"); 3566 break; 3567 case ISD::SHL: 3568 case ISD::SRA: 3569 case ISD::SRL: 3570 case ISD::ROTL: 3571 case ISD::ROTR: 3572 assert(VT == N1.getValueType() && 3573 "Shift operators return type must be the same as their first arg"); 3574 assert(VT.isInteger() && N2.getValueType().isInteger() && 3575 "Shifts only work on integers"); 3576 assert((!VT.isVector() || VT == N2.getValueType()) && 3577 "Vector shift amounts must be in the same as their first arg"); 3578 // Verify that the shift amount VT is bit enough to hold valid shift 3579 // amounts. This catches things like trying to shift an i1024 value by an 3580 // i8, which is easy to fall into in generic code that uses 3581 // TLI.getShiftAmount(). 3582 assert(N2.getValueType().getSizeInBits() >= 3583 Log2_32_Ceil(N1.getValueType().getSizeInBits()) && 3584 "Invalid use of small shift amount with oversized value!"); 3585 3586 // Always fold shifts of i1 values so the code generator doesn't need to 3587 // handle them. Since we know the size of the shift has to be less than the 3588 // size of the value, the shift/rotate count is guaranteed to be zero. 3589 if (VT == MVT::i1) 3590 return N1; 3591 if (N2C && N2C->isNullValue()) 3592 return N1; 3593 break; 3594 case ISD::FP_ROUND_INREG: { 3595 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3596 assert(VT == N1.getValueType() && "Not an inreg round!"); 3597 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() && 3598 "Cannot FP_ROUND_INREG integer types"); 3599 assert(EVT.isVector() == VT.isVector() && 3600 "FP_ROUND_INREG type should be vector iff the operand " 3601 "type is vector!"); 3602 assert((!EVT.isVector() || 3603 EVT.getVectorNumElements() == VT.getVectorNumElements()) && 3604 "Vector element counts must match in FP_ROUND_INREG"); 3605 assert(EVT.bitsLE(VT) && "Not rounding down!"); 3606 (void)EVT; 3607 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding. 3608 break; 3609 } 3610 case ISD::FP_ROUND: 3611 assert(VT.isFloatingPoint() && 3612 N1.getValueType().isFloatingPoint() && 3613 VT.bitsLE(N1.getValueType()) && 3614 N2C && "Invalid FP_ROUND!"); 3615 if (N1.getValueType() == VT) return N1; // noop conversion. 3616 break; 3617 case ISD::AssertSext: 3618 case ISD::AssertZext: { 3619 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3620 assert(VT == N1.getValueType() && "Not an inreg extend!"); 3621 assert(VT.isInteger() && EVT.isInteger() && 3622 "Cannot *_EXTEND_INREG FP types"); 3623 assert(!EVT.isVector() && 3624 "AssertSExt/AssertZExt type should be the vector element type " 3625 "rather than the vector type!"); 3626 assert(EVT.bitsLE(VT) && "Not extending!"); 3627 if (VT == EVT) return N1; // noop assertion. 3628 break; 3629 } 3630 case ISD::SIGN_EXTEND_INREG: { 3631 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3632 assert(VT == N1.getValueType() && "Not an inreg extend!"); 3633 assert(VT.isInteger() && EVT.isInteger() && 3634 "Cannot *_EXTEND_INREG FP types"); 3635 assert(EVT.isVector() == VT.isVector() && 3636 "SIGN_EXTEND_INREG type should be vector iff the operand " 3637 "type is vector!"); 3638 assert((!EVT.isVector() || 3639 EVT.getVectorNumElements() == VT.getVectorNumElements()) && 3640 "Vector element counts must match in SIGN_EXTEND_INREG"); 3641 assert(EVT.bitsLE(VT) && "Not extending!"); 3642 if (EVT == VT) return N1; // Not actually extending 3643 3644 auto SignExtendInReg = [&](APInt Val) { 3645 unsigned FromBits = EVT.getScalarType().getSizeInBits(); 3646 Val <<= Val.getBitWidth() - FromBits; 3647 Val = Val.ashr(Val.getBitWidth() - FromBits); 3648 return getConstant(Val, DL, VT.getScalarType()); 3649 }; 3650 3651 if (N1C) { 3652 const APInt &Val = N1C->getAPIntValue(); 3653 return SignExtendInReg(Val); 3654 } 3655 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 3656 SmallVector<SDValue, 8> Ops; 3657 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 3658 SDValue Op = N1.getOperand(i); 3659 if (Op.isUndef()) { 3660 Ops.push_back(getUNDEF(VT.getScalarType())); 3661 continue; 3662 } 3663 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 3664 APInt Val = C->getAPIntValue(); 3665 Val = Val.zextOrTrunc(VT.getScalarSizeInBits()); 3666 Ops.push_back(SignExtendInReg(Val)); 3667 continue; 3668 } 3669 break; 3670 } 3671 if (Ops.size() == VT.getVectorNumElements()) 3672 return getBuildVector(VT, DL, Ops); 3673 } 3674 break; 3675 } 3676 case ISD::EXTRACT_VECTOR_ELT: 3677 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF. 3678 if (N1.isUndef()) 3679 return getUNDEF(VT); 3680 3681 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF 3682 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 3683 return getUNDEF(VT); 3684 3685 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 3686 // expanding copies of large vectors from registers. 3687 if (N2C && 3688 N1.getOpcode() == ISD::CONCAT_VECTORS && 3689 N1.getNumOperands() > 0) { 3690 unsigned Factor = 3691 N1.getOperand(0).getValueType().getVectorNumElements(); 3692 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 3693 N1.getOperand(N2C->getZExtValue() / Factor), 3694 getConstant(N2C->getZExtValue() % Factor, DL, 3695 N2.getValueType())); 3696 } 3697 3698 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is 3699 // expanding large vector constants. 3700 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) { 3701 SDValue Elt = N1.getOperand(N2C->getZExtValue()); 3702 3703 if (VT != Elt.getValueType()) 3704 // If the vector element type is not legal, the BUILD_VECTOR operands 3705 // are promoted and implicitly truncated, and the result implicitly 3706 // extended. Make that explicit here. 3707 Elt = getAnyExtOrTrunc(Elt, DL, VT); 3708 3709 return Elt; 3710 } 3711 3712 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 3713 // operations are lowered to scalars. 3714 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 3715 // If the indices are the same, return the inserted element else 3716 // if the indices are known different, extract the element from 3717 // the original vector. 3718 SDValue N1Op2 = N1.getOperand(2); 3719 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 3720 3721 if (N1Op2C && N2C) { 3722 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 3723 if (VT == N1.getOperand(1).getValueType()) 3724 return N1.getOperand(1); 3725 else 3726 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 3727 } 3728 3729 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 3730 } 3731 } 3732 break; 3733 case ISD::EXTRACT_ELEMENT: 3734 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 3735 assert(!N1.getValueType().isVector() && !VT.isVector() && 3736 (N1.getValueType().isInteger() == VT.isInteger()) && 3737 N1.getValueType() != VT && 3738 "Wrong types for EXTRACT_ELEMENT!"); 3739 3740 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 3741 // 64-bit integers into 32-bit parts. Instead of building the extract of 3742 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 3743 if (N1.getOpcode() == ISD::BUILD_PAIR) 3744 return N1.getOperand(N2C->getZExtValue()); 3745 3746 // EXTRACT_ELEMENT of a constant int is also very common. 3747 if (N1C) { 3748 unsigned ElementSize = VT.getSizeInBits(); 3749 unsigned Shift = ElementSize * N2C->getZExtValue(); 3750 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift); 3751 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT); 3752 } 3753 break; 3754 case ISD::EXTRACT_SUBVECTOR: 3755 if (VT.isSimple() && N1.getValueType().isSimple()) { 3756 assert(VT.isVector() && N1.getValueType().isVector() && 3757 "Extract subvector VTs must be a vectors!"); 3758 assert(VT.getVectorElementType() == 3759 N1.getValueType().getVectorElementType() && 3760 "Extract subvector VTs must have the same element type!"); 3761 assert(VT.getSimpleVT() <= N1.getSimpleValueType() && 3762 "Extract subvector must be from larger vector to smaller vector!"); 3763 3764 if (N2C) { 3765 assert((VT.getVectorNumElements() + N2C->getZExtValue() 3766 <= N1.getValueType().getVectorNumElements()) 3767 && "Extract subvector overflow!"); 3768 } 3769 3770 // Trivial extraction. 3771 if (VT.getSimpleVT() == N1.getSimpleValueType()) 3772 return N1; 3773 3774 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 3775 // during shuffle legalization. 3776 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 3777 VT == N1.getOperand(1).getValueType()) 3778 return N1.getOperand(1); 3779 } 3780 break; 3781 } 3782 3783 // Perform trivial constant folding. 3784 if (SDValue SV = 3785 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode())) 3786 return SV; 3787 3788 // Constant fold FP operations. 3789 bool HasFPExceptions = TLI->hasFloatingPointExceptions(); 3790 if (N1CFP) { 3791 if (N2CFP) { 3792 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF(); 3793 APFloat::opStatus s; 3794 switch (Opcode) { 3795 case ISD::FADD: 3796 s = V1.add(V2, APFloat::rmNearestTiesToEven); 3797 if (!HasFPExceptions || s != APFloat::opInvalidOp) 3798 return getConstantFP(V1, DL, VT); 3799 break; 3800 case ISD::FSUB: 3801 s = V1.subtract(V2, APFloat::rmNearestTiesToEven); 3802 if (!HasFPExceptions || s!=APFloat::opInvalidOp) 3803 return getConstantFP(V1, DL, VT); 3804 break; 3805 case ISD::FMUL: 3806 s = V1.multiply(V2, APFloat::rmNearestTiesToEven); 3807 if (!HasFPExceptions || s!=APFloat::opInvalidOp) 3808 return getConstantFP(V1, DL, VT); 3809 break; 3810 case ISD::FDIV: 3811 s = V1.divide(V2, APFloat::rmNearestTiesToEven); 3812 if (!HasFPExceptions || (s!=APFloat::opInvalidOp && 3813 s!=APFloat::opDivByZero)) { 3814 return getConstantFP(V1, DL, VT); 3815 } 3816 break; 3817 case ISD::FREM : 3818 s = V1.mod(V2); 3819 if (!HasFPExceptions || (s!=APFloat::opInvalidOp && 3820 s!=APFloat::opDivByZero)) { 3821 return getConstantFP(V1, DL, VT); 3822 } 3823 break; 3824 case ISD::FCOPYSIGN: 3825 V1.copySign(V2); 3826 return getConstantFP(V1, DL, VT); 3827 default: break; 3828 } 3829 } 3830 3831 if (Opcode == ISD::FP_ROUND) { 3832 APFloat V = N1CFP->getValueAPF(); // make copy 3833 bool ignored; 3834 // This can return overflow, underflow, or inexact; we don't care. 3835 // FIXME need to be more flexible about rounding mode. 3836 (void)V.convert(EVTToAPFloatSemantics(VT), 3837 APFloat::rmNearestTiesToEven, &ignored); 3838 return getConstantFP(V, DL, VT); 3839 } 3840 } 3841 3842 // Canonicalize an UNDEF to the RHS, even over a constant. 3843 if (N1.isUndef()) { 3844 if (isCommutativeBinOp(Opcode)) { 3845 std::swap(N1, N2); 3846 } else { 3847 switch (Opcode) { 3848 case ISD::FP_ROUND_INREG: 3849 case ISD::SIGN_EXTEND_INREG: 3850 case ISD::SUB: 3851 case ISD::FSUB: 3852 case ISD::FDIV: 3853 case ISD::FREM: 3854 case ISD::SRA: 3855 return N1; // fold op(undef, arg2) -> undef 3856 case ISD::UDIV: 3857 case ISD::SDIV: 3858 case ISD::UREM: 3859 case ISD::SREM: 3860 case ISD::SRL: 3861 case ISD::SHL: 3862 if (!VT.isVector()) 3863 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 3864 // For vectors, we can't easily build an all zero vector, just return 3865 // the LHS. 3866 return N2; 3867 } 3868 } 3869 } 3870 3871 // Fold a bunch of operators when the RHS is undef. 3872 if (N2.isUndef()) { 3873 switch (Opcode) { 3874 case ISD::XOR: 3875 if (N1.isUndef()) 3876 // Handle undef ^ undef -> 0 special case. This is a common 3877 // idiom (misuse). 3878 return getConstant(0, DL, VT); 3879 LLVM_FALLTHROUGH; 3880 case ISD::ADD: 3881 case ISD::ADDC: 3882 case ISD::ADDE: 3883 case ISD::SUB: 3884 case ISD::UDIV: 3885 case ISD::SDIV: 3886 case ISD::UREM: 3887 case ISD::SREM: 3888 return N2; // fold op(arg1, undef) -> undef 3889 case ISD::FADD: 3890 case ISD::FSUB: 3891 case ISD::FMUL: 3892 case ISD::FDIV: 3893 case ISD::FREM: 3894 if (getTarget().Options.UnsafeFPMath) 3895 return N2; 3896 break; 3897 case ISD::MUL: 3898 case ISD::AND: 3899 case ISD::SRL: 3900 case ISD::SHL: 3901 if (!VT.isVector()) 3902 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 3903 // For vectors, we can't easily build an all zero vector, just return 3904 // the LHS. 3905 return N1; 3906 case ISD::OR: 3907 if (!VT.isVector()) 3908 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT); 3909 // For vectors, we can't easily build an all one vector, just return 3910 // the LHS. 3911 return N1; 3912 case ISD::SRA: 3913 return N1; 3914 } 3915 } 3916 3917 // Memoize this node if possible. 3918 SDNode *N; 3919 SDVTList VTs = getVTList(VT); 3920 if (VT != MVT::Glue) { 3921 SDValue Ops[] = {N1, N2}; 3922 FoldingSetNodeID ID; 3923 AddNodeIDNode(ID, Opcode, VTs, Ops); 3924 void *IP = nullptr; 3925 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 3926 if (Flags) 3927 E->intersectFlagsWith(Flags); 3928 return SDValue(E, 0); 3929 } 3930 3931 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags); 3932 CSEMap.InsertNode(N, IP); 3933 } else { 3934 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags); 3935 } 3936 3937 InsertNode(N); 3938 return SDValue(N, 0); 3939 } 3940 3941 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 3942 SDValue N1, SDValue N2, SDValue N3) { 3943 // Perform various simplifications. 3944 switch (Opcode) { 3945 case ISD::FMA: { 3946 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3947 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 3948 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 3949 if (N1CFP && N2CFP && N3CFP) { 3950 APFloat V1 = N1CFP->getValueAPF(); 3951 const APFloat &V2 = N2CFP->getValueAPF(); 3952 const APFloat &V3 = N3CFP->getValueAPF(); 3953 APFloat::opStatus s = 3954 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 3955 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp) 3956 return getConstantFP(V1, DL, VT); 3957 } 3958 break; 3959 } 3960 case ISD::CONCAT_VECTORS: { 3961 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 3962 SDValue Ops[] = {N1, N2, N3}; 3963 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 3964 return V; 3965 break; 3966 } 3967 case ISD::SETCC: { 3968 // Use FoldSetCC to simplify SETCC's. 3969 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 3970 return V; 3971 // Vector constant folding. 3972 SDValue Ops[] = {N1, N2, N3}; 3973 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 3974 return V; 3975 break; 3976 } 3977 case ISD::SELECT: 3978 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 3979 if (N1C->getZExtValue()) 3980 return N2; // select true, X, Y -> X 3981 return N3; // select false, X, Y -> Y 3982 } 3983 3984 if (N2 == N3) return N2; // select C, X, X -> X 3985 break; 3986 case ISD::VECTOR_SHUFFLE: 3987 llvm_unreachable("should use getVectorShuffle constructor!"); 3988 case ISD::INSERT_SUBVECTOR: { 3989 SDValue Index = N3; 3990 if (VT.isSimple() && N1.getValueType().isSimple() 3991 && N2.getValueType().isSimple()) { 3992 assert(VT.isVector() && N1.getValueType().isVector() && 3993 N2.getValueType().isVector() && 3994 "Insert subvector VTs must be a vectors"); 3995 assert(VT == N1.getValueType() && 3996 "Dest and insert subvector source types must match!"); 3997 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() && 3998 "Insert subvector must be from smaller vector to larger vector!"); 3999 if (isa<ConstantSDNode>(Index)) { 4000 assert((N2.getValueType().getVectorNumElements() + 4001 cast<ConstantSDNode>(Index)->getZExtValue() 4002 <= VT.getVectorNumElements()) 4003 && "Insert subvector overflow!"); 4004 } 4005 4006 // Trivial insertion. 4007 if (VT.getSimpleVT() == N2.getSimpleValueType()) 4008 return N2; 4009 } 4010 break; 4011 } 4012 case ISD::BITCAST: 4013 // Fold bit_convert nodes from a type to themselves. 4014 if (N1.getValueType() == VT) 4015 return N1; 4016 break; 4017 } 4018 4019 // Memoize node if it doesn't produce a flag. 4020 SDNode *N; 4021 SDVTList VTs = getVTList(VT); 4022 SDValue Ops[] = {N1, N2, N3}; 4023 if (VT != MVT::Glue) { 4024 FoldingSetNodeID ID; 4025 AddNodeIDNode(ID, Opcode, VTs, Ops); 4026 void *IP = nullptr; 4027 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4028 return SDValue(E, 0); 4029 4030 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4031 createOperands(N, Ops); 4032 CSEMap.InsertNode(N, IP); 4033 } else { 4034 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4035 createOperands(N, Ops); 4036 } 4037 4038 InsertNode(N); 4039 return SDValue(N, 0); 4040 } 4041 4042 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4043 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 4044 SDValue Ops[] = { N1, N2, N3, N4 }; 4045 return getNode(Opcode, DL, VT, Ops); 4046 } 4047 4048 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4049 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 4050 SDValue N5) { 4051 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 4052 return getNode(Opcode, DL, VT, Ops); 4053 } 4054 4055 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 4056 /// the incoming stack arguments to be loaded from the stack. 4057 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 4058 SmallVector<SDValue, 8> ArgChains; 4059 4060 // Include the original chain at the beginning of the list. When this is 4061 // used by target LowerCall hooks, this helps legalize find the 4062 // CALLSEQ_BEGIN node. 4063 ArgChains.push_back(Chain); 4064 4065 // Add a chain value for each stack argument. 4066 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 4067 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 4068 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 4069 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 4070 if (FI->getIndex() < 0) 4071 ArgChains.push_back(SDValue(L, 1)); 4072 4073 // Build a tokenfactor for all the chains. 4074 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 4075 } 4076 4077 /// getMemsetValue - Vectorized representation of the memset value 4078 /// operand. 4079 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 4080 const SDLoc &dl) { 4081 assert(!Value.isUndef()); 4082 4083 unsigned NumBits = VT.getScalarType().getSizeInBits(); 4084 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 4085 assert(C->getAPIntValue().getBitWidth() == 8); 4086 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 4087 if (VT.isInteger()) 4088 return DAG.getConstant(Val, dl, VT); 4089 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 4090 VT); 4091 } 4092 4093 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 4094 EVT IntVT = VT.getScalarType(); 4095 if (!IntVT.isInteger()) 4096 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 4097 4098 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 4099 if (NumBits > 8) { 4100 // Use a multiplication with 0x010101... to extend the input to the 4101 // required length. 4102 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 4103 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 4104 DAG.getConstant(Magic, dl, IntVT)); 4105 } 4106 4107 if (VT != Value.getValueType() && !VT.isInteger()) 4108 Value = DAG.getBitcast(VT.getScalarType(), Value); 4109 if (VT != Value.getValueType()) 4110 Value = DAG.getSplatBuildVector(VT, dl, Value); 4111 4112 return Value; 4113 } 4114 4115 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 4116 /// used when a memcpy is turned into a memset when the source is a constant 4117 /// string ptr. 4118 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 4119 const TargetLowering &TLI, StringRef Str) { 4120 // Handle vector with all elements zero. 4121 if (Str.empty()) { 4122 if (VT.isInteger()) 4123 return DAG.getConstant(0, dl, VT); 4124 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 4125 return DAG.getConstantFP(0.0, dl, VT); 4126 else if (VT.isVector()) { 4127 unsigned NumElts = VT.getVectorNumElements(); 4128 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 4129 return DAG.getNode(ISD::BITCAST, dl, VT, 4130 DAG.getConstant(0, dl, 4131 EVT::getVectorVT(*DAG.getContext(), 4132 EltVT, NumElts))); 4133 } else 4134 llvm_unreachable("Expected type!"); 4135 } 4136 4137 assert(!VT.isVector() && "Can't handle vector type here!"); 4138 unsigned NumVTBits = VT.getSizeInBits(); 4139 unsigned NumVTBytes = NumVTBits / 8; 4140 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size())); 4141 4142 APInt Val(NumVTBits, 0); 4143 if (DAG.getDataLayout().isLittleEndian()) { 4144 for (unsigned i = 0; i != NumBytes; ++i) 4145 Val |= (uint64_t)(unsigned char)Str[i] << i*8; 4146 } else { 4147 for (unsigned i = 0; i != NumBytes; ++i) 4148 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8; 4149 } 4150 4151 // If the "cost" of materializing the integer immediate is less than the cost 4152 // of a load, then it is cost effective to turn the load into the immediate. 4153 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 4154 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 4155 return DAG.getConstant(Val, dl, VT); 4156 return SDValue(nullptr, 0); 4157 } 4158 4159 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset, 4160 const SDLoc &DL) { 4161 EVT VT = Base.getValueType(); 4162 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT)); 4163 } 4164 4165 /// isMemSrcFromString - Returns true if memcpy source is a string constant. 4166 /// 4167 static bool isMemSrcFromString(SDValue Src, StringRef &Str) { 4168 uint64_t SrcDelta = 0; 4169 GlobalAddressSDNode *G = nullptr; 4170 if (Src.getOpcode() == ISD::GlobalAddress) 4171 G = cast<GlobalAddressSDNode>(Src); 4172 else if (Src.getOpcode() == ISD::ADD && 4173 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 4174 Src.getOperand(1).getOpcode() == ISD::Constant) { 4175 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 4176 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 4177 } 4178 if (!G) 4179 return false; 4180 4181 return getConstantStringInfo(G->getGlobal(), Str, 4182 SrcDelta + G->getOffset(), false); 4183 } 4184 4185 /// Determines the optimal series of memory ops to replace the memset / memcpy. 4186 /// Return true if the number of memory ops is below the threshold (Limit). 4187 /// It returns the types of the sequence of memory ops to perform 4188 /// memset / memcpy by reference. 4189 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps, 4190 unsigned Limit, uint64_t Size, 4191 unsigned DstAlign, unsigned SrcAlign, 4192 bool IsMemset, 4193 bool ZeroMemset, 4194 bool MemcpyStrSrc, 4195 bool AllowOverlap, 4196 unsigned DstAS, unsigned SrcAS, 4197 SelectionDAG &DAG, 4198 const TargetLowering &TLI) { 4199 assert((SrcAlign == 0 || SrcAlign >= DstAlign) && 4200 "Expecting memcpy / memset source to meet alignment requirement!"); 4201 // If 'SrcAlign' is zero, that means the memory operation does not need to 4202 // load the value, i.e. memset or memcpy from constant string. Otherwise, 4203 // it's the inferred alignment of the source. 'DstAlign', on the other hand, 4204 // is the specified alignment of the memory operation. If it is zero, that 4205 // means it's possible to change the alignment of the destination. 4206 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does 4207 // not need to be loaded. 4208 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign, 4209 IsMemset, ZeroMemset, MemcpyStrSrc, 4210 DAG.getMachineFunction()); 4211 4212 if (VT == MVT::Other) { 4213 if (DstAlign >= DAG.getDataLayout().getPointerPrefAlignment(DstAS) || 4214 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign)) { 4215 VT = TLI.getPointerTy(DAG.getDataLayout(), DstAS); 4216 } else { 4217 switch (DstAlign & 7) { 4218 case 0: VT = MVT::i64; break; 4219 case 4: VT = MVT::i32; break; 4220 case 2: VT = MVT::i16; break; 4221 default: VT = MVT::i8; break; 4222 } 4223 } 4224 4225 MVT LVT = MVT::i64; 4226 while (!TLI.isTypeLegal(LVT)) 4227 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 4228 assert(LVT.isInteger()); 4229 4230 if (VT.bitsGT(LVT)) 4231 VT = LVT; 4232 } 4233 4234 unsigned NumMemOps = 0; 4235 while (Size != 0) { 4236 unsigned VTSize = VT.getSizeInBits() / 8; 4237 while (VTSize > Size) { 4238 // For now, only use non-vector load / store's for the left-over pieces. 4239 EVT NewVT = VT; 4240 unsigned NewVTSize; 4241 4242 bool Found = false; 4243 if (VT.isVector() || VT.isFloatingPoint()) { 4244 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 4245 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) && 4246 TLI.isSafeMemOpType(NewVT.getSimpleVT())) 4247 Found = true; 4248 else if (NewVT == MVT::i64 && 4249 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 4250 TLI.isSafeMemOpType(MVT::f64)) { 4251 // i64 is usually not legal on 32-bit targets, but f64 may be. 4252 NewVT = MVT::f64; 4253 Found = true; 4254 } 4255 } 4256 4257 if (!Found) { 4258 do { 4259 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 4260 if (NewVT == MVT::i8) 4261 break; 4262 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT())); 4263 } 4264 NewVTSize = NewVT.getSizeInBits() / 8; 4265 4266 // If the new VT cannot cover all of the remaining bits, then consider 4267 // issuing a (or a pair of) unaligned and overlapping load / store. 4268 // FIXME: Only does this for 64-bit or more since we don't have proper 4269 // cost model for unaligned load / store. 4270 bool Fast; 4271 if (NumMemOps && AllowOverlap && 4272 VTSize >= 8 && NewVTSize < Size && 4273 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast) 4274 VTSize = Size; 4275 else { 4276 VT = NewVT; 4277 VTSize = NewVTSize; 4278 } 4279 } 4280 4281 if (++NumMemOps > Limit) 4282 return false; 4283 4284 MemOps.push_back(VT); 4285 Size -= VTSize; 4286 } 4287 4288 return true; 4289 } 4290 4291 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) { 4292 // On Darwin, -Os means optimize for size without hurting performance, so 4293 // only really optimize for size when -Oz (MinSize) is used. 4294 if (MF.getTarget().getTargetTriple().isOSDarwin()) 4295 return MF.getFunction()->optForMinSize(); 4296 return MF.getFunction()->optForSize(); 4297 } 4298 4299 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 4300 SDValue Chain, SDValue Dst, SDValue Src, 4301 uint64_t Size, unsigned Align, 4302 bool isVol, bool AlwaysInline, 4303 MachinePointerInfo DstPtrInfo, 4304 MachinePointerInfo SrcPtrInfo) { 4305 // Turn a memcpy of undef to nop. 4306 if (Src.isUndef()) 4307 return Chain; 4308 4309 // Expand memcpy to a series of load and store ops if the size operand falls 4310 // below a certain threshold. 4311 // TODO: In the AlwaysInline case, if the size is big then generate a loop 4312 // rather than maybe a humongous number of loads and stores. 4313 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4314 std::vector<EVT> MemOps; 4315 bool DstAlignCanChange = false; 4316 MachineFunction &MF = DAG.getMachineFunction(); 4317 MachineFrameInfo &MFI = MF.getFrameInfo(); 4318 bool OptSize = shouldLowerMemFuncForSize(MF); 4319 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 4320 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 4321 DstAlignCanChange = true; 4322 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 4323 if (Align > SrcAlign) 4324 SrcAlign = Align; 4325 StringRef Str; 4326 bool CopyFromStr = isMemSrcFromString(Src, Str); 4327 bool isZeroStr = CopyFromStr && Str.empty(); 4328 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 4329 4330 if (!FindOptimalMemOpLowering(MemOps, Limit, Size, 4331 (DstAlignCanChange ? 0 : Align), 4332 (isZeroStr ? 0 : SrcAlign), 4333 false, false, CopyFromStr, true, 4334 DstPtrInfo.getAddrSpace(), 4335 SrcPtrInfo.getAddrSpace(), 4336 DAG, TLI)) 4337 return SDValue(); 4338 4339 if (DstAlignCanChange) { 4340 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 4341 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty); 4342 4343 // Don't promote to an alignment that would require dynamic stack 4344 // realignment. 4345 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 4346 if (!TRI->needsStackRealignment(MF)) 4347 while (NewAlign > Align && 4348 DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign)) 4349 NewAlign /= 2; 4350 4351 if (NewAlign > Align) { 4352 // Give the stack frame object a larger alignment if needed. 4353 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign) 4354 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 4355 Align = NewAlign; 4356 } 4357 } 4358 4359 MachineMemOperand::Flags MMOFlags = 4360 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 4361 SmallVector<SDValue, 8> OutChains; 4362 unsigned NumMemOps = MemOps.size(); 4363 uint64_t SrcOff = 0, DstOff = 0; 4364 for (unsigned i = 0; i != NumMemOps; ++i) { 4365 EVT VT = MemOps[i]; 4366 unsigned VTSize = VT.getSizeInBits() / 8; 4367 SDValue Value, Store; 4368 4369 if (VTSize > Size) { 4370 // Issuing an unaligned load / store pair that overlaps with the previous 4371 // pair. Adjust the offset accordingly. 4372 assert(i == NumMemOps-1 && i != 0); 4373 SrcOff -= VTSize - Size; 4374 DstOff -= VTSize - Size; 4375 } 4376 4377 if (CopyFromStr && 4378 (isZeroStr || (VT.isInteger() && !VT.isVector()))) { 4379 // It's unlikely a store of a vector immediate can be done in a single 4380 // instruction. It would require a load from a constantpool first. 4381 // We only handle zero vectors here. 4382 // FIXME: Handle other cases where store of vector immediate is done in 4383 // a single instruction. 4384 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff)); 4385 if (Value.getNode()) 4386 Store = DAG.getStore(Chain, dl, Value, 4387 DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4388 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags); 4389 } 4390 4391 if (!Store.getNode()) { 4392 // The type might not be legal for the target. This should only happen 4393 // if the type is smaller than a legal type, as on PPC, so the right 4394 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 4395 // to Load/Store if NVT==VT. 4396 // FIXME does the case above also need this? 4397 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 4398 assert(NVT.bitsGE(VT)); 4399 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain, 4400 DAG.getMemBasePlusOffset(Src, SrcOff, dl), 4401 SrcPtrInfo.getWithOffset(SrcOff), VT, 4402 MinAlign(SrcAlign, SrcOff), MMOFlags); 4403 OutChains.push_back(Value.getValue(1)); 4404 Store = DAG.getTruncStore( 4405 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4406 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags); 4407 } 4408 OutChains.push_back(Store); 4409 SrcOff += VTSize; 4410 DstOff += VTSize; 4411 Size -= VTSize; 4412 } 4413 4414 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 4415 } 4416 4417 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 4418 SDValue Chain, SDValue Dst, SDValue Src, 4419 uint64_t Size, unsigned Align, 4420 bool isVol, bool AlwaysInline, 4421 MachinePointerInfo DstPtrInfo, 4422 MachinePointerInfo SrcPtrInfo) { 4423 // Turn a memmove of undef to nop. 4424 if (Src.isUndef()) 4425 return Chain; 4426 4427 // Expand memmove to a series of load and store ops if the size operand falls 4428 // below a certain threshold. 4429 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4430 std::vector<EVT> MemOps; 4431 bool DstAlignCanChange = false; 4432 MachineFunction &MF = DAG.getMachineFunction(); 4433 MachineFrameInfo &MFI = MF.getFrameInfo(); 4434 bool OptSize = shouldLowerMemFuncForSize(MF); 4435 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 4436 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 4437 DstAlignCanChange = true; 4438 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 4439 if (Align > SrcAlign) 4440 SrcAlign = Align; 4441 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 4442 4443 if (!FindOptimalMemOpLowering(MemOps, Limit, Size, 4444 (DstAlignCanChange ? 0 : Align), SrcAlign, 4445 false, false, false, false, 4446 DstPtrInfo.getAddrSpace(), 4447 SrcPtrInfo.getAddrSpace(), 4448 DAG, TLI)) 4449 return SDValue(); 4450 4451 if (DstAlignCanChange) { 4452 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 4453 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty); 4454 if (NewAlign > Align) { 4455 // Give the stack frame object a larger alignment if needed. 4456 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign) 4457 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 4458 Align = NewAlign; 4459 } 4460 } 4461 4462 MachineMemOperand::Flags MMOFlags = 4463 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 4464 uint64_t SrcOff = 0, DstOff = 0; 4465 SmallVector<SDValue, 8> LoadValues; 4466 SmallVector<SDValue, 8> LoadChains; 4467 SmallVector<SDValue, 8> OutChains; 4468 unsigned NumMemOps = MemOps.size(); 4469 for (unsigned i = 0; i < NumMemOps; i++) { 4470 EVT VT = MemOps[i]; 4471 unsigned VTSize = VT.getSizeInBits() / 8; 4472 SDValue Value; 4473 4474 Value = 4475 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl), 4476 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, MMOFlags); 4477 LoadValues.push_back(Value); 4478 LoadChains.push_back(Value.getValue(1)); 4479 SrcOff += VTSize; 4480 } 4481 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 4482 OutChains.clear(); 4483 for (unsigned i = 0; i < NumMemOps; i++) { 4484 EVT VT = MemOps[i]; 4485 unsigned VTSize = VT.getSizeInBits() / 8; 4486 SDValue Store; 4487 4488 Store = DAG.getStore(Chain, dl, LoadValues[i], 4489 DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4490 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags); 4491 OutChains.push_back(Store); 4492 DstOff += VTSize; 4493 } 4494 4495 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 4496 } 4497 4498 /// \brief Lower the call to 'memset' intrinsic function into a series of store 4499 /// operations. 4500 /// 4501 /// \param DAG Selection DAG where lowered code is placed. 4502 /// \param dl Link to corresponding IR location. 4503 /// \param Chain Control flow dependency. 4504 /// \param Dst Pointer to destination memory location. 4505 /// \param Src Value of byte to write into the memory. 4506 /// \param Size Number of bytes to write. 4507 /// \param Align Alignment of the destination in bytes. 4508 /// \param isVol True if destination is volatile. 4509 /// \param DstPtrInfo IR information on the memory pointer. 4510 /// \returns New head in the control flow, if lowering was successful, empty 4511 /// SDValue otherwise. 4512 /// 4513 /// The function tries to replace 'llvm.memset' intrinsic with several store 4514 /// operations and value calculation code. This is usually profitable for small 4515 /// memory size. 4516 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 4517 SDValue Chain, SDValue Dst, SDValue Src, 4518 uint64_t Size, unsigned Align, bool isVol, 4519 MachinePointerInfo DstPtrInfo) { 4520 // Turn a memset of undef to nop. 4521 if (Src.isUndef()) 4522 return Chain; 4523 4524 // Expand memset to a series of load/store ops if the size operand 4525 // falls below a certain threshold. 4526 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4527 std::vector<EVT> MemOps; 4528 bool DstAlignCanChange = false; 4529 MachineFunction &MF = DAG.getMachineFunction(); 4530 MachineFrameInfo &MFI = MF.getFrameInfo(); 4531 bool OptSize = shouldLowerMemFuncForSize(MF); 4532 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 4533 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 4534 DstAlignCanChange = true; 4535 bool IsZeroVal = 4536 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 4537 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize), 4538 Size, (DstAlignCanChange ? 0 : Align), 0, 4539 true, IsZeroVal, false, true, 4540 DstPtrInfo.getAddrSpace(), ~0u, 4541 DAG, TLI)) 4542 return SDValue(); 4543 4544 if (DstAlignCanChange) { 4545 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 4546 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty); 4547 if (NewAlign > Align) { 4548 // Give the stack frame object a larger alignment if needed. 4549 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign) 4550 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 4551 Align = NewAlign; 4552 } 4553 } 4554 4555 SmallVector<SDValue, 8> OutChains; 4556 uint64_t DstOff = 0; 4557 unsigned NumMemOps = MemOps.size(); 4558 4559 // Find the largest store and generate the bit pattern for it. 4560 EVT LargestVT = MemOps[0]; 4561 for (unsigned i = 1; i < NumMemOps; i++) 4562 if (MemOps[i].bitsGT(LargestVT)) 4563 LargestVT = MemOps[i]; 4564 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 4565 4566 for (unsigned i = 0; i < NumMemOps; i++) { 4567 EVT VT = MemOps[i]; 4568 unsigned VTSize = VT.getSizeInBits() / 8; 4569 if (VTSize > Size) { 4570 // Issuing an unaligned load / store pair that overlaps with the previous 4571 // pair. Adjust the offset accordingly. 4572 assert(i == NumMemOps-1 && i != 0); 4573 DstOff -= VTSize - Size; 4574 } 4575 4576 // If this store is smaller than the largest store see whether we can get 4577 // the smaller value for free with a truncate. 4578 SDValue Value = MemSetValue; 4579 if (VT.bitsLT(LargestVT)) { 4580 if (!LargestVT.isVector() && !VT.isVector() && 4581 TLI.isTruncateFree(LargestVT, VT)) 4582 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 4583 else 4584 Value = getMemsetValue(Src, VT, DAG, dl); 4585 } 4586 assert(Value.getValueType() == VT && "Value with wrong type."); 4587 SDValue Store = DAG.getStore( 4588 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4589 DstPtrInfo.getWithOffset(DstOff), Align, 4590 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone); 4591 OutChains.push_back(Store); 4592 DstOff += VT.getSizeInBits() / 8; 4593 Size -= VTSize; 4594 } 4595 4596 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 4597 } 4598 4599 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 4600 unsigned AS) { 4601 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 4602 // pointer operands can be losslessly bitcasted to pointers of address space 0 4603 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) { 4604 report_fatal_error("cannot lower memory intrinsic in address space " + 4605 Twine(AS)); 4606 } 4607 } 4608 4609 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 4610 SDValue Src, SDValue Size, unsigned Align, 4611 bool isVol, bool AlwaysInline, bool isTailCall, 4612 MachinePointerInfo DstPtrInfo, 4613 MachinePointerInfo SrcPtrInfo) { 4614 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4615 4616 // Check to see if we should lower the memcpy to loads and stores first. 4617 // For cases within the target-specified limits, this is the best choice. 4618 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4619 if (ConstantSize) { 4620 // Memcpy with size zero? Just return the original chain. 4621 if (ConstantSize->isNullValue()) 4622 return Chain; 4623 4624 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 4625 ConstantSize->getZExtValue(),Align, 4626 isVol, false, DstPtrInfo, SrcPtrInfo); 4627 if (Result.getNode()) 4628 return Result; 4629 } 4630 4631 // Then check to see if we should lower the memcpy with target-specific 4632 // code. If the target chooses to do this, this is the next best. 4633 if (TSI) { 4634 SDValue Result = TSI->EmitTargetCodeForMemcpy( 4635 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline, 4636 DstPtrInfo, SrcPtrInfo); 4637 if (Result.getNode()) 4638 return Result; 4639 } 4640 4641 // If we really need inline code and the target declined to provide it, 4642 // use a (potentially long) sequence of loads and stores. 4643 if (AlwaysInline) { 4644 assert(ConstantSize && "AlwaysInline requires a constant size!"); 4645 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 4646 ConstantSize->getZExtValue(), Align, isVol, 4647 true, DstPtrInfo, SrcPtrInfo); 4648 } 4649 4650 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 4651 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 4652 4653 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 4654 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 4655 // respect volatile, so they may do things like read or write memory 4656 // beyond the given memory regions. But fixing this isn't easy, and most 4657 // people don't care. 4658 4659 // Emit a library call. 4660 TargetLowering::ArgListTy Args; 4661 TargetLowering::ArgListEntry Entry; 4662 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 4663 Entry.Node = Dst; Args.push_back(Entry); 4664 Entry.Node = Src; Args.push_back(Entry); 4665 Entry.Node = Size; Args.push_back(Entry); 4666 // FIXME: pass in SDLoc 4667 TargetLowering::CallLoweringInfo CLI(*this); 4668 CLI.setDebugLoc(dl) 4669 .setChain(Chain) 4670 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 4671 Dst.getValueType().getTypeForEVT(*getContext()), 4672 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 4673 TLI->getPointerTy(getDataLayout())), 4674 std::move(Args)) 4675 .setDiscardResult() 4676 .setTailCall(isTailCall); 4677 4678 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4679 return CallResult.second; 4680 } 4681 4682 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 4683 SDValue Src, SDValue Size, unsigned Align, 4684 bool isVol, bool isTailCall, 4685 MachinePointerInfo DstPtrInfo, 4686 MachinePointerInfo SrcPtrInfo) { 4687 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4688 4689 // Check to see if we should lower the memmove to loads and stores first. 4690 // For cases within the target-specified limits, this is the best choice. 4691 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4692 if (ConstantSize) { 4693 // Memmove with size zero? Just return the original chain. 4694 if (ConstantSize->isNullValue()) 4695 return Chain; 4696 4697 SDValue Result = 4698 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src, 4699 ConstantSize->getZExtValue(), Align, isVol, 4700 false, DstPtrInfo, SrcPtrInfo); 4701 if (Result.getNode()) 4702 return Result; 4703 } 4704 4705 // Then check to see if we should lower the memmove with target-specific 4706 // code. If the target chooses to do this, this is the next best. 4707 if (TSI) { 4708 SDValue Result = TSI->EmitTargetCodeForMemmove( 4709 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo); 4710 if (Result.getNode()) 4711 return Result; 4712 } 4713 4714 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 4715 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 4716 4717 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 4718 // not be safe. See memcpy above for more details. 4719 4720 // Emit a library call. 4721 TargetLowering::ArgListTy Args; 4722 TargetLowering::ArgListEntry Entry; 4723 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 4724 Entry.Node = Dst; Args.push_back(Entry); 4725 Entry.Node = Src; Args.push_back(Entry); 4726 Entry.Node = Size; Args.push_back(Entry); 4727 // FIXME: pass in SDLoc 4728 TargetLowering::CallLoweringInfo CLI(*this); 4729 CLI.setDebugLoc(dl) 4730 .setChain(Chain) 4731 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 4732 Dst.getValueType().getTypeForEVT(*getContext()), 4733 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 4734 TLI->getPointerTy(getDataLayout())), 4735 std::move(Args)) 4736 .setDiscardResult() 4737 .setTailCall(isTailCall); 4738 4739 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4740 return CallResult.second; 4741 } 4742 4743 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 4744 SDValue Src, SDValue Size, unsigned Align, 4745 bool isVol, bool isTailCall, 4746 MachinePointerInfo DstPtrInfo) { 4747 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4748 4749 // Check to see if we should lower the memset to stores first. 4750 // For cases within the target-specified limits, this is the best choice. 4751 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4752 if (ConstantSize) { 4753 // Memset with size zero? Just return the original chain. 4754 if (ConstantSize->isNullValue()) 4755 return Chain; 4756 4757 SDValue Result = 4758 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), 4759 Align, isVol, DstPtrInfo); 4760 4761 if (Result.getNode()) 4762 return Result; 4763 } 4764 4765 // Then check to see if we should lower the memset with target-specific 4766 // code. If the target chooses to do this, this is the next best. 4767 if (TSI) { 4768 SDValue Result = TSI->EmitTargetCodeForMemset( 4769 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo); 4770 if (Result.getNode()) 4771 return Result; 4772 } 4773 4774 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 4775 4776 // Emit a library call. 4777 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext()); 4778 TargetLowering::ArgListTy Args; 4779 TargetLowering::ArgListEntry Entry; 4780 Entry.Node = Dst; Entry.Ty = IntPtrTy; 4781 Args.push_back(Entry); 4782 Entry.Node = Src; 4783 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 4784 Args.push_back(Entry); 4785 Entry.Node = Size; 4786 Entry.Ty = IntPtrTy; 4787 Args.push_back(Entry); 4788 4789 // FIXME: pass in SDLoc 4790 TargetLowering::CallLoweringInfo CLI(*this); 4791 CLI.setDebugLoc(dl) 4792 .setChain(Chain) 4793 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 4794 Dst.getValueType().getTypeForEVT(*getContext()), 4795 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 4796 TLI->getPointerTy(getDataLayout())), 4797 std::move(Args)) 4798 .setDiscardResult() 4799 .setTailCall(isTailCall); 4800 4801 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4802 return CallResult.second; 4803 } 4804 4805 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 4806 SDVTList VTList, ArrayRef<SDValue> Ops, 4807 MachineMemOperand *MMO, 4808 AtomicOrdering SuccessOrdering, 4809 AtomicOrdering FailureOrdering, 4810 SynchronizationScope SynchScope) { 4811 FoldingSetNodeID ID; 4812 ID.AddInteger(MemVT.getRawBits()); 4813 AddNodeIDNode(ID, Opcode, VTList, Ops); 4814 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 4815 void* IP = nullptr; 4816 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 4817 cast<AtomicSDNode>(E)->refineAlignment(MMO); 4818 return SDValue(E, 0); 4819 } 4820 4821 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 4822 VTList, MemVT, MMO, SuccessOrdering, 4823 FailureOrdering, SynchScope); 4824 createOperands(N, Ops); 4825 4826 CSEMap.InsertNode(N, IP); 4827 InsertNode(N); 4828 return SDValue(N, 0); 4829 } 4830 4831 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 4832 SDVTList VTList, ArrayRef<SDValue> Ops, 4833 MachineMemOperand *MMO, AtomicOrdering Ordering, 4834 SynchronizationScope SynchScope) { 4835 return getAtomic(Opcode, dl, MemVT, VTList, Ops, MMO, Ordering, 4836 Ordering, SynchScope); 4837 } 4838 4839 SDValue SelectionDAG::getAtomicCmpSwap( 4840 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, 4841 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo, 4842 unsigned Alignment, AtomicOrdering SuccessOrdering, 4843 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) { 4844 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 4845 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 4846 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 4847 4848 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4849 Alignment = getEVTAlignment(MemVT); 4850 4851 MachineFunction &MF = getMachineFunction(); 4852 4853 // FIXME: Volatile isn't really correct; we should keep track of atomic 4854 // orderings in the memoperand. 4855 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad | 4856 MachineMemOperand::MOStore; 4857 MachineMemOperand *MMO = 4858 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment); 4859 4860 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO, 4861 SuccessOrdering, FailureOrdering, SynchScope); 4862 } 4863 4864 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 4865 EVT MemVT, SDVTList VTs, SDValue Chain, 4866 SDValue Ptr, SDValue Cmp, SDValue Swp, 4867 MachineMemOperand *MMO, 4868 AtomicOrdering SuccessOrdering, 4869 AtomicOrdering FailureOrdering, 4870 SynchronizationScope SynchScope) { 4871 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 4872 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 4873 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 4874 4875 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 4876 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, 4877 SuccessOrdering, FailureOrdering, SynchScope); 4878 } 4879 4880 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 4881 SDValue Chain, SDValue Ptr, SDValue Val, 4882 const Value *PtrVal, unsigned Alignment, 4883 AtomicOrdering Ordering, 4884 SynchronizationScope SynchScope) { 4885 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4886 Alignment = getEVTAlignment(MemVT); 4887 4888 MachineFunction &MF = getMachineFunction(); 4889 // An atomic store does not load. An atomic load does not store. 4890 // (An atomicrmw obviously both loads and stores.) 4891 // For now, atomics are considered to be volatile always, and they are 4892 // chained as such. 4893 // FIXME: Volatile isn't really correct; we should keep track of atomic 4894 // orderings in the memoperand. 4895 auto Flags = MachineMemOperand::MOVolatile; 4896 if (Opcode != ISD::ATOMIC_STORE) 4897 Flags |= MachineMemOperand::MOLoad; 4898 if (Opcode != ISD::ATOMIC_LOAD) 4899 Flags |= MachineMemOperand::MOStore; 4900 4901 MachineMemOperand *MMO = 4902 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags, 4903 MemVT.getStoreSize(), Alignment); 4904 4905 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO, 4906 Ordering, SynchScope); 4907 } 4908 4909 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 4910 SDValue Chain, SDValue Ptr, SDValue Val, 4911 MachineMemOperand *MMO, AtomicOrdering Ordering, 4912 SynchronizationScope SynchScope) { 4913 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 4914 Opcode == ISD::ATOMIC_LOAD_SUB || 4915 Opcode == ISD::ATOMIC_LOAD_AND || 4916 Opcode == ISD::ATOMIC_LOAD_OR || 4917 Opcode == ISD::ATOMIC_LOAD_XOR || 4918 Opcode == ISD::ATOMIC_LOAD_NAND || 4919 Opcode == ISD::ATOMIC_LOAD_MIN || 4920 Opcode == ISD::ATOMIC_LOAD_MAX || 4921 Opcode == ISD::ATOMIC_LOAD_UMIN || 4922 Opcode == ISD::ATOMIC_LOAD_UMAX || 4923 Opcode == ISD::ATOMIC_SWAP || 4924 Opcode == ISD::ATOMIC_STORE) && 4925 "Invalid Atomic Op"); 4926 4927 EVT VT = Val.getValueType(); 4928 4929 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 4930 getVTList(VT, MVT::Other); 4931 SDValue Ops[] = {Chain, Ptr, Val}; 4932 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope); 4933 } 4934 4935 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 4936 EVT VT, SDValue Chain, SDValue Ptr, 4937 MachineMemOperand *MMO, AtomicOrdering Ordering, 4938 SynchronizationScope SynchScope) { 4939 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 4940 4941 SDVTList VTs = getVTList(VT, MVT::Other); 4942 SDValue Ops[] = {Chain, Ptr}; 4943 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope); 4944 } 4945 4946 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 4947 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 4948 if (Ops.size() == 1) 4949 return Ops[0]; 4950 4951 SmallVector<EVT, 4> VTs; 4952 VTs.reserve(Ops.size()); 4953 for (unsigned i = 0; i < Ops.size(); ++i) 4954 VTs.push_back(Ops[i].getValueType()); 4955 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 4956 } 4957 4958 SDValue SelectionDAG::getMemIntrinsicNode( 4959 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 4960 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol, 4961 bool ReadMem, bool WriteMem, unsigned Size) { 4962 if (Align == 0) // Ensure that codegen never sees alignment 0 4963 Align = getEVTAlignment(MemVT); 4964 4965 MachineFunction &MF = getMachineFunction(); 4966 auto Flags = MachineMemOperand::MONone; 4967 if (WriteMem) 4968 Flags |= MachineMemOperand::MOStore; 4969 if (ReadMem) 4970 Flags |= MachineMemOperand::MOLoad; 4971 if (Vol) 4972 Flags |= MachineMemOperand::MOVolatile; 4973 if (!Size) 4974 Size = MemVT.getStoreSize(); 4975 MachineMemOperand *MMO = 4976 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align); 4977 4978 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 4979 } 4980 4981 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 4982 SDVTList VTList, 4983 ArrayRef<SDValue> Ops, EVT MemVT, 4984 MachineMemOperand *MMO) { 4985 assert((Opcode == ISD::INTRINSIC_VOID || 4986 Opcode == ISD::INTRINSIC_W_CHAIN || 4987 Opcode == ISD::PREFETCH || 4988 Opcode == ISD::LIFETIME_START || 4989 Opcode == ISD::LIFETIME_END || 4990 (Opcode <= INT_MAX && 4991 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 4992 "Opcode is not a memory-accessing opcode!"); 4993 4994 // Memoize the node unless it returns a flag. 4995 MemIntrinsicSDNode *N; 4996 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 4997 FoldingSetNodeID ID; 4998 AddNodeIDNode(ID, Opcode, VTList, Ops); 4999 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5000 void *IP = nullptr; 5001 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5002 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 5003 return SDValue(E, 0); 5004 } 5005 5006 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 5007 VTList, MemVT, MMO); 5008 createOperands(N, Ops); 5009 5010 CSEMap.InsertNode(N, IP); 5011 } else { 5012 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 5013 VTList, MemVT, MMO); 5014 createOperands(N, Ops); 5015 } 5016 InsertNode(N); 5017 return SDValue(N, 0); 5018 } 5019 5020 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 5021 /// MachinePointerInfo record from it. This is particularly useful because the 5022 /// code generator has many cases where it doesn't bother passing in a 5023 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 5024 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr, 5025 int64_t Offset = 0) { 5026 // If this is FI+Offset, we can model it. 5027 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 5028 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 5029 FI->getIndex(), Offset); 5030 5031 // If this is (FI+Offset1)+Offset2, we can model it. 5032 if (Ptr.getOpcode() != ISD::ADD || 5033 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 5034 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 5035 return MachinePointerInfo(); 5036 5037 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 5038 return MachinePointerInfo::getFixedStack( 5039 DAG.getMachineFunction(), FI, 5040 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 5041 } 5042 5043 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 5044 /// MachinePointerInfo record from it. This is particularly useful because the 5045 /// code generator has many cases where it doesn't bother passing in a 5046 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 5047 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr, 5048 SDValue OffsetOp) { 5049 // If the 'Offset' value isn't a constant, we can't handle this. 5050 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 5051 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue()); 5052 if (OffsetOp.isUndef()) 5053 return InferPointerInfo(DAG, Ptr); 5054 return MachinePointerInfo(); 5055 } 5056 5057 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 5058 EVT VT, const SDLoc &dl, SDValue Chain, 5059 SDValue Ptr, SDValue Offset, 5060 MachinePointerInfo PtrInfo, EVT MemVT, 5061 unsigned Alignment, 5062 MachineMemOperand::Flags MMOFlags, 5063 const AAMDNodes &AAInfo, const MDNode *Ranges) { 5064 assert(Chain.getValueType() == MVT::Other && 5065 "Invalid chain type"); 5066 if (Alignment == 0) // Ensure that codegen never sees alignment 0 5067 Alignment = getEVTAlignment(VT); 5068 5069 MMOFlags |= MachineMemOperand::MOLoad; 5070 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 5071 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 5072 // clients. 5073 if (PtrInfo.V.isNull()) 5074 PtrInfo = InferPointerInfo(*this, Ptr, Offset); 5075 5076 MachineFunction &MF = getMachineFunction(); 5077 MachineMemOperand *MMO = MF.getMachineMemOperand( 5078 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges); 5079 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 5080 } 5081 5082 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 5083 EVT VT, const SDLoc &dl, SDValue Chain, 5084 SDValue Ptr, SDValue Offset, EVT MemVT, 5085 MachineMemOperand *MMO) { 5086 if (VT == MemVT) { 5087 ExtType = ISD::NON_EXTLOAD; 5088 } else if (ExtType == ISD::NON_EXTLOAD) { 5089 assert(VT == MemVT && "Non-extending load from different memory type!"); 5090 } else { 5091 // Extending load. 5092 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 5093 "Should only be an extending load, not truncating!"); 5094 assert(VT.isInteger() == MemVT.isInteger() && 5095 "Cannot convert from FP to Int or Int -> FP!"); 5096 assert(VT.isVector() == MemVT.isVector() && 5097 "Cannot use an ext load to convert to or from a vector!"); 5098 assert((!VT.isVector() || 5099 VT.getVectorNumElements() == MemVT.getVectorNumElements()) && 5100 "Cannot use an ext load to change the number of vector elements!"); 5101 } 5102 5103 bool Indexed = AM != ISD::UNINDEXED; 5104 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 5105 5106 SDVTList VTs = Indexed ? 5107 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 5108 SDValue Ops[] = { Chain, Ptr, Offset }; 5109 FoldingSetNodeID ID; 5110 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 5111 ID.AddInteger(MemVT.getRawBits()); 5112 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 5113 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 5114 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5115 void *IP = nullptr; 5116 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5117 cast<LoadSDNode>(E)->refineAlignment(MMO); 5118 return SDValue(E, 0); 5119 } 5120 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 5121 ExtType, MemVT, MMO); 5122 createOperands(N, Ops); 5123 5124 CSEMap.InsertNode(N, IP); 5125 InsertNode(N); 5126 return SDValue(N, 0); 5127 } 5128 5129 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 5130 SDValue Ptr, MachinePointerInfo PtrInfo, 5131 unsigned Alignment, 5132 MachineMemOperand::Flags MMOFlags, 5133 const AAMDNodes &AAInfo, const MDNode *Ranges) { 5134 SDValue Undef = getUNDEF(Ptr.getValueType()); 5135 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 5136 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 5137 } 5138 5139 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 5140 SDValue Ptr, MachineMemOperand *MMO) { 5141 SDValue Undef = getUNDEF(Ptr.getValueType()); 5142 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 5143 VT, MMO); 5144 } 5145 5146 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 5147 EVT VT, SDValue Chain, SDValue Ptr, 5148 MachinePointerInfo PtrInfo, EVT MemVT, 5149 unsigned Alignment, 5150 MachineMemOperand::Flags MMOFlags, 5151 const AAMDNodes &AAInfo) { 5152 SDValue Undef = getUNDEF(Ptr.getValueType()); 5153 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 5154 MemVT, Alignment, MMOFlags, AAInfo); 5155 } 5156 5157 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 5158 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 5159 MachineMemOperand *MMO) { 5160 SDValue Undef = getUNDEF(Ptr.getValueType()); 5161 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 5162 MemVT, MMO); 5163 } 5164 5165 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 5166 SDValue Base, SDValue Offset, 5167 ISD::MemIndexedMode AM) { 5168 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 5169 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 5170 // Don't propagate the invariant flag. 5171 auto MMOFlags = 5172 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOInvariant; 5173 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 5174 LD->getChain(), Base, Offset, LD->getPointerInfo(), 5175 LD->getMemoryVT(), LD->getAlignment(), MMOFlags, 5176 LD->getAAInfo()); 5177 } 5178 5179 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 5180 SDValue Ptr, MachinePointerInfo PtrInfo, 5181 unsigned Alignment, 5182 MachineMemOperand::Flags MMOFlags, 5183 const AAMDNodes &AAInfo) { 5184 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 5185 if (Alignment == 0) // Ensure that codegen never sees alignment 0 5186 Alignment = getEVTAlignment(Val.getValueType()); 5187 5188 MMOFlags |= MachineMemOperand::MOStore; 5189 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 5190 5191 if (PtrInfo.V.isNull()) 5192 PtrInfo = InferPointerInfo(*this, Ptr); 5193 5194 MachineFunction &MF = getMachineFunction(); 5195 MachineMemOperand *MMO = MF.getMachineMemOperand( 5196 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo); 5197 return getStore(Chain, dl, Val, Ptr, MMO); 5198 } 5199 5200 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 5201 SDValue Ptr, MachineMemOperand *MMO) { 5202 assert(Chain.getValueType() == MVT::Other && 5203 "Invalid chain type"); 5204 EVT VT = Val.getValueType(); 5205 SDVTList VTs = getVTList(MVT::Other); 5206 SDValue Undef = getUNDEF(Ptr.getValueType()); 5207 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 5208 FoldingSetNodeID ID; 5209 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 5210 ID.AddInteger(VT.getRawBits()); 5211 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 5212 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 5213 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5214 void *IP = nullptr; 5215 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5216 cast<StoreSDNode>(E)->refineAlignment(MMO); 5217 return SDValue(E, 0); 5218 } 5219 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 5220 ISD::UNINDEXED, false, VT, MMO); 5221 createOperands(N, Ops); 5222 5223 CSEMap.InsertNode(N, IP); 5224 InsertNode(N); 5225 return SDValue(N, 0); 5226 } 5227 5228 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 5229 SDValue Ptr, MachinePointerInfo PtrInfo, 5230 EVT SVT, unsigned Alignment, 5231 MachineMemOperand::Flags MMOFlags, 5232 const AAMDNodes &AAInfo) { 5233 assert(Chain.getValueType() == MVT::Other && 5234 "Invalid chain type"); 5235 if (Alignment == 0) // Ensure that codegen never sees alignment 0 5236 Alignment = getEVTAlignment(SVT); 5237 5238 MMOFlags |= MachineMemOperand::MOStore; 5239 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 5240 5241 if (PtrInfo.V.isNull()) 5242 PtrInfo = InferPointerInfo(*this, Ptr); 5243 5244 MachineFunction &MF = getMachineFunction(); 5245 MachineMemOperand *MMO = MF.getMachineMemOperand( 5246 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo); 5247 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 5248 } 5249 5250 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 5251 SDValue Ptr, EVT SVT, 5252 MachineMemOperand *MMO) { 5253 EVT VT = Val.getValueType(); 5254 5255 assert(Chain.getValueType() == MVT::Other && 5256 "Invalid chain type"); 5257 if (VT == SVT) 5258 return getStore(Chain, dl, Val, Ptr, MMO); 5259 5260 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 5261 "Should only be a truncating store, not extending!"); 5262 assert(VT.isInteger() == SVT.isInteger() && 5263 "Can't do FP-INT conversion!"); 5264 assert(VT.isVector() == SVT.isVector() && 5265 "Cannot use trunc store to convert to or from a vector!"); 5266 assert((!VT.isVector() || 5267 VT.getVectorNumElements() == SVT.getVectorNumElements()) && 5268 "Cannot use trunc store to change the number of vector elements!"); 5269 5270 SDVTList VTs = getVTList(MVT::Other); 5271 SDValue Undef = getUNDEF(Ptr.getValueType()); 5272 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 5273 FoldingSetNodeID ID; 5274 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 5275 ID.AddInteger(SVT.getRawBits()); 5276 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 5277 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 5278 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5279 void *IP = nullptr; 5280 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5281 cast<StoreSDNode>(E)->refineAlignment(MMO); 5282 return SDValue(E, 0); 5283 } 5284 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 5285 ISD::UNINDEXED, true, SVT, MMO); 5286 createOperands(N, Ops); 5287 5288 CSEMap.InsertNode(N, IP); 5289 InsertNode(N); 5290 return SDValue(N, 0); 5291 } 5292 5293 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 5294 SDValue Base, SDValue Offset, 5295 ISD::MemIndexedMode AM) { 5296 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 5297 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 5298 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 5299 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 5300 FoldingSetNodeID ID; 5301 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 5302 ID.AddInteger(ST->getMemoryVT().getRawBits()); 5303 ID.AddInteger(ST->getRawSubclassData()); 5304 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 5305 void *IP = nullptr; 5306 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 5307 return SDValue(E, 0); 5308 5309 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 5310 ST->isTruncatingStore(), ST->getMemoryVT(), 5311 ST->getMemOperand()); 5312 createOperands(N, Ops); 5313 5314 CSEMap.InsertNode(N, IP); 5315 InsertNode(N); 5316 return SDValue(N, 0); 5317 } 5318 5319 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 5320 SDValue Ptr, SDValue Mask, SDValue Src0, 5321 EVT MemVT, MachineMemOperand *MMO, 5322 ISD::LoadExtType ExtTy) { 5323 5324 SDVTList VTs = getVTList(VT, MVT::Other); 5325 SDValue Ops[] = { Chain, Ptr, Mask, Src0 }; 5326 FoldingSetNodeID ID; 5327 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 5328 ID.AddInteger(VT.getRawBits()); 5329 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 5330 dl.getIROrder(), VTs, ExtTy, MemVT, MMO)); 5331 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5332 void *IP = nullptr; 5333 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5334 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 5335 return SDValue(E, 0); 5336 } 5337 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 5338 ExtTy, MemVT, MMO); 5339 createOperands(N, Ops); 5340 5341 CSEMap.InsertNode(N, IP); 5342 InsertNode(N); 5343 return SDValue(N, 0); 5344 } 5345 5346 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 5347 SDValue Val, SDValue Ptr, SDValue Mask, 5348 EVT MemVT, MachineMemOperand *MMO, 5349 bool isTrunc) { 5350 assert(Chain.getValueType() == MVT::Other && 5351 "Invalid chain type"); 5352 EVT VT = Val.getValueType(); 5353 SDVTList VTs = getVTList(MVT::Other); 5354 SDValue Ops[] = { Chain, Ptr, Mask, Val }; 5355 FoldingSetNodeID ID; 5356 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 5357 ID.AddInteger(VT.getRawBits()); 5358 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 5359 dl.getIROrder(), VTs, isTrunc, MemVT, MMO)); 5360 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5361 void *IP = nullptr; 5362 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5363 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 5364 return SDValue(E, 0); 5365 } 5366 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 5367 isTrunc, MemVT, MMO); 5368 createOperands(N, Ops); 5369 5370 CSEMap.InsertNode(N, IP); 5371 InsertNode(N); 5372 return SDValue(N, 0); 5373 } 5374 5375 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl, 5376 ArrayRef<SDValue> Ops, 5377 MachineMemOperand *MMO) { 5378 assert(Ops.size() == 5 && "Incompatible number of operands"); 5379 5380 FoldingSetNodeID ID; 5381 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 5382 ID.AddInteger(VT.getRawBits()); 5383 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 5384 dl.getIROrder(), VTs, VT, MMO)); 5385 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5386 void *IP = nullptr; 5387 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5388 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 5389 return SDValue(E, 0); 5390 } 5391 5392 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 5393 VTs, VT, MMO); 5394 createOperands(N, Ops); 5395 5396 assert(N->getValue().getValueType() == N->getValueType(0) && 5397 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 5398 assert(N->getMask().getValueType().getVectorNumElements() == 5399 N->getValueType(0).getVectorNumElements() && 5400 "Vector width mismatch between mask and data"); 5401 assert(N->getIndex().getValueType().getVectorNumElements() == 5402 N->getValueType(0).getVectorNumElements() && 5403 "Vector width mismatch between index and data"); 5404 5405 CSEMap.InsertNode(N, IP); 5406 InsertNode(N); 5407 return SDValue(N, 0); 5408 } 5409 5410 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl, 5411 ArrayRef<SDValue> Ops, 5412 MachineMemOperand *MMO) { 5413 assert(Ops.size() == 5 && "Incompatible number of operands"); 5414 5415 FoldingSetNodeID ID; 5416 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 5417 ID.AddInteger(VT.getRawBits()); 5418 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 5419 dl.getIROrder(), VTs, VT, MMO)); 5420 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5421 void *IP = nullptr; 5422 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5423 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 5424 return SDValue(E, 0); 5425 } 5426 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 5427 VTs, VT, MMO); 5428 createOperands(N, Ops); 5429 5430 assert(N->getMask().getValueType().getVectorNumElements() == 5431 N->getValue().getValueType().getVectorNumElements() && 5432 "Vector width mismatch between mask and data"); 5433 assert(N->getIndex().getValueType().getVectorNumElements() == 5434 N->getValue().getValueType().getVectorNumElements() && 5435 "Vector width mismatch between index and data"); 5436 5437 CSEMap.InsertNode(N, IP); 5438 InsertNode(N); 5439 return SDValue(N, 0); 5440 } 5441 5442 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 5443 SDValue Ptr, SDValue SV, unsigned Align) { 5444 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 5445 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 5446 } 5447 5448 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5449 ArrayRef<SDUse> Ops) { 5450 switch (Ops.size()) { 5451 case 0: return getNode(Opcode, DL, VT); 5452 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 5453 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 5454 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 5455 default: break; 5456 } 5457 5458 // Copy from an SDUse array into an SDValue array for use with 5459 // the regular getNode logic. 5460 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 5461 return getNode(Opcode, DL, VT, NewOps); 5462 } 5463 5464 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5465 ArrayRef<SDValue> Ops, const SDNodeFlags *Flags) { 5466 unsigned NumOps = Ops.size(); 5467 switch (NumOps) { 5468 case 0: return getNode(Opcode, DL, VT); 5469 case 1: return getNode(Opcode, DL, VT, Ops[0]); 5470 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 5471 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 5472 default: break; 5473 } 5474 5475 switch (Opcode) { 5476 default: break; 5477 case ISD::CONCAT_VECTORS: { 5478 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 5479 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 5480 return V; 5481 break; 5482 } 5483 case ISD::SELECT_CC: { 5484 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 5485 assert(Ops[0].getValueType() == Ops[1].getValueType() && 5486 "LHS and RHS of condition must have same type!"); 5487 assert(Ops[2].getValueType() == Ops[3].getValueType() && 5488 "True and False arms of SelectCC must have same type!"); 5489 assert(Ops[2].getValueType() == VT && 5490 "select_cc node must be of same type as true and false value!"); 5491 break; 5492 } 5493 case ISD::BR_CC: { 5494 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 5495 assert(Ops[2].getValueType() == Ops[3].getValueType() && 5496 "LHS/RHS of comparison should match types!"); 5497 break; 5498 } 5499 } 5500 5501 // Memoize nodes. 5502 SDNode *N; 5503 SDVTList VTs = getVTList(VT); 5504 5505 if (VT != MVT::Glue) { 5506 FoldingSetNodeID ID; 5507 AddNodeIDNode(ID, Opcode, VTs, Ops); 5508 void *IP = nullptr; 5509 5510 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5511 return SDValue(E, 0); 5512 5513 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5514 createOperands(N, Ops); 5515 5516 CSEMap.InsertNode(N, IP); 5517 } else { 5518 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5519 createOperands(N, Ops); 5520 } 5521 5522 InsertNode(N); 5523 return SDValue(N, 0); 5524 } 5525 5526 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 5527 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 5528 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 5529 } 5530 5531 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 5532 ArrayRef<SDValue> Ops) { 5533 if (VTList.NumVTs == 1) 5534 return getNode(Opcode, DL, VTList.VTs[0], Ops); 5535 5536 #if 0 5537 switch (Opcode) { 5538 // FIXME: figure out how to safely handle things like 5539 // int foo(int x) { return 1 << (x & 255); } 5540 // int bar() { return foo(256); } 5541 case ISD::SRA_PARTS: 5542 case ISD::SRL_PARTS: 5543 case ISD::SHL_PARTS: 5544 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 5545 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 5546 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 5547 else if (N3.getOpcode() == ISD::AND) 5548 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 5549 // If the and is only masking out bits that cannot effect the shift, 5550 // eliminate the and. 5551 unsigned NumBits = VT.getScalarType().getSizeInBits()*2; 5552 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 5553 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 5554 } 5555 break; 5556 } 5557 #endif 5558 5559 // Memoize the node unless it returns a flag. 5560 SDNode *N; 5561 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 5562 FoldingSetNodeID ID; 5563 AddNodeIDNode(ID, Opcode, VTList, Ops); 5564 void *IP = nullptr; 5565 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5566 return SDValue(E, 0); 5567 5568 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 5569 createOperands(N, Ops); 5570 CSEMap.InsertNode(N, IP); 5571 } else { 5572 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 5573 createOperands(N, Ops); 5574 } 5575 InsertNode(N); 5576 return SDValue(N, 0); 5577 } 5578 5579 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 5580 SDVTList VTList) { 5581 return getNode(Opcode, DL, VTList, None); 5582 } 5583 5584 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 5585 SDValue N1) { 5586 SDValue Ops[] = { N1 }; 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) { 5592 SDValue Ops[] = { N1, N2 }; 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) { 5598 SDValue Ops[] = { N1, N2, N3 }; 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 Ops[] = { N1, N2, N3, N4 }; 5605 return getNode(Opcode, DL, VTList, Ops); 5606 } 5607 5608 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 5609 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 5610 SDValue N5) { 5611 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 5612 return getNode(Opcode, DL, VTList, Ops); 5613 } 5614 5615 SDVTList SelectionDAG::getVTList(EVT VT) { 5616 return makeVTList(SDNode::getValueTypeList(VT), 1); 5617 } 5618 5619 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 5620 FoldingSetNodeID ID; 5621 ID.AddInteger(2U); 5622 ID.AddInteger(VT1.getRawBits()); 5623 ID.AddInteger(VT2.getRawBits()); 5624 5625 void *IP = nullptr; 5626 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5627 if (!Result) { 5628 EVT *Array = Allocator.Allocate<EVT>(2); 5629 Array[0] = VT1; 5630 Array[1] = VT2; 5631 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 5632 VTListMap.InsertNode(Result, IP); 5633 } 5634 return Result->getSDVTList(); 5635 } 5636 5637 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 5638 FoldingSetNodeID ID; 5639 ID.AddInteger(3U); 5640 ID.AddInteger(VT1.getRawBits()); 5641 ID.AddInteger(VT2.getRawBits()); 5642 ID.AddInteger(VT3.getRawBits()); 5643 5644 void *IP = nullptr; 5645 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5646 if (!Result) { 5647 EVT *Array = Allocator.Allocate<EVT>(3); 5648 Array[0] = VT1; 5649 Array[1] = VT2; 5650 Array[2] = VT3; 5651 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 5652 VTListMap.InsertNode(Result, IP); 5653 } 5654 return Result->getSDVTList(); 5655 } 5656 5657 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 5658 FoldingSetNodeID ID; 5659 ID.AddInteger(4U); 5660 ID.AddInteger(VT1.getRawBits()); 5661 ID.AddInteger(VT2.getRawBits()); 5662 ID.AddInteger(VT3.getRawBits()); 5663 ID.AddInteger(VT4.getRawBits()); 5664 5665 void *IP = nullptr; 5666 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5667 if (!Result) { 5668 EVT *Array = Allocator.Allocate<EVT>(4); 5669 Array[0] = VT1; 5670 Array[1] = VT2; 5671 Array[2] = VT3; 5672 Array[3] = VT4; 5673 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 5674 VTListMap.InsertNode(Result, IP); 5675 } 5676 return Result->getSDVTList(); 5677 } 5678 5679 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 5680 unsigned NumVTs = VTs.size(); 5681 FoldingSetNodeID ID; 5682 ID.AddInteger(NumVTs); 5683 for (unsigned index = 0; index < NumVTs; index++) { 5684 ID.AddInteger(VTs[index].getRawBits()); 5685 } 5686 5687 void *IP = nullptr; 5688 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5689 if (!Result) { 5690 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 5691 std::copy(VTs.begin(), VTs.end(), Array); 5692 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 5693 VTListMap.InsertNode(Result, IP); 5694 } 5695 return Result->getSDVTList(); 5696 } 5697 5698 5699 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 5700 /// specified operands. If the resultant node already exists in the DAG, 5701 /// this does not modify the specified node, instead it returns the node that 5702 /// already exists. If the resultant node does not exist in the DAG, the 5703 /// input node is returned. As a degenerate case, if you specify the same 5704 /// input operands as the node already has, the input node is returned. 5705 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 5706 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 5707 5708 // Check to see if there is no change. 5709 if (Op == N->getOperand(0)) return N; 5710 5711 // See if the modified node already exists. 5712 void *InsertPos = nullptr; 5713 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 5714 return Existing; 5715 5716 // Nope it doesn't. Remove the node from its current place in the maps. 5717 if (InsertPos) 5718 if (!RemoveNodeFromCSEMaps(N)) 5719 InsertPos = nullptr; 5720 5721 // Now we update the operands. 5722 N->OperandList[0].set(Op); 5723 5724 // If this gets put into a CSE map, add it. 5725 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5726 return N; 5727 } 5728 5729 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 5730 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 5731 5732 // Check to see if there is no change. 5733 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 5734 return N; // No operands changed, just return the input node. 5735 5736 // See if the modified node already exists. 5737 void *InsertPos = nullptr; 5738 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 5739 return Existing; 5740 5741 // Nope it doesn't. Remove the node from its current place in the maps. 5742 if (InsertPos) 5743 if (!RemoveNodeFromCSEMaps(N)) 5744 InsertPos = nullptr; 5745 5746 // Now we update the operands. 5747 if (N->OperandList[0] != Op1) 5748 N->OperandList[0].set(Op1); 5749 if (N->OperandList[1] != Op2) 5750 N->OperandList[1].set(Op2); 5751 5752 // If this gets put into a CSE map, add it. 5753 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5754 return N; 5755 } 5756 5757 SDNode *SelectionDAG:: 5758 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 5759 SDValue Ops[] = { Op1, Op2, Op3 }; 5760 return UpdateNodeOperands(N, Ops); 5761 } 5762 5763 SDNode *SelectionDAG:: 5764 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 5765 SDValue Op3, SDValue Op4) { 5766 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 5767 return UpdateNodeOperands(N, Ops); 5768 } 5769 5770 SDNode *SelectionDAG:: 5771 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 5772 SDValue Op3, SDValue Op4, SDValue Op5) { 5773 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 5774 return UpdateNodeOperands(N, Ops); 5775 } 5776 5777 SDNode *SelectionDAG:: 5778 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 5779 unsigned NumOps = Ops.size(); 5780 assert(N->getNumOperands() == NumOps && 5781 "Update with wrong number of operands"); 5782 5783 // If no operands changed just return the input node. 5784 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 5785 return N; 5786 5787 // See if the modified node already exists. 5788 void *InsertPos = nullptr; 5789 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 5790 return Existing; 5791 5792 // Nope it doesn't. Remove the node from its current place in the maps. 5793 if (InsertPos) 5794 if (!RemoveNodeFromCSEMaps(N)) 5795 InsertPos = nullptr; 5796 5797 // Now we update the operands. 5798 for (unsigned i = 0; i != NumOps; ++i) 5799 if (N->OperandList[i] != Ops[i]) 5800 N->OperandList[i].set(Ops[i]); 5801 5802 // If this gets put into a CSE map, add it. 5803 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5804 return N; 5805 } 5806 5807 /// DropOperands - Release the operands and set this node to have 5808 /// zero operands. 5809 void SDNode::DropOperands() { 5810 // Unlike the code in MorphNodeTo that does this, we don't need to 5811 // watch for dead nodes here. 5812 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 5813 SDUse &Use = *I++; 5814 Use.set(SDValue()); 5815 } 5816 } 5817 5818 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 5819 /// machine opcode. 5820 /// 5821 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5822 EVT VT) { 5823 SDVTList VTs = getVTList(VT); 5824 return SelectNodeTo(N, MachineOpc, VTs, None); 5825 } 5826 5827 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5828 EVT VT, SDValue Op1) { 5829 SDVTList VTs = getVTList(VT); 5830 SDValue Ops[] = { Op1 }; 5831 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5832 } 5833 5834 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5835 EVT VT, SDValue Op1, 5836 SDValue Op2) { 5837 SDVTList VTs = getVTList(VT); 5838 SDValue Ops[] = { Op1, Op2 }; 5839 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5840 } 5841 5842 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5843 EVT VT, SDValue Op1, 5844 SDValue Op2, SDValue Op3) { 5845 SDVTList VTs = getVTList(VT); 5846 SDValue Ops[] = { Op1, Op2, Op3 }; 5847 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5848 } 5849 5850 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5851 EVT VT, ArrayRef<SDValue> Ops) { 5852 SDVTList VTs = getVTList(VT); 5853 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5854 } 5855 5856 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5857 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 5858 SDVTList VTs = getVTList(VT1, VT2); 5859 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5860 } 5861 5862 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5863 EVT VT1, EVT VT2) { 5864 SDVTList VTs = getVTList(VT1, VT2); 5865 return SelectNodeTo(N, MachineOpc, VTs, None); 5866 } 5867 5868 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5869 EVT VT1, EVT VT2, EVT VT3, 5870 ArrayRef<SDValue> Ops) { 5871 SDVTList VTs = getVTList(VT1, VT2, VT3); 5872 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5873 } 5874 5875 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5876 EVT VT1, EVT VT2, EVT VT3, EVT VT4, 5877 ArrayRef<SDValue> Ops) { 5878 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4); 5879 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5880 } 5881 5882 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5883 EVT VT1, EVT VT2, 5884 SDValue Op1) { 5885 SDVTList VTs = getVTList(VT1, VT2); 5886 SDValue Ops[] = { Op1 }; 5887 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5888 } 5889 5890 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5891 EVT VT1, EVT VT2, 5892 SDValue Op1, SDValue Op2) { 5893 SDVTList VTs = getVTList(VT1, VT2); 5894 SDValue Ops[] = { Op1, Op2 }; 5895 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5896 } 5897 5898 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5899 EVT VT1, EVT VT2, 5900 SDValue Op1, SDValue Op2, 5901 SDValue Op3) { 5902 SDVTList VTs = getVTList(VT1, VT2); 5903 SDValue Ops[] = { Op1, Op2, Op3 }; 5904 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5905 } 5906 5907 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5908 EVT VT1, EVT VT2, EVT VT3, 5909 SDValue Op1, SDValue Op2, 5910 SDValue Op3) { 5911 SDVTList VTs = getVTList(VT1, VT2, VT3); 5912 SDValue Ops[] = { Op1, Op2, Op3 }; 5913 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5914 } 5915 5916 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5917 SDVTList VTs,ArrayRef<SDValue> Ops) { 5918 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 5919 // Reset the NodeID to -1. 5920 New->setNodeId(-1); 5921 if (New != N) { 5922 ReplaceAllUsesWith(N, New); 5923 RemoveDeadNode(N); 5924 } 5925 return New; 5926 } 5927 5928 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away 5929 /// the line number information on the merged node since it is not possible to 5930 /// preserve the information that operation is associated with multiple lines. 5931 /// This will make the debugger working better at -O0, were there is a higher 5932 /// probability having other instructions associated with that line. 5933 /// 5934 /// For IROrder, we keep the smaller of the two 5935 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, const SDLoc &OLoc) { 5936 DebugLoc NLoc = N->getDebugLoc(); 5937 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 5938 N->setDebugLoc(DebugLoc()); 5939 } 5940 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 5941 N->setIROrder(Order); 5942 return N; 5943 } 5944 5945 /// MorphNodeTo - This *mutates* the specified node to have the specified 5946 /// return type, opcode, and operands. 5947 /// 5948 /// Note that MorphNodeTo returns the resultant node. If there is already a 5949 /// node of the specified opcode and operands, it returns that node instead of 5950 /// the current one. Note that the SDLoc need not be the same. 5951 /// 5952 /// Using MorphNodeTo is faster than creating a new node and swapping it in 5953 /// with ReplaceAllUsesWith both because it often avoids allocating a new 5954 /// node, and because it doesn't require CSE recalculation for any of 5955 /// the node's users. 5956 /// 5957 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 5958 /// As a consequence it isn't appropriate to use from within the DAG combiner or 5959 /// the legalizer which maintain worklists that would need to be updated when 5960 /// deleting things. 5961 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 5962 SDVTList VTs, ArrayRef<SDValue> Ops) { 5963 // If an identical node already exists, use it. 5964 void *IP = nullptr; 5965 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 5966 FoldingSetNodeID ID; 5967 AddNodeIDNode(ID, Opc, VTs, Ops); 5968 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 5969 return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N)); 5970 } 5971 5972 if (!RemoveNodeFromCSEMaps(N)) 5973 IP = nullptr; 5974 5975 // Start the morphing. 5976 N->NodeType = Opc; 5977 N->ValueList = VTs.VTs; 5978 N->NumValues = VTs.NumVTs; 5979 5980 // Clear the operands list, updating used nodes to remove this from their 5981 // use list. Keep track of any operands that become dead as a result. 5982 SmallPtrSet<SDNode*, 16> DeadNodeSet; 5983 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 5984 SDUse &Use = *I++; 5985 SDNode *Used = Use.getNode(); 5986 Use.set(SDValue()); 5987 if (Used->use_empty()) 5988 DeadNodeSet.insert(Used); 5989 } 5990 5991 // For MachineNode, initialize the memory references information. 5992 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 5993 MN->setMemRefs(nullptr, nullptr); 5994 5995 // Swap for an appropriately sized array from the recycler. 5996 removeOperands(N); 5997 createOperands(N, Ops); 5998 5999 // Delete any nodes that are still dead after adding the uses for the 6000 // new operands. 6001 if (!DeadNodeSet.empty()) { 6002 SmallVector<SDNode *, 16> DeadNodes; 6003 for (SDNode *N : DeadNodeSet) 6004 if (N->use_empty()) 6005 DeadNodes.push_back(N); 6006 RemoveDeadNodes(DeadNodes); 6007 } 6008 6009 if (IP) 6010 CSEMap.InsertNode(N, IP); // Memoize the new node. 6011 return N; 6012 } 6013 6014 6015 /// getMachineNode - These are used for target selectors to create a new node 6016 /// with specified return type(s), MachineInstr opcode, and operands. 6017 /// 6018 /// Note that getMachineNode returns the resultant node. If there is already a 6019 /// node of the specified opcode and operands, it returns that node instead of 6020 /// the current one. 6021 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6022 EVT VT) { 6023 SDVTList VTs = getVTList(VT); 6024 return getMachineNode(Opcode, dl, VTs, None); 6025 } 6026 6027 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6028 EVT VT, SDValue Op1) { 6029 SDVTList VTs = getVTList(VT); 6030 SDValue Ops[] = { Op1 }; 6031 return getMachineNode(Opcode, dl, VTs, Ops); 6032 } 6033 6034 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6035 EVT VT, SDValue Op1, SDValue Op2) { 6036 SDVTList VTs = getVTList(VT); 6037 SDValue Ops[] = { Op1, Op2 }; 6038 return getMachineNode(Opcode, dl, VTs, Ops); 6039 } 6040 6041 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6042 EVT VT, SDValue Op1, SDValue Op2, 6043 SDValue Op3) { 6044 SDVTList VTs = getVTList(VT); 6045 SDValue Ops[] = { Op1, Op2, Op3 }; 6046 return getMachineNode(Opcode, dl, VTs, Ops); 6047 } 6048 6049 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6050 EVT VT, ArrayRef<SDValue> Ops) { 6051 SDVTList VTs = getVTList(VT); 6052 return getMachineNode(Opcode, dl, VTs, Ops); 6053 } 6054 6055 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6056 EVT VT1, EVT VT2) { 6057 SDVTList VTs = getVTList(VT1, VT2); 6058 return getMachineNode(Opcode, dl, VTs, None); 6059 } 6060 6061 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6062 EVT VT1, EVT VT2, SDValue Op1) { 6063 SDVTList VTs = getVTList(VT1, VT2); 6064 SDValue Ops[] = { Op1 }; 6065 return getMachineNode(Opcode, dl, VTs, Ops); 6066 } 6067 6068 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6069 EVT VT1, EVT VT2, SDValue Op1, 6070 SDValue Op2) { 6071 SDVTList VTs = getVTList(VT1, VT2); 6072 SDValue Ops[] = { Op1, Op2 }; 6073 return getMachineNode(Opcode, dl, VTs, Ops); 6074 } 6075 6076 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6077 EVT VT1, EVT VT2, SDValue Op1, 6078 SDValue Op2, SDValue Op3) { 6079 SDVTList VTs = getVTList(VT1, VT2); 6080 SDValue Ops[] = { Op1, Op2, Op3 }; 6081 return getMachineNode(Opcode, dl, VTs, Ops); 6082 } 6083 6084 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6085 EVT VT1, EVT VT2, 6086 ArrayRef<SDValue> Ops) { 6087 SDVTList VTs = getVTList(VT1, VT2); 6088 return getMachineNode(Opcode, dl, VTs, Ops); 6089 } 6090 6091 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6092 EVT VT1, EVT VT2, EVT VT3, 6093 SDValue Op1, SDValue Op2) { 6094 SDVTList VTs = getVTList(VT1, VT2, VT3); 6095 SDValue Ops[] = { Op1, Op2 }; 6096 return getMachineNode(Opcode, dl, VTs, Ops); 6097 } 6098 6099 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6100 EVT VT1, EVT VT2, EVT VT3, 6101 SDValue Op1, SDValue Op2, 6102 SDValue Op3) { 6103 SDVTList VTs = getVTList(VT1, VT2, VT3); 6104 SDValue Ops[] = { Op1, Op2, Op3 }; 6105 return getMachineNode(Opcode, dl, VTs, Ops); 6106 } 6107 6108 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6109 EVT VT1, EVT VT2, EVT VT3, 6110 ArrayRef<SDValue> Ops) { 6111 SDVTList VTs = getVTList(VT1, VT2, VT3); 6112 return getMachineNode(Opcode, dl, VTs, Ops); 6113 } 6114 6115 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6116 EVT VT1, EVT VT2, EVT VT3, EVT VT4, 6117 ArrayRef<SDValue> Ops) { 6118 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4); 6119 return getMachineNode(Opcode, dl, VTs, Ops); 6120 } 6121 6122 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6123 ArrayRef<EVT> ResultTys, 6124 ArrayRef<SDValue> Ops) { 6125 SDVTList VTs = getVTList(ResultTys); 6126 return getMachineNode(Opcode, dl, VTs, Ops); 6127 } 6128 6129 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 6130 SDVTList VTs, 6131 ArrayRef<SDValue> Ops) { 6132 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 6133 MachineSDNode *N; 6134 void *IP = nullptr; 6135 6136 if (DoCSE) { 6137 FoldingSetNodeID ID; 6138 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 6139 IP = nullptr; 6140 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6141 return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL)); 6142 } 6143 } 6144 6145 // Allocate a new MachineSDNode. 6146 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6147 createOperands(N, Ops); 6148 6149 if (DoCSE) 6150 CSEMap.InsertNode(N, IP); 6151 6152 InsertNode(N); 6153 return N; 6154 } 6155 6156 /// getTargetExtractSubreg - A convenience function for creating 6157 /// TargetOpcode::EXTRACT_SUBREG nodes. 6158 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 6159 SDValue Operand) { 6160 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 6161 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 6162 VT, Operand, SRIdxVal); 6163 return SDValue(Subreg, 0); 6164 } 6165 6166 /// getTargetInsertSubreg - A convenience function for creating 6167 /// TargetOpcode::INSERT_SUBREG nodes. 6168 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 6169 SDValue Operand, SDValue Subreg) { 6170 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 6171 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 6172 VT, Operand, Subreg, SRIdxVal); 6173 return SDValue(Result, 0); 6174 } 6175 6176 /// getNodeIfExists - Get the specified node if it's already available, or 6177 /// else return NULL. 6178 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 6179 ArrayRef<SDValue> Ops, 6180 const SDNodeFlags *Flags) { 6181 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 6182 FoldingSetNodeID ID; 6183 AddNodeIDNode(ID, Opcode, VTList, Ops); 6184 void *IP = nullptr; 6185 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 6186 if (Flags) 6187 E->intersectFlagsWith(Flags); 6188 return E; 6189 } 6190 } 6191 return nullptr; 6192 } 6193 6194 /// getDbgValue - Creates a SDDbgValue node. 6195 /// 6196 /// SDNode 6197 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N, 6198 unsigned R, bool IsIndirect, uint64_t Off, 6199 const DebugLoc &DL, unsigned O) { 6200 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 6201 "Expected inlined-at fields to agree"); 6202 return new (DbgInfo->getAlloc()) 6203 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O); 6204 } 6205 6206 /// Constant 6207 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr, 6208 const Value *C, uint64_t Off, 6209 const DebugLoc &DL, unsigned O) { 6210 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 6211 "Expected inlined-at fields to agree"); 6212 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O); 6213 } 6214 6215 /// FrameIndex 6216 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr, 6217 unsigned FI, uint64_t Off, 6218 const DebugLoc &DL, 6219 unsigned O) { 6220 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 6221 "Expected inlined-at fields to agree"); 6222 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O); 6223 } 6224 6225 namespace { 6226 6227 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 6228 /// pointed to by a use iterator is deleted, increment the use iterator 6229 /// so that it doesn't dangle. 6230 /// 6231 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 6232 SDNode::use_iterator &UI; 6233 SDNode::use_iterator &UE; 6234 6235 void NodeDeleted(SDNode *N, SDNode *E) override { 6236 // Increment the iterator as needed. 6237 while (UI != UE && N == *UI) 6238 ++UI; 6239 } 6240 6241 public: 6242 RAUWUpdateListener(SelectionDAG &d, 6243 SDNode::use_iterator &ui, 6244 SDNode::use_iterator &ue) 6245 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 6246 }; 6247 6248 } 6249 6250 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 6251 /// This can cause recursive merging of nodes in the DAG. 6252 /// 6253 /// This version assumes From has a single result value. 6254 /// 6255 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 6256 SDNode *From = FromN.getNode(); 6257 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 6258 "Cannot replace with this method!"); 6259 assert(From != To.getNode() && "Cannot replace uses of with self"); 6260 6261 // Preserve Debug Values 6262 TransferDbgValues(FromN, To); 6263 6264 // Iterate over all the existing uses of From. New uses will be added 6265 // to the beginning of the use list, which we avoid visiting. 6266 // This specifically avoids visiting uses of From that arise while the 6267 // replacement is happening, because any such uses would be the result 6268 // of CSE: If an existing node looks like From after one of its operands 6269 // is replaced by To, we don't want to replace of all its users with To 6270 // too. See PR3018 for more info. 6271 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 6272 RAUWUpdateListener Listener(*this, UI, UE); 6273 while (UI != UE) { 6274 SDNode *User = *UI; 6275 6276 // This node is about to morph, remove its old self from the CSE maps. 6277 RemoveNodeFromCSEMaps(User); 6278 6279 // A user can appear in a use list multiple times, and when this 6280 // happens the uses are usually next to each other in the list. 6281 // To help reduce the number of CSE recomputations, process all 6282 // the uses of this user that we can find this way. 6283 do { 6284 SDUse &Use = UI.getUse(); 6285 ++UI; 6286 Use.set(To); 6287 } while (UI != UE && *UI == User); 6288 6289 // Now that we have modified User, add it back to the CSE maps. If it 6290 // already exists there, recursively merge the results together. 6291 AddModifiedNodeToCSEMaps(User); 6292 } 6293 6294 6295 // If we just RAUW'd the root, take note. 6296 if (FromN == getRoot()) 6297 setRoot(To); 6298 } 6299 6300 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 6301 /// This can cause recursive merging of nodes in the DAG. 6302 /// 6303 /// This version assumes that for each value of From, there is a 6304 /// corresponding value in To in the same position with the same type. 6305 /// 6306 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 6307 #ifndef NDEBUG 6308 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 6309 assert((!From->hasAnyUseOfValue(i) || 6310 From->getValueType(i) == To->getValueType(i)) && 6311 "Cannot use this version of ReplaceAllUsesWith!"); 6312 #endif 6313 6314 // Handle the trivial case. 6315 if (From == To) 6316 return; 6317 6318 // Preserve Debug Info. Only do this if there's a use. 6319 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 6320 if (From->hasAnyUseOfValue(i)) { 6321 assert((i < To->getNumValues()) && "Invalid To location"); 6322 TransferDbgValues(SDValue(From, i), SDValue(To, i)); 6323 } 6324 6325 // Iterate over just the existing users of From. See the comments in 6326 // the ReplaceAllUsesWith above. 6327 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 6328 RAUWUpdateListener Listener(*this, UI, UE); 6329 while (UI != UE) { 6330 SDNode *User = *UI; 6331 6332 // This node is about to morph, remove its old self from the CSE maps. 6333 RemoveNodeFromCSEMaps(User); 6334 6335 // A user can appear in a use list multiple times, and when this 6336 // happens the uses are usually next to each other in the list. 6337 // To help reduce the number of CSE recomputations, process all 6338 // the uses of this user that we can find this way. 6339 do { 6340 SDUse &Use = UI.getUse(); 6341 ++UI; 6342 Use.setNode(To); 6343 } while (UI != UE && *UI == User); 6344 6345 // Now that we have modified User, add it back to the CSE maps. If it 6346 // already exists there, recursively merge the results together. 6347 AddModifiedNodeToCSEMaps(User); 6348 } 6349 6350 // If we just RAUW'd the root, take note. 6351 if (From == getRoot().getNode()) 6352 setRoot(SDValue(To, getRoot().getResNo())); 6353 } 6354 6355 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 6356 /// This can cause recursive merging of nodes in the DAG. 6357 /// 6358 /// This version can replace From with any result values. To must match the 6359 /// number and types of values returned by From. 6360 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 6361 if (From->getNumValues() == 1) // Handle the simple case efficiently. 6362 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 6363 6364 // Preserve Debug Info. 6365 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 6366 TransferDbgValues(SDValue(From, i), *To); 6367 6368 // Iterate over just the existing users of From. See the comments in 6369 // the ReplaceAllUsesWith above. 6370 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 6371 RAUWUpdateListener Listener(*this, UI, UE); 6372 while (UI != UE) { 6373 SDNode *User = *UI; 6374 6375 // This node is about to morph, remove its old self from the CSE maps. 6376 RemoveNodeFromCSEMaps(User); 6377 6378 // A user can appear in a use list multiple times, and when this 6379 // happens the uses are usually next to each other in the list. 6380 // To help reduce the number of CSE recomputations, process all 6381 // the uses of this user that we can find this way. 6382 do { 6383 SDUse &Use = UI.getUse(); 6384 const SDValue &ToOp = To[Use.getResNo()]; 6385 ++UI; 6386 Use.set(ToOp); 6387 } while (UI != UE && *UI == User); 6388 6389 // Now that we have modified User, add it back to the CSE maps. If it 6390 // already exists there, recursively merge the results together. 6391 AddModifiedNodeToCSEMaps(User); 6392 } 6393 6394 // If we just RAUW'd the root, take note. 6395 if (From == getRoot().getNode()) 6396 setRoot(SDValue(To[getRoot().getResNo()])); 6397 } 6398 6399 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 6400 /// uses of other values produced by From.getNode() alone. The Deleted 6401 /// vector is handled the same way as for ReplaceAllUsesWith. 6402 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 6403 // Handle the really simple, really trivial case efficiently. 6404 if (From == To) return; 6405 6406 // Handle the simple, trivial, case efficiently. 6407 if (From.getNode()->getNumValues() == 1) { 6408 ReplaceAllUsesWith(From, To); 6409 return; 6410 } 6411 6412 // Preserve Debug Info. 6413 TransferDbgValues(From, To); 6414 6415 // Iterate over just the existing users of From. See the comments in 6416 // the ReplaceAllUsesWith above. 6417 SDNode::use_iterator UI = From.getNode()->use_begin(), 6418 UE = From.getNode()->use_end(); 6419 RAUWUpdateListener Listener(*this, UI, UE); 6420 while (UI != UE) { 6421 SDNode *User = *UI; 6422 bool UserRemovedFromCSEMaps = false; 6423 6424 // A user can appear in a use list multiple times, and when this 6425 // happens the uses are usually next to each other in the list. 6426 // To help reduce the number of CSE recomputations, process all 6427 // the uses of this user that we can find this way. 6428 do { 6429 SDUse &Use = UI.getUse(); 6430 6431 // Skip uses of different values from the same node. 6432 if (Use.getResNo() != From.getResNo()) { 6433 ++UI; 6434 continue; 6435 } 6436 6437 // If this node hasn't been modified yet, it's still in the CSE maps, 6438 // so remove its old self from the CSE maps. 6439 if (!UserRemovedFromCSEMaps) { 6440 RemoveNodeFromCSEMaps(User); 6441 UserRemovedFromCSEMaps = true; 6442 } 6443 6444 ++UI; 6445 Use.set(To); 6446 } while (UI != UE && *UI == User); 6447 6448 // We are iterating over all uses of the From node, so if a use 6449 // doesn't use the specific value, no changes are made. 6450 if (!UserRemovedFromCSEMaps) 6451 continue; 6452 6453 // Now that we have modified User, add it back to the CSE maps. If it 6454 // already exists there, recursively merge the results together. 6455 AddModifiedNodeToCSEMaps(User); 6456 } 6457 6458 // If we just RAUW'd the root, take note. 6459 if (From == getRoot()) 6460 setRoot(To); 6461 } 6462 6463 namespace { 6464 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 6465 /// to record information about a use. 6466 struct UseMemo { 6467 SDNode *User; 6468 unsigned Index; 6469 SDUse *Use; 6470 }; 6471 6472 /// operator< - Sort Memos by User. 6473 bool operator<(const UseMemo &L, const UseMemo &R) { 6474 return (intptr_t)L.User < (intptr_t)R.User; 6475 } 6476 } 6477 6478 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 6479 /// uses of other values produced by From.getNode() alone. The same value 6480 /// may appear in both the From and To list. The Deleted vector is 6481 /// handled the same way as for ReplaceAllUsesWith. 6482 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 6483 const SDValue *To, 6484 unsigned Num){ 6485 // Handle the simple, trivial case efficiently. 6486 if (Num == 1) 6487 return ReplaceAllUsesOfValueWith(*From, *To); 6488 6489 TransferDbgValues(*From, *To); 6490 6491 // Read up all the uses and make records of them. This helps 6492 // processing new uses that are introduced during the 6493 // replacement process. 6494 SmallVector<UseMemo, 4> Uses; 6495 for (unsigned i = 0; i != Num; ++i) { 6496 unsigned FromResNo = From[i].getResNo(); 6497 SDNode *FromNode = From[i].getNode(); 6498 for (SDNode::use_iterator UI = FromNode->use_begin(), 6499 E = FromNode->use_end(); UI != E; ++UI) { 6500 SDUse &Use = UI.getUse(); 6501 if (Use.getResNo() == FromResNo) { 6502 UseMemo Memo = { *UI, i, &Use }; 6503 Uses.push_back(Memo); 6504 } 6505 } 6506 } 6507 6508 // Sort the uses, so that all the uses from a given User are together. 6509 std::sort(Uses.begin(), Uses.end()); 6510 6511 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 6512 UseIndex != UseIndexEnd; ) { 6513 // We know that this user uses some value of From. If it is the right 6514 // value, update it. 6515 SDNode *User = Uses[UseIndex].User; 6516 6517 // This node is about to morph, remove its old self from the CSE maps. 6518 RemoveNodeFromCSEMaps(User); 6519 6520 // The Uses array is sorted, so all the uses for a given User 6521 // are next to each other in the list. 6522 // To help reduce the number of CSE recomputations, process all 6523 // the uses of this user that we can find this way. 6524 do { 6525 unsigned i = Uses[UseIndex].Index; 6526 SDUse &Use = *Uses[UseIndex].Use; 6527 ++UseIndex; 6528 6529 Use.set(To[i]); 6530 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 6531 6532 // Now that we have modified User, add it back to the CSE maps. If it 6533 // already exists there, recursively merge the results together. 6534 AddModifiedNodeToCSEMaps(User); 6535 } 6536 } 6537 6538 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 6539 /// based on their topological order. It returns the maximum id and a vector 6540 /// of the SDNodes* in assigned order by reference. 6541 unsigned SelectionDAG::AssignTopologicalOrder() { 6542 6543 unsigned DAGSize = 0; 6544 6545 // SortedPos tracks the progress of the algorithm. Nodes before it are 6546 // sorted, nodes after it are unsorted. When the algorithm completes 6547 // it is at the end of the list. 6548 allnodes_iterator SortedPos = allnodes_begin(); 6549 6550 // Visit all the nodes. Move nodes with no operands to the front of 6551 // the list immediately. Annotate nodes that do have operands with their 6552 // operand count. Before we do this, the Node Id fields of the nodes 6553 // may contain arbitrary values. After, the Node Id fields for nodes 6554 // before SortedPos will contain the topological sort index, and the 6555 // Node Id fields for nodes At SortedPos and after will contain the 6556 // count of outstanding operands. 6557 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 6558 SDNode *N = &*I++; 6559 checkForCycles(N, this); 6560 unsigned Degree = N->getNumOperands(); 6561 if (Degree == 0) { 6562 // A node with no uses, add it to the result array immediately. 6563 N->setNodeId(DAGSize++); 6564 allnodes_iterator Q(N); 6565 if (Q != SortedPos) 6566 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 6567 assert(SortedPos != AllNodes.end() && "Overran node list"); 6568 ++SortedPos; 6569 } else { 6570 // Temporarily use the Node Id as scratch space for the degree count. 6571 N->setNodeId(Degree); 6572 } 6573 } 6574 6575 // Visit all the nodes. As we iterate, move nodes into sorted order, 6576 // such that by the time the end is reached all nodes will be sorted. 6577 for (SDNode &Node : allnodes()) { 6578 SDNode *N = &Node; 6579 checkForCycles(N, this); 6580 // N is in sorted position, so all its uses have one less operand 6581 // that needs to be sorted. 6582 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6583 UI != UE; ++UI) { 6584 SDNode *P = *UI; 6585 unsigned Degree = P->getNodeId(); 6586 assert(Degree != 0 && "Invalid node degree"); 6587 --Degree; 6588 if (Degree == 0) { 6589 // All of P's operands are sorted, so P may sorted now. 6590 P->setNodeId(DAGSize++); 6591 if (P->getIterator() != SortedPos) 6592 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 6593 assert(SortedPos != AllNodes.end() && "Overran node list"); 6594 ++SortedPos; 6595 } else { 6596 // Update P's outstanding operand count. 6597 P->setNodeId(Degree); 6598 } 6599 } 6600 if (Node.getIterator() == SortedPos) { 6601 #ifndef NDEBUG 6602 allnodes_iterator I(N); 6603 SDNode *S = &*++I; 6604 dbgs() << "Overran sorted position:\n"; 6605 S->dumprFull(this); dbgs() << "\n"; 6606 dbgs() << "Checking if this is due to cycles\n"; 6607 checkForCycles(this, true); 6608 #endif 6609 llvm_unreachable(nullptr); 6610 } 6611 } 6612 6613 assert(SortedPos == AllNodes.end() && 6614 "Topological sort incomplete!"); 6615 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 6616 "First node in topological sort is not the entry token!"); 6617 assert(AllNodes.front().getNodeId() == 0 && 6618 "First node in topological sort has non-zero id!"); 6619 assert(AllNodes.front().getNumOperands() == 0 && 6620 "First node in topological sort has operands!"); 6621 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 6622 "Last node in topologic sort has unexpected id!"); 6623 assert(AllNodes.back().use_empty() && 6624 "Last node in topologic sort has users!"); 6625 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 6626 return DAGSize; 6627 } 6628 6629 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 6630 /// value is produced by SD. 6631 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) { 6632 if (SD) { 6633 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 6634 SD->setHasDebugValue(true); 6635 } 6636 DbgInfo->add(DB, SD, isParameter); 6637 } 6638 6639 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes. 6640 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) { 6641 if (From == To || !From.getNode()->getHasDebugValue()) 6642 return; 6643 SDNode *FromNode = From.getNode(); 6644 SDNode *ToNode = To.getNode(); 6645 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode); 6646 SmallVector<SDDbgValue *, 2> ClonedDVs; 6647 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end(); 6648 I != E; ++I) { 6649 SDDbgValue *Dbg = *I; 6650 // Only add Dbgvalues attached to same ResNo. 6651 if (Dbg->getKind() == SDDbgValue::SDNODE && 6652 Dbg->getSDNode() == From.getNode() && 6653 Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) { 6654 assert(FromNode != ToNode && 6655 "Should not transfer Debug Values intranode"); 6656 SDDbgValue *Clone = 6657 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode, 6658 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(), 6659 Dbg->getDebugLoc(), Dbg->getOrder()); 6660 ClonedDVs.push_back(Clone); 6661 Dbg->setIsInvalidated(); 6662 } 6663 } 6664 for (SDDbgValue *I : ClonedDVs) 6665 AddDbgValue(I, ToNode, false); 6666 } 6667 6668 //===----------------------------------------------------------------------===// 6669 // SDNode Class 6670 //===----------------------------------------------------------------------===// 6671 6672 bool llvm::isNullConstant(SDValue V) { 6673 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 6674 return Const != nullptr && Const->isNullValue(); 6675 } 6676 6677 bool llvm::isNullFPConstant(SDValue V) { 6678 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 6679 return Const != nullptr && Const->isZero() && !Const->isNegative(); 6680 } 6681 6682 bool llvm::isAllOnesConstant(SDValue V) { 6683 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 6684 return Const != nullptr && Const->isAllOnesValue(); 6685 } 6686 6687 bool llvm::isOneConstant(SDValue V) { 6688 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 6689 return Const != nullptr && Const->isOne(); 6690 } 6691 6692 bool llvm::isBitwiseNot(SDValue V) { 6693 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1)); 6694 } 6695 6696 HandleSDNode::~HandleSDNode() { 6697 DropOperands(); 6698 } 6699 6700 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 6701 const DebugLoc &DL, 6702 const GlobalValue *GA, EVT VT, 6703 int64_t o, unsigned char TF) 6704 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 6705 TheGlobal = GA; 6706 } 6707 6708 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 6709 EVT VT, unsigned SrcAS, 6710 unsigned DestAS) 6711 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 6712 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 6713 6714 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 6715 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 6716 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 6717 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 6718 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 6719 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 6720 6721 // We check here that the size of the memory operand fits within the size of 6722 // the MMO. This is because the MMO might indicate only a possible address 6723 // range instead of specifying the affected memory addresses precisely. 6724 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!"); 6725 } 6726 6727 /// Profile - Gather unique data for the node. 6728 /// 6729 void SDNode::Profile(FoldingSetNodeID &ID) const { 6730 AddNodeIDNode(ID, this); 6731 } 6732 6733 namespace { 6734 struct EVTArray { 6735 std::vector<EVT> VTs; 6736 6737 EVTArray() { 6738 VTs.reserve(MVT::LAST_VALUETYPE); 6739 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 6740 VTs.push_back(MVT((MVT::SimpleValueType)i)); 6741 } 6742 }; 6743 } 6744 6745 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs; 6746 static ManagedStatic<EVTArray> SimpleVTArray; 6747 static ManagedStatic<sys::SmartMutex<true> > VTMutex; 6748 6749 /// getValueTypeList - Return a pointer to the specified value type. 6750 /// 6751 const EVT *SDNode::getValueTypeList(EVT VT) { 6752 if (VT.isExtended()) { 6753 sys::SmartScopedLock<true> Lock(*VTMutex); 6754 return &(*EVTs->insert(VT).first); 6755 } else { 6756 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 6757 "Value type out of range!"); 6758 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 6759 } 6760 } 6761 6762 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 6763 /// indicated value. This method ignores uses of other values defined by this 6764 /// operation. 6765 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 6766 assert(Value < getNumValues() && "Bad value!"); 6767 6768 // TODO: Only iterate over uses of a given value of the node 6769 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 6770 if (UI.getUse().getResNo() == Value) { 6771 if (NUses == 0) 6772 return false; 6773 --NUses; 6774 } 6775 } 6776 6777 // Found exactly the right number of uses? 6778 return NUses == 0; 6779 } 6780 6781 6782 /// hasAnyUseOfValue - Return true if there are any use of the indicated 6783 /// value. This method ignores uses of other values defined by this operation. 6784 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 6785 assert(Value < getNumValues() && "Bad value!"); 6786 6787 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 6788 if (UI.getUse().getResNo() == Value) 6789 return true; 6790 6791 return false; 6792 } 6793 6794 6795 /// isOnlyUserOf - Return true if this node is the only use of N. 6796 /// 6797 bool SDNode::isOnlyUserOf(const SDNode *N) const { 6798 bool Seen = false; 6799 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 6800 SDNode *User = *I; 6801 if (User == this) 6802 Seen = true; 6803 else 6804 return false; 6805 } 6806 6807 return Seen; 6808 } 6809 6810 /// isOperand - Return true if this node is an operand of N. 6811 /// 6812 bool SDValue::isOperandOf(const SDNode *N) const { 6813 for (const SDValue &Op : N->op_values()) 6814 if (*this == Op) 6815 return true; 6816 return false; 6817 } 6818 6819 bool SDNode::isOperandOf(const SDNode *N) const { 6820 for (const SDValue &Op : N->op_values()) 6821 if (this == Op.getNode()) 6822 return true; 6823 return false; 6824 } 6825 6826 /// reachesChainWithoutSideEffects - Return true if this operand (which must 6827 /// be a chain) reaches the specified operand without crossing any 6828 /// side-effecting instructions on any chain path. In practice, this looks 6829 /// through token factors and non-volatile loads. In order to remain efficient, 6830 /// this only looks a couple of nodes in, it does not do an exhaustive search. 6831 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 6832 unsigned Depth) const { 6833 if (*this == Dest) return true; 6834 6835 // Don't search too deeply, we just want to be able to see through 6836 // TokenFactor's etc. 6837 if (Depth == 0) return false; 6838 6839 // If this is a token factor, all inputs to the TF happen in parallel. If any 6840 // of the operands of the TF does not reach dest, then we cannot do the xform. 6841 if (getOpcode() == ISD::TokenFactor) { 6842 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 6843 if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1)) 6844 return false; 6845 return true; 6846 } 6847 6848 // Loads don't have side effects, look through them. 6849 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 6850 if (!Ld->isVolatile()) 6851 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 6852 } 6853 return false; 6854 } 6855 6856 bool SDNode::hasPredecessor(const SDNode *N) const { 6857 SmallPtrSet<const SDNode *, 32> Visited; 6858 SmallVector<const SDNode *, 16> Worklist; 6859 Worklist.push_back(this); 6860 return hasPredecessorHelper(N, Visited, Worklist); 6861 } 6862 6863 uint64_t SDNode::getConstantOperandVal(unsigned Num) const { 6864 assert(Num < NumOperands && "Invalid child # of SDNode!"); 6865 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue(); 6866 } 6867 6868 const SDNodeFlags *SDNode::getFlags() const { 6869 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this)) 6870 return &FlagsNode->Flags; 6871 return nullptr; 6872 } 6873 6874 void SDNode::intersectFlagsWith(const SDNodeFlags *Flags) { 6875 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this)) 6876 FlagsNode->Flags.intersectWith(Flags); 6877 } 6878 6879 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 6880 assert(N->getNumValues() == 1 && 6881 "Can't unroll a vector with multiple results!"); 6882 6883 EVT VT = N->getValueType(0); 6884 unsigned NE = VT.getVectorNumElements(); 6885 EVT EltVT = VT.getVectorElementType(); 6886 SDLoc dl(N); 6887 6888 SmallVector<SDValue, 8> Scalars; 6889 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 6890 6891 // If ResNE is 0, fully unroll the vector op. 6892 if (ResNE == 0) 6893 ResNE = NE; 6894 else if (NE > ResNE) 6895 NE = ResNE; 6896 6897 unsigned i; 6898 for (i= 0; i != NE; ++i) { 6899 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 6900 SDValue Operand = N->getOperand(j); 6901 EVT OperandVT = Operand.getValueType(); 6902 if (OperandVT.isVector()) { 6903 // A vector operand; extract a single element. 6904 EVT OperandEltVT = OperandVT.getVectorElementType(); 6905 Operands[j] = 6906 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand, 6907 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout()))); 6908 } else { 6909 // A scalar operand; just use it as is. 6910 Operands[j] = Operand; 6911 } 6912 } 6913 6914 switch (N->getOpcode()) { 6915 default: { 6916 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 6917 N->getFlags())); 6918 break; 6919 } 6920 case ISD::VSELECT: 6921 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 6922 break; 6923 case ISD::SHL: 6924 case ISD::SRA: 6925 case ISD::SRL: 6926 case ISD::ROTL: 6927 case ISD::ROTR: 6928 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 6929 getShiftAmountOperand(Operands[0].getValueType(), 6930 Operands[1]))); 6931 break; 6932 case ISD::SIGN_EXTEND_INREG: 6933 case ISD::FP_ROUND_INREG: { 6934 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 6935 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 6936 Operands[0], 6937 getValueType(ExtVT))); 6938 } 6939 } 6940 } 6941 6942 for (; i < ResNE; ++i) 6943 Scalars.push_back(getUNDEF(EltVT)); 6944 6945 return getNode(ISD::BUILD_VECTOR, dl, 6946 EVT::getVectorVT(*getContext(), EltVT, ResNE), Scalars); 6947 } 6948 6949 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 6950 LoadSDNode *Base, 6951 unsigned Bytes, 6952 int Dist) const { 6953 if (LD->isVolatile() || Base->isVolatile()) 6954 return false; 6955 if (LD->isIndexed() || Base->isIndexed()) 6956 return false; 6957 if (LD->getChain() != Base->getChain()) 6958 return false; 6959 EVT VT = LD->getValueType(0); 6960 if (VT.getSizeInBits() / 8 != Bytes) 6961 return false; 6962 6963 SDValue Loc = LD->getOperand(1); 6964 SDValue BaseLoc = Base->getOperand(1); 6965 if (Loc.getOpcode() == ISD::FrameIndex) { 6966 if (BaseLoc.getOpcode() != ISD::FrameIndex) 6967 return false; 6968 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 6969 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 6970 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 6971 int FS = MFI.getObjectSize(FI); 6972 int BFS = MFI.getObjectSize(BFI); 6973 if (FS != BFS || FS != (int)Bytes) return false; 6974 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 6975 } 6976 6977 // Handle X + C. 6978 if (isBaseWithConstantOffset(Loc)) { 6979 int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 6980 if (Loc.getOperand(0) == BaseLoc) { 6981 // If the base location is a simple address with no offset itself, then 6982 // the second load's first add operand should be the base address. 6983 if (LocOffset == Dist * (int)Bytes) 6984 return true; 6985 } else if (isBaseWithConstantOffset(BaseLoc)) { 6986 // The base location itself has an offset, so subtract that value from the 6987 // second load's offset before comparing to distance * size. 6988 int64_t BOffset = 6989 cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue(); 6990 if (Loc.getOperand(0) == BaseLoc.getOperand(0)) { 6991 if ((LocOffset - BOffset) == Dist * (int)Bytes) 6992 return true; 6993 } 6994 } 6995 } 6996 const GlobalValue *GV1 = nullptr; 6997 const GlobalValue *GV2 = nullptr; 6998 int64_t Offset1 = 0; 6999 int64_t Offset2 = 0; 7000 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1); 7001 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 7002 if (isGA1 && isGA2 && GV1 == GV2) 7003 return Offset1 == (Offset2 + Dist*Bytes); 7004 return false; 7005 } 7006 7007 7008 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if 7009 /// it cannot be inferred. 7010 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const { 7011 // If this is a GlobalAddress + cst, return the alignment. 7012 const GlobalValue *GV; 7013 int64_t GVOffset = 0; 7014 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 7015 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 7016 APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0); 7017 llvm::computeKnownBits(const_cast<GlobalValue *>(GV), KnownZero, KnownOne, 7018 getDataLayout()); 7019 unsigned AlignBits = KnownZero.countTrailingOnes(); 7020 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0; 7021 if (Align) 7022 return MinAlign(Align, GVOffset); 7023 } 7024 7025 // If this is a direct reference to a stack slot, use information about the 7026 // stack slot's alignment. 7027 int FrameIdx = 1 << 31; 7028 int64_t FrameOffset = 0; 7029 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 7030 FrameIdx = FI->getIndex(); 7031 } else if (isBaseWithConstantOffset(Ptr) && 7032 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 7033 // Handle FI+Cst 7034 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7035 FrameOffset = Ptr.getConstantOperandVal(1); 7036 } 7037 7038 if (FrameIdx != (1 << 31)) { 7039 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 7040 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx), 7041 FrameOffset); 7042 return FIInfoAlign; 7043 } 7044 7045 return 0; 7046 } 7047 7048 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 7049 /// which is split (or expanded) into two not necessarily identical pieces. 7050 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 7051 // Currently all types are split in half. 7052 EVT LoVT, HiVT; 7053 if (!VT.isVector()) { 7054 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 7055 } else { 7056 unsigned NumElements = VT.getVectorNumElements(); 7057 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 7058 LoVT = HiVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 7059 NumElements/2); 7060 } 7061 return std::make_pair(LoVT, HiVT); 7062 } 7063 7064 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 7065 /// low/high part. 7066 std::pair<SDValue, SDValue> 7067 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 7068 const EVT &HiVT) { 7069 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <= 7070 N.getValueType().getVectorNumElements() && 7071 "More vector elements requested than available!"); 7072 SDValue Lo, Hi; 7073 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, 7074 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout()))); 7075 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 7076 getConstant(LoVT.getVectorNumElements(), DL, 7077 TLI->getVectorIdxTy(getDataLayout()))); 7078 return std::make_pair(Lo, Hi); 7079 } 7080 7081 void SelectionDAG::ExtractVectorElements(SDValue Op, 7082 SmallVectorImpl<SDValue> &Args, 7083 unsigned Start, unsigned Count) { 7084 EVT VT = Op.getValueType(); 7085 if (Count == 0) 7086 Count = VT.getVectorNumElements(); 7087 7088 EVT EltVT = VT.getVectorElementType(); 7089 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout()); 7090 SDLoc SL(Op); 7091 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 7092 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 7093 Op, getConstant(i, SL, IdxTy))); 7094 } 7095 } 7096 7097 // getAddressSpace - Return the address space this GlobalAddress belongs to. 7098 unsigned GlobalAddressSDNode::getAddressSpace() const { 7099 return getGlobal()->getType()->getAddressSpace(); 7100 } 7101 7102 7103 Type *ConstantPoolSDNode::getType() const { 7104 if (isMachineConstantPoolEntry()) 7105 return Val.MachineCPVal->getType(); 7106 return Val.ConstVal->getType(); 7107 } 7108 7109 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, 7110 APInt &SplatUndef, 7111 unsigned &SplatBitSize, 7112 bool &HasAnyUndefs, 7113 unsigned MinSplatBits, 7114 bool isBigEndian) const { 7115 EVT VT = getValueType(0); 7116 assert(VT.isVector() && "Expected a vector type"); 7117 unsigned sz = VT.getSizeInBits(); 7118 if (MinSplatBits > sz) 7119 return false; 7120 7121 SplatValue = APInt(sz, 0); 7122 SplatUndef = APInt(sz, 0); 7123 7124 // Get the bits. Bits with undefined values (when the corresponding element 7125 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 7126 // in SplatValue. If any of the values are not constant, give up and return 7127 // false. 7128 unsigned int nOps = getNumOperands(); 7129 assert(nOps > 0 && "isConstantSplat has 0-size build vector"); 7130 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits(); 7131 7132 for (unsigned j = 0; j < nOps; ++j) { 7133 unsigned i = isBigEndian ? nOps-1-j : j; 7134 SDValue OpVal = getOperand(i); 7135 unsigned BitPos = j * EltBitSize; 7136 7137 if (OpVal.isUndef()) 7138 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize); 7139 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) 7140 SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize). 7141 zextOrTrunc(sz) << BitPos; 7142 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 7143 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos; 7144 else 7145 return false; 7146 } 7147 7148 // The build_vector is all constants or undefs. Find the smallest element 7149 // size that splats the vector. 7150 7151 HasAnyUndefs = (SplatUndef != 0); 7152 while (sz > 8) { 7153 7154 unsigned HalfSize = sz / 2; 7155 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 7156 APInt LowValue = SplatValue.trunc(HalfSize); 7157 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 7158 APInt LowUndef = SplatUndef.trunc(HalfSize); 7159 7160 // If the two halves do not match (ignoring undef bits), stop here. 7161 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 7162 MinSplatBits > HalfSize) 7163 break; 7164 7165 SplatValue = HighValue | LowValue; 7166 SplatUndef = HighUndef & LowUndef; 7167 7168 sz = HalfSize; 7169 } 7170 7171 SplatBitSize = sz; 7172 return true; 7173 } 7174 7175 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 7176 if (UndefElements) { 7177 UndefElements->clear(); 7178 UndefElements->resize(getNumOperands()); 7179 } 7180 SDValue Splatted; 7181 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 7182 SDValue Op = getOperand(i); 7183 if (Op.isUndef()) { 7184 if (UndefElements) 7185 (*UndefElements)[i] = true; 7186 } else if (!Splatted) { 7187 Splatted = Op; 7188 } else if (Splatted != Op) { 7189 return SDValue(); 7190 } 7191 } 7192 7193 if (!Splatted) { 7194 assert(getOperand(0).isUndef() && 7195 "Can only have a splat without a constant for all undefs."); 7196 return getOperand(0); 7197 } 7198 7199 return Splatted; 7200 } 7201 7202 ConstantSDNode * 7203 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 7204 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 7205 } 7206 7207 ConstantFPSDNode * 7208 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 7209 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 7210 } 7211 7212 int32_t 7213 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 7214 uint32_t BitWidth) const { 7215 if (ConstantFPSDNode *CN = 7216 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 7217 bool IsExact; 7218 APSInt IntVal(BitWidth); 7219 const APFloat &APF = CN->getValueAPF(); 7220 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 7221 APFloat::opOK || 7222 !IsExact) 7223 return -1; 7224 7225 return IntVal.exactLogBase2(); 7226 } 7227 return -1; 7228 } 7229 7230 bool BuildVectorSDNode::isConstant() const { 7231 for (const SDValue &Op : op_values()) { 7232 unsigned Opc = Op.getOpcode(); 7233 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 7234 return false; 7235 } 7236 return true; 7237 } 7238 7239 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 7240 // Find the first non-undef value in the shuffle mask. 7241 unsigned i, e; 7242 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 7243 /* search */; 7244 7245 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!"); 7246 7247 // Make sure all remaining elements are either undef or the same as the first 7248 // non-undef value. 7249 for (int Idx = Mask[i]; i != e; ++i) 7250 if (Mask[i] >= 0 && Mask[i] != Idx) 7251 return false; 7252 return true; 7253 } 7254 7255 // \brief Returns the SDNode if it is a constant integer BuildVector 7256 // or constant integer. 7257 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) { 7258 if (isa<ConstantSDNode>(N)) 7259 return N.getNode(); 7260 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 7261 return N.getNode(); 7262 // Treat a GlobalAddress supporting constant offset folding as a 7263 // constant integer. 7264 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 7265 if (GA->getOpcode() == ISD::GlobalAddress && 7266 TLI->isOffsetFoldingLegal(GA)) 7267 return GA; 7268 return nullptr; 7269 } 7270 7271 #ifndef NDEBUG 7272 static void checkForCyclesHelper(const SDNode *N, 7273 SmallPtrSetImpl<const SDNode*> &Visited, 7274 SmallPtrSetImpl<const SDNode*> &Checked, 7275 const llvm::SelectionDAG *DAG) { 7276 // If this node has already been checked, don't check it again. 7277 if (Checked.count(N)) 7278 return; 7279 7280 // If a node has already been visited on this depth-first walk, reject it as 7281 // a cycle. 7282 if (!Visited.insert(N).second) { 7283 errs() << "Detected cycle in SelectionDAG\n"; 7284 dbgs() << "Offending node:\n"; 7285 N->dumprFull(DAG); dbgs() << "\n"; 7286 abort(); 7287 } 7288 7289 for (const SDValue &Op : N->op_values()) 7290 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 7291 7292 Checked.insert(N); 7293 Visited.erase(N); 7294 } 7295 #endif 7296 7297 void llvm::checkForCycles(const llvm::SDNode *N, 7298 const llvm::SelectionDAG *DAG, 7299 bool force) { 7300 #ifndef NDEBUG 7301 bool check = force; 7302 #ifdef EXPENSIVE_CHECKS 7303 check = true; 7304 #endif // EXPENSIVE_CHECKS 7305 if (check) { 7306 assert(N && "Checking nonexistent SDNode"); 7307 SmallPtrSet<const SDNode*, 32> visited; 7308 SmallPtrSet<const SDNode*, 32> checked; 7309 checkForCyclesHelper(N, visited, checked, DAG); 7310 } 7311 #endif // !NDEBUG 7312 } 7313 7314 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 7315 checkForCycles(DAG->getRoot().getNode(), DAG, force); 7316 } 7317