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