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