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