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