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