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