1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements the SelectionDAG class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/SelectionDAG.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/APSInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/DenseSet.h" 21 #include "llvm/ADT/FoldingSet.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/Analysis/VectorUtils.h" 30 #include "llvm/BinaryFormat/Dwarf.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/FunctionLoweringInfo.h" 33 #include "llvm/CodeGen/ISDOpcodes.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineConstantPool.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineMemOperand.h" 39 #include "llvm/CodeGen/MachineValueType.h" 40 #include "llvm/CodeGen/RuntimeLibcalls.h" 41 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 42 #include "llvm/CodeGen/SelectionDAGNodes.h" 43 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 44 #include "llvm/CodeGen/TargetFrameLowering.h" 45 #include "llvm/CodeGen/TargetLowering.h" 46 #include "llvm/CodeGen/TargetRegisterInfo.h" 47 #include "llvm/CodeGen/TargetSubtargetInfo.h" 48 #include "llvm/CodeGen/ValueTypes.h" 49 #include "llvm/IR/Constant.h" 50 #include "llvm/IR/ConstantRange.h" 51 #include "llvm/IR/Constants.h" 52 #include "llvm/IR/DataLayout.h" 53 #include "llvm/IR/DebugInfoMetadata.h" 54 #include "llvm/IR/DebugLoc.h" 55 #include "llvm/IR/DerivedTypes.h" 56 #include "llvm/IR/Function.h" 57 #include "llvm/IR/GlobalValue.h" 58 #include "llvm/IR/Metadata.h" 59 #include "llvm/IR/Type.h" 60 #include "llvm/Support/Casting.h" 61 #include "llvm/Support/CodeGen.h" 62 #include "llvm/Support/Compiler.h" 63 #include "llvm/Support/Debug.h" 64 #include "llvm/Support/ErrorHandling.h" 65 #include "llvm/Support/KnownBits.h" 66 #include "llvm/Support/MathExtras.h" 67 #include "llvm/Support/Mutex.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include "llvm/Target/TargetOptions.h" 71 #include "llvm/TargetParser/Triple.h" 72 #include "llvm/Transforms/Utils/SizeOpts.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstdint> 76 #include <cstdlib> 77 #include <limits> 78 #include <set> 79 #include <string> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 85 /// makeVTList - Return an instance of the SDVTList struct initialized with the 86 /// specified members. 87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 88 SDVTList Res = {VTs, NumVTs}; 89 return Res; 90 } 91 92 // Default null implementations of the callbacks. 93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 96 97 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 98 void SelectionDAG::DAGNodeInsertedListener::anchor() {} 99 100 #define DEBUG_TYPE "selectiondag" 101 102 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 103 cl::Hidden, cl::init(true), 104 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 105 106 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 107 cl::desc("Number limit for gluing ld/st of memcpy."), 108 cl::Hidden, cl::init(0)); 109 110 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 111 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 112 } 113 114 //===----------------------------------------------------------------------===// 115 // ConstantFPSDNode Class 116 //===----------------------------------------------------------------------===// 117 118 /// isExactlyValue - We don't rely on operator== working on double values, as 119 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 120 /// As such, this method can be used to do an exact bit-for-bit comparison of 121 /// two floating point values. 122 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 123 return getValueAPF().bitwiseIsEqual(V); 124 } 125 126 bool ConstantFPSDNode::isValueValidForType(EVT VT, 127 const APFloat& Val) { 128 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 129 130 // convert modifies in place, so make a copy. 131 APFloat Val2 = APFloat(Val); 132 bool losesInfo; 133 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 134 APFloat::rmNearestTiesToEven, 135 &losesInfo); 136 return !losesInfo; 137 } 138 139 //===----------------------------------------------------------------------===// 140 // ISD Namespace 141 //===----------------------------------------------------------------------===// 142 143 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 144 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 145 unsigned EltSize = 146 N->getValueType(0).getVectorElementType().getSizeInBits(); 147 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 148 SplatVal = Op0->getAPIntValue().trunc(EltSize); 149 return true; 150 } 151 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 152 SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize); 153 return true; 154 } 155 } 156 157 auto *BV = dyn_cast<BuildVectorSDNode>(N); 158 if (!BV) 159 return false; 160 161 APInt SplatUndef; 162 unsigned SplatBitSize; 163 bool HasUndefs; 164 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 165 // Endianness does not matter here. We are checking for a splat given the 166 // element size of the vector, and if we find such a splat for little endian 167 // layout, then that should be valid also for big endian (as the full vector 168 // size is known to be a multiple of the element size). 169 const bool IsBigEndian = false; 170 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 171 EltSize, IsBigEndian) && 172 EltSize == SplatBitSize; 173 } 174 175 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 176 // specializations of the more general isConstantSplatVector()? 177 178 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 179 // Look through a bit convert. 180 while (N->getOpcode() == ISD::BITCAST) 181 N = N->getOperand(0).getNode(); 182 183 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 184 APInt SplatVal; 185 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 186 } 187 188 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 189 190 unsigned i = 0, e = N->getNumOperands(); 191 192 // Skip over all of the undef values. 193 while (i != e && N->getOperand(i).isUndef()) 194 ++i; 195 196 // Do not accept an all-undef vector. 197 if (i == e) return false; 198 199 // Do not accept build_vectors that aren't all constants or which have non-~0 200 // elements. We have to be a bit careful here, as the type of the constant 201 // may not be the same as the type of the vector elements due to type 202 // legalization (the elements are promoted to a legal type for the target and 203 // a vector of a type may be legal when the base element type is not). 204 // We only want to check enough bits to cover the vector elements, because 205 // we care if the resultant vector is all ones, not whether the individual 206 // constants are. 207 SDValue NotZero = N->getOperand(i); 208 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 209 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 210 if (CN->getAPIntValue().countr_one() < EltSize) 211 return false; 212 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 213 if (CFPN->getValueAPF().bitcastToAPInt().countr_one() < EltSize) 214 return false; 215 } else 216 return false; 217 218 // Okay, we have at least one ~0 value, check to see if the rest match or are 219 // undefs. Even with the above element type twiddling, this should be OK, as 220 // the same type legalization should have applied to all the elements. 221 for (++i; i != e; ++i) 222 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 223 return false; 224 return true; 225 } 226 227 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 228 // Look through a bit convert. 229 while (N->getOpcode() == ISD::BITCAST) 230 N = N->getOperand(0).getNode(); 231 232 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 233 APInt SplatVal; 234 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 235 } 236 237 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 238 239 bool IsAllUndef = true; 240 for (const SDValue &Op : N->op_values()) { 241 if (Op.isUndef()) 242 continue; 243 IsAllUndef = false; 244 // Do not accept build_vectors that aren't all constants or which have non-0 245 // elements. We have to be a bit careful here, as the type of the constant 246 // may not be the same as the type of the vector elements due to type 247 // legalization (the elements are promoted to a legal type for the target 248 // and a vector of a type may be legal when the base element type is not). 249 // We only want to check enough bits to cover the vector elements, because 250 // we care if the resultant vector is all zeros, not whether the individual 251 // constants are. 252 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 253 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 254 if (CN->getAPIntValue().countr_zero() < EltSize) 255 return false; 256 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 257 if (CFPN->getValueAPF().bitcastToAPInt().countr_zero() < EltSize) 258 return false; 259 } else 260 return false; 261 } 262 263 // Do not accept an all-undef vector. 264 if (IsAllUndef) 265 return false; 266 return true; 267 } 268 269 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 270 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 271 } 272 273 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 274 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 275 } 276 277 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 278 if (N->getOpcode() != ISD::BUILD_VECTOR) 279 return false; 280 281 for (const SDValue &Op : N->op_values()) { 282 if (Op.isUndef()) 283 continue; 284 if (!isa<ConstantSDNode>(Op)) 285 return false; 286 } 287 return true; 288 } 289 290 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 291 if (N->getOpcode() != ISD::BUILD_VECTOR) 292 return false; 293 294 for (const SDValue &Op : N->op_values()) { 295 if (Op.isUndef()) 296 continue; 297 if (!isa<ConstantFPSDNode>(Op)) 298 return false; 299 } 300 return true; 301 } 302 303 bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize, 304 bool Signed) { 305 assert(N->getValueType(0).isVector() && "Expected a vector!"); 306 307 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 308 if (EltSize <= NewEltSize) 309 return false; 310 311 if (N->getOpcode() == ISD::ZERO_EXTEND) { 312 return (N->getOperand(0).getValueType().getScalarSizeInBits() <= 313 NewEltSize) && 314 !Signed; 315 } 316 if (N->getOpcode() == ISD::SIGN_EXTEND) { 317 return (N->getOperand(0).getValueType().getScalarSizeInBits() <= 318 NewEltSize) && 319 Signed; 320 } 321 if (N->getOpcode() != ISD::BUILD_VECTOR) 322 return false; 323 324 for (const SDValue &Op : N->op_values()) { 325 if (Op.isUndef()) 326 continue; 327 if (!isa<ConstantSDNode>(Op)) 328 return false; 329 330 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().trunc(EltSize); 331 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C) 332 return false; 333 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C) 334 return false; 335 } 336 337 return true; 338 } 339 340 bool ISD::allOperandsUndef(const SDNode *N) { 341 // Return false if the node has no operands. 342 // This is "logically inconsistent" with the definition of "all" but 343 // is probably the desired behavior. 344 if (N->getNumOperands() == 0) 345 return false; 346 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 347 } 348 349 bool ISD::isFreezeUndef(const SDNode *N) { 350 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef(); 351 } 352 353 template <typename ConstNodeType> 354 bool ISD::matchUnaryPredicateImpl(SDValue Op, 355 std::function<bool(ConstNodeType *)> Match, 356 bool AllowUndefs) { 357 // FIXME: Add support for scalar UNDEF cases? 358 if (auto *C = dyn_cast<ConstNodeType>(Op)) 359 return Match(C); 360 361 // FIXME: Add support for vector UNDEF cases? 362 if (ISD::BUILD_VECTOR != Op.getOpcode() && 363 ISD::SPLAT_VECTOR != Op.getOpcode()) 364 return false; 365 366 EVT SVT = Op.getValueType().getScalarType(); 367 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 368 if (AllowUndefs && Op.getOperand(i).isUndef()) { 369 if (!Match(nullptr)) 370 return false; 371 continue; 372 } 373 374 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i)); 375 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 376 return false; 377 } 378 return true; 379 } 380 // Build used template types. 381 template bool ISD::matchUnaryPredicateImpl<ConstantSDNode>( 382 SDValue, std::function<bool(ConstantSDNode *)>, bool); 383 template bool ISD::matchUnaryPredicateImpl<ConstantFPSDNode>( 384 SDValue, std::function<bool(ConstantFPSDNode *)>, bool); 385 386 bool ISD::matchBinaryPredicate( 387 SDValue LHS, SDValue RHS, 388 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 389 bool AllowUndefs, bool AllowTypeMismatch) { 390 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 391 return false; 392 393 // TODO: Add support for scalar UNDEF cases? 394 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 395 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 396 return Match(LHSCst, RHSCst); 397 398 // TODO: Add support for vector UNDEF cases? 399 if (LHS.getOpcode() != RHS.getOpcode() || 400 (LHS.getOpcode() != ISD::BUILD_VECTOR && 401 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 402 return false; 403 404 EVT SVT = LHS.getValueType().getScalarType(); 405 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 406 SDValue LHSOp = LHS.getOperand(i); 407 SDValue RHSOp = RHS.getOperand(i); 408 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 409 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 410 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 411 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 412 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 413 return false; 414 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 415 LHSOp.getValueType() != RHSOp.getValueType())) 416 return false; 417 if (!Match(LHSCst, RHSCst)) 418 return false; 419 } 420 return true; 421 } 422 423 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 424 switch (VecReduceOpcode) { 425 default: 426 llvm_unreachable("Expected VECREDUCE opcode"); 427 case ISD::VECREDUCE_FADD: 428 case ISD::VECREDUCE_SEQ_FADD: 429 case ISD::VP_REDUCE_FADD: 430 case ISD::VP_REDUCE_SEQ_FADD: 431 return ISD::FADD; 432 case ISD::VECREDUCE_FMUL: 433 case ISD::VECREDUCE_SEQ_FMUL: 434 case ISD::VP_REDUCE_FMUL: 435 case ISD::VP_REDUCE_SEQ_FMUL: 436 return ISD::FMUL; 437 case ISD::VECREDUCE_ADD: 438 case ISD::VP_REDUCE_ADD: 439 return ISD::ADD; 440 case ISD::VECREDUCE_MUL: 441 case ISD::VP_REDUCE_MUL: 442 return ISD::MUL; 443 case ISD::VECREDUCE_AND: 444 case ISD::VP_REDUCE_AND: 445 return ISD::AND; 446 case ISD::VECREDUCE_OR: 447 case ISD::VP_REDUCE_OR: 448 return ISD::OR; 449 case ISD::VECREDUCE_XOR: 450 case ISD::VP_REDUCE_XOR: 451 return ISD::XOR; 452 case ISD::VECREDUCE_SMAX: 453 case ISD::VP_REDUCE_SMAX: 454 return ISD::SMAX; 455 case ISD::VECREDUCE_SMIN: 456 case ISD::VP_REDUCE_SMIN: 457 return ISD::SMIN; 458 case ISD::VECREDUCE_UMAX: 459 case ISD::VP_REDUCE_UMAX: 460 return ISD::UMAX; 461 case ISD::VECREDUCE_UMIN: 462 case ISD::VP_REDUCE_UMIN: 463 return ISD::UMIN; 464 case ISD::VECREDUCE_FMAX: 465 case ISD::VP_REDUCE_FMAX: 466 return ISD::FMAXNUM; 467 case ISD::VECREDUCE_FMIN: 468 case ISD::VP_REDUCE_FMIN: 469 return ISD::FMINNUM; 470 case ISD::VECREDUCE_FMAXIMUM: 471 return ISD::FMAXIMUM; 472 case ISD::VECREDUCE_FMINIMUM: 473 return ISD::FMINIMUM; 474 } 475 } 476 477 bool ISD::isVPOpcode(unsigned Opcode) { 478 switch (Opcode) { 479 default: 480 return false; 481 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 482 case ISD::VPSD: \ 483 return true; 484 #include "llvm/IR/VPIntrinsics.def" 485 } 486 } 487 488 bool ISD::isVPBinaryOp(unsigned Opcode) { 489 switch (Opcode) { 490 default: 491 break; 492 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 493 #define VP_PROPERTY_BINARYOP return true; 494 #define END_REGISTER_VP_SDNODE(VPSD) break; 495 #include "llvm/IR/VPIntrinsics.def" 496 } 497 return false; 498 } 499 500 bool ISD::isVPReduction(unsigned Opcode) { 501 switch (Opcode) { 502 default: 503 break; 504 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 505 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 506 #define END_REGISTER_VP_SDNODE(VPSD) break; 507 #include "llvm/IR/VPIntrinsics.def" 508 } 509 return false; 510 } 511 512 /// The operand position of the vector mask. 513 std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 514 switch (Opcode) { 515 default: 516 return std::nullopt; 517 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 518 case ISD::VPSD: \ 519 return MASKPOS; 520 #include "llvm/IR/VPIntrinsics.def" 521 } 522 } 523 524 /// The operand position of the explicit vector length parameter. 525 std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 526 switch (Opcode) { 527 default: 528 return std::nullopt; 529 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 530 case ISD::VPSD: \ 531 return EVLPOS; 532 #include "llvm/IR/VPIntrinsics.def" 533 } 534 } 535 536 std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode, 537 bool hasFPExcept) { 538 // FIXME: Return strict opcodes in case of fp exceptions. 539 switch (VPOpcode) { 540 default: 541 return std::nullopt; 542 #define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC: 543 #define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC; 544 #define END_REGISTER_VP_SDNODE(VPOPC) break; 545 #include "llvm/IR/VPIntrinsics.def" 546 } 547 return std::nullopt; 548 } 549 550 unsigned ISD::getVPForBaseOpcode(unsigned Opcode) { 551 switch (Opcode) { 552 default: 553 llvm_unreachable("can not translate this Opcode to VP."); 554 #define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break; 555 #define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC: 556 #define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC; 557 #include "llvm/IR/VPIntrinsics.def" 558 } 559 } 560 561 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 562 switch (ExtType) { 563 case ISD::EXTLOAD: 564 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 565 case ISD::SEXTLOAD: 566 return ISD::SIGN_EXTEND; 567 case ISD::ZEXTLOAD: 568 return ISD::ZERO_EXTEND; 569 default: 570 break; 571 } 572 573 llvm_unreachable("Invalid LoadExtType"); 574 } 575 576 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 577 // To perform this operation, we just need to swap the L and G bits of the 578 // operation. 579 unsigned OldL = (Operation >> 2) & 1; 580 unsigned OldG = (Operation >> 1) & 1; 581 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 582 (OldL << 1) | // New G bit 583 (OldG << 2)); // New L bit. 584 } 585 586 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 587 unsigned Operation = Op; 588 if (isIntegerLike) 589 Operation ^= 7; // Flip L, G, E bits, but not U. 590 else 591 Operation ^= 15; // Flip all of the condition bits. 592 593 if (Operation > ISD::SETTRUE2) 594 Operation &= ~8; // Don't let N and U bits get set. 595 596 return ISD::CondCode(Operation); 597 } 598 599 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 600 return getSetCCInverseImpl(Op, Type.isInteger()); 601 } 602 603 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 604 bool isIntegerLike) { 605 return getSetCCInverseImpl(Op, isIntegerLike); 606 } 607 608 /// For an integer comparison, return 1 if the comparison is a signed operation 609 /// and 2 if the result is an unsigned comparison. Return zero if the operation 610 /// does not depend on the sign of the input (setne and seteq). 611 static int isSignedOp(ISD::CondCode Opcode) { 612 switch (Opcode) { 613 default: llvm_unreachable("Illegal integer setcc operation!"); 614 case ISD::SETEQ: 615 case ISD::SETNE: return 0; 616 case ISD::SETLT: 617 case ISD::SETLE: 618 case ISD::SETGT: 619 case ISD::SETGE: return 1; 620 case ISD::SETULT: 621 case ISD::SETULE: 622 case ISD::SETUGT: 623 case ISD::SETUGE: return 2; 624 } 625 } 626 627 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 628 EVT Type) { 629 bool IsInteger = Type.isInteger(); 630 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 631 // Cannot fold a signed integer setcc with an unsigned integer setcc. 632 return ISD::SETCC_INVALID; 633 634 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 635 636 // If the N and U bits get set, then the resultant comparison DOES suddenly 637 // care about orderedness, and it is true when ordered. 638 if (Op > ISD::SETTRUE2) 639 Op &= ~16; // Clear the U bit if the N bit is set. 640 641 // Canonicalize illegal integer setcc's. 642 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 643 Op = ISD::SETNE; 644 645 return ISD::CondCode(Op); 646 } 647 648 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 649 EVT Type) { 650 bool IsInteger = Type.isInteger(); 651 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 652 // Cannot fold a signed setcc with an unsigned setcc. 653 return ISD::SETCC_INVALID; 654 655 // Combine all of the condition bits. 656 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 657 658 // Canonicalize illegal integer setcc's. 659 if (IsInteger) { 660 switch (Result) { 661 default: break; 662 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 663 case ISD::SETOEQ: // SETEQ & SETU[LG]E 664 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 665 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 666 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 667 } 668 } 669 670 return Result; 671 } 672 673 //===----------------------------------------------------------------------===// 674 // SDNode Profile Support 675 //===----------------------------------------------------------------------===// 676 677 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 678 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 679 ID.AddInteger(OpC); 680 } 681 682 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 683 /// solely with their pointer. 684 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 685 ID.AddPointer(VTList.VTs); 686 } 687 688 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 689 static void AddNodeIDOperands(FoldingSetNodeID &ID, 690 ArrayRef<SDValue> Ops) { 691 for (const auto &Op : Ops) { 692 ID.AddPointer(Op.getNode()); 693 ID.AddInteger(Op.getResNo()); 694 } 695 } 696 697 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 698 static void AddNodeIDOperands(FoldingSetNodeID &ID, 699 ArrayRef<SDUse> Ops) { 700 for (const auto &Op : Ops) { 701 ID.AddPointer(Op.getNode()); 702 ID.AddInteger(Op.getResNo()); 703 } 704 } 705 706 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC, 707 SDVTList VTList, ArrayRef<SDValue> OpList) { 708 AddNodeIDOpcode(ID, OpC); 709 AddNodeIDValueTypes(ID, VTList); 710 AddNodeIDOperands(ID, OpList); 711 } 712 713 /// If this is an SDNode with special info, add this info to the NodeID data. 714 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 715 switch (N->getOpcode()) { 716 case ISD::TargetExternalSymbol: 717 case ISD::ExternalSymbol: 718 case ISD::MCSymbol: 719 llvm_unreachable("Should only be used on nodes with operands"); 720 default: break; // Normal nodes don't need extra info. 721 case ISD::TargetConstant: 722 case ISD::Constant: { 723 const ConstantSDNode *C = cast<ConstantSDNode>(N); 724 ID.AddPointer(C->getConstantIntValue()); 725 ID.AddBoolean(C->isOpaque()); 726 break; 727 } 728 case ISD::TargetConstantFP: 729 case ISD::ConstantFP: 730 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 731 break; 732 case ISD::TargetGlobalAddress: 733 case ISD::GlobalAddress: 734 case ISD::TargetGlobalTLSAddress: 735 case ISD::GlobalTLSAddress: { 736 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 737 ID.AddPointer(GA->getGlobal()); 738 ID.AddInteger(GA->getOffset()); 739 ID.AddInteger(GA->getTargetFlags()); 740 break; 741 } 742 case ISD::BasicBlock: 743 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 744 break; 745 case ISD::Register: 746 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 747 break; 748 case ISD::RegisterMask: 749 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 750 break; 751 case ISD::SRCVALUE: 752 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 753 break; 754 case ISD::FrameIndex: 755 case ISD::TargetFrameIndex: 756 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 757 break; 758 case ISD::LIFETIME_START: 759 case ISD::LIFETIME_END: 760 if (cast<LifetimeSDNode>(N)->hasOffset()) { 761 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 762 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 763 } 764 break; 765 case ISD::PSEUDO_PROBE: 766 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 767 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 768 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 769 break; 770 case ISD::JumpTable: 771 case ISD::TargetJumpTable: 772 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 773 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 774 break; 775 case ISD::ConstantPool: 776 case ISD::TargetConstantPool: { 777 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 778 ID.AddInteger(CP->getAlign().value()); 779 ID.AddInteger(CP->getOffset()); 780 if (CP->isMachineConstantPoolEntry()) 781 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 782 else 783 ID.AddPointer(CP->getConstVal()); 784 ID.AddInteger(CP->getTargetFlags()); 785 break; 786 } 787 case ISD::TargetIndex: { 788 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 789 ID.AddInteger(TI->getIndex()); 790 ID.AddInteger(TI->getOffset()); 791 ID.AddInteger(TI->getTargetFlags()); 792 break; 793 } 794 case ISD::LOAD: { 795 const LoadSDNode *LD = cast<LoadSDNode>(N); 796 ID.AddInteger(LD->getMemoryVT().getRawBits()); 797 ID.AddInteger(LD->getRawSubclassData()); 798 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 799 ID.AddInteger(LD->getMemOperand()->getFlags()); 800 break; 801 } 802 case ISD::STORE: { 803 const StoreSDNode *ST = cast<StoreSDNode>(N); 804 ID.AddInteger(ST->getMemoryVT().getRawBits()); 805 ID.AddInteger(ST->getRawSubclassData()); 806 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 807 ID.AddInteger(ST->getMemOperand()->getFlags()); 808 break; 809 } 810 case ISD::VP_LOAD: { 811 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 812 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 813 ID.AddInteger(ELD->getRawSubclassData()); 814 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 815 ID.AddInteger(ELD->getMemOperand()->getFlags()); 816 break; 817 } 818 case ISD::VP_STORE: { 819 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 820 ID.AddInteger(EST->getMemoryVT().getRawBits()); 821 ID.AddInteger(EST->getRawSubclassData()); 822 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 823 ID.AddInteger(EST->getMemOperand()->getFlags()); 824 break; 825 } 826 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: { 827 const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N); 828 ID.AddInteger(SLD->getMemoryVT().getRawBits()); 829 ID.AddInteger(SLD->getRawSubclassData()); 830 ID.AddInteger(SLD->getPointerInfo().getAddrSpace()); 831 break; 832 } 833 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: { 834 const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N); 835 ID.AddInteger(SST->getMemoryVT().getRawBits()); 836 ID.AddInteger(SST->getRawSubclassData()); 837 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 838 break; 839 } 840 case ISD::VP_GATHER: { 841 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 842 ID.AddInteger(EG->getMemoryVT().getRawBits()); 843 ID.AddInteger(EG->getRawSubclassData()); 844 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 845 ID.AddInteger(EG->getMemOperand()->getFlags()); 846 break; 847 } 848 case ISD::VP_SCATTER: { 849 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 850 ID.AddInteger(ES->getMemoryVT().getRawBits()); 851 ID.AddInteger(ES->getRawSubclassData()); 852 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 853 ID.AddInteger(ES->getMemOperand()->getFlags()); 854 break; 855 } 856 case ISD::MLOAD: { 857 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 858 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 859 ID.AddInteger(MLD->getRawSubclassData()); 860 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 861 ID.AddInteger(MLD->getMemOperand()->getFlags()); 862 break; 863 } 864 case ISD::MSTORE: { 865 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 866 ID.AddInteger(MST->getMemoryVT().getRawBits()); 867 ID.AddInteger(MST->getRawSubclassData()); 868 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 869 ID.AddInteger(MST->getMemOperand()->getFlags()); 870 break; 871 } 872 case ISD::MGATHER: { 873 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 874 ID.AddInteger(MG->getMemoryVT().getRawBits()); 875 ID.AddInteger(MG->getRawSubclassData()); 876 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 877 ID.AddInteger(MG->getMemOperand()->getFlags()); 878 break; 879 } 880 case ISD::MSCATTER: { 881 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 882 ID.AddInteger(MS->getMemoryVT().getRawBits()); 883 ID.AddInteger(MS->getRawSubclassData()); 884 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 885 ID.AddInteger(MS->getMemOperand()->getFlags()); 886 break; 887 } 888 case ISD::ATOMIC_CMP_SWAP: 889 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 890 case ISD::ATOMIC_SWAP: 891 case ISD::ATOMIC_LOAD_ADD: 892 case ISD::ATOMIC_LOAD_SUB: 893 case ISD::ATOMIC_LOAD_AND: 894 case ISD::ATOMIC_LOAD_CLR: 895 case ISD::ATOMIC_LOAD_OR: 896 case ISD::ATOMIC_LOAD_XOR: 897 case ISD::ATOMIC_LOAD_NAND: 898 case ISD::ATOMIC_LOAD_MIN: 899 case ISD::ATOMIC_LOAD_MAX: 900 case ISD::ATOMIC_LOAD_UMIN: 901 case ISD::ATOMIC_LOAD_UMAX: 902 case ISD::ATOMIC_LOAD: 903 case ISD::ATOMIC_STORE: { 904 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 905 ID.AddInteger(AT->getMemoryVT().getRawBits()); 906 ID.AddInteger(AT->getRawSubclassData()); 907 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 908 ID.AddInteger(AT->getMemOperand()->getFlags()); 909 break; 910 } 911 case ISD::VECTOR_SHUFFLE: { 912 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 913 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 914 i != e; ++i) 915 ID.AddInteger(SVN->getMaskElt(i)); 916 break; 917 } 918 case ISD::TargetBlockAddress: 919 case ISD::BlockAddress: { 920 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 921 ID.AddPointer(BA->getBlockAddress()); 922 ID.AddInteger(BA->getOffset()); 923 ID.AddInteger(BA->getTargetFlags()); 924 break; 925 } 926 case ISD::AssertAlign: 927 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value()); 928 break; 929 case ISD::PREFETCH: 930 case ISD::INTRINSIC_VOID: 931 case ISD::INTRINSIC_W_CHAIN: 932 // Handled by MemIntrinsicSDNode check after the switch. 933 break; 934 } // end switch (N->getOpcode()) 935 936 // MemIntrinsic nodes could also have subclass data, address spaces, and flags 937 // to check. 938 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) { 939 ID.AddInteger(MN->getRawSubclassData()); 940 ID.AddInteger(MN->getPointerInfo().getAddrSpace()); 941 ID.AddInteger(MN->getMemOperand()->getFlags()); 942 ID.AddInteger(MN->getMemoryVT().getRawBits()); 943 } 944 } 945 946 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 947 /// data. 948 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 949 AddNodeIDOpcode(ID, N->getOpcode()); 950 // Add the return value info. 951 AddNodeIDValueTypes(ID, N->getVTList()); 952 // Add the operand info. 953 AddNodeIDOperands(ID, N->ops()); 954 955 // Handle SDNode leafs with special info. 956 AddNodeIDCustom(ID, N); 957 } 958 959 //===----------------------------------------------------------------------===// 960 // SelectionDAG Class 961 //===----------------------------------------------------------------------===// 962 963 /// doNotCSE - Return true if CSE should not be performed for this node. 964 static bool doNotCSE(SDNode *N) { 965 if (N->getValueType(0) == MVT::Glue) 966 return true; // Never CSE anything that produces a glue result. 967 968 switch (N->getOpcode()) { 969 default: break; 970 case ISD::HANDLENODE: 971 case ISD::EH_LABEL: 972 return true; // Never CSE these nodes. 973 } 974 975 // Check that remaining values produced are not flags. 976 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 977 if (N->getValueType(i) == MVT::Glue) 978 return true; // Never CSE anything that produces a glue result. 979 980 return false; 981 } 982 983 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 984 /// SelectionDAG. 985 void SelectionDAG::RemoveDeadNodes() { 986 // Create a dummy node (which is not added to allnodes), that adds a reference 987 // to the root node, preventing it from being deleted. 988 HandleSDNode Dummy(getRoot()); 989 990 SmallVector<SDNode*, 128> DeadNodes; 991 992 // Add all obviously-dead nodes to the DeadNodes worklist. 993 for (SDNode &Node : allnodes()) 994 if (Node.use_empty()) 995 DeadNodes.push_back(&Node); 996 997 RemoveDeadNodes(DeadNodes); 998 999 // If the root changed (e.g. it was a dead load, update the root). 1000 setRoot(Dummy.getValue()); 1001 } 1002 1003 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 1004 /// given list, and any nodes that become unreachable as a result. 1005 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 1006 1007 // Process the worklist, deleting the nodes and adding their uses to the 1008 // worklist. 1009 while (!DeadNodes.empty()) { 1010 SDNode *N = DeadNodes.pop_back_val(); 1011 // Skip to next node if we've already managed to delete the node. This could 1012 // happen if replacing a node causes a node previously added to the node to 1013 // be deleted. 1014 if (N->getOpcode() == ISD::DELETED_NODE) 1015 continue; 1016 1017 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1018 DUL->NodeDeleted(N, nullptr); 1019 1020 // Take the node out of the appropriate CSE map. 1021 RemoveNodeFromCSEMaps(N); 1022 1023 // Next, brutally remove the operand list. This is safe to do, as there are 1024 // no cycles in the graph. 1025 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 1026 SDUse &Use = *I++; 1027 SDNode *Operand = Use.getNode(); 1028 Use.set(SDValue()); 1029 1030 // Now that we removed this operand, see if there are no uses of it left. 1031 if (Operand->use_empty()) 1032 DeadNodes.push_back(Operand); 1033 } 1034 1035 DeallocateNode(N); 1036 } 1037 } 1038 1039 void SelectionDAG::RemoveDeadNode(SDNode *N){ 1040 SmallVector<SDNode*, 16> DeadNodes(1, N); 1041 1042 // Create a dummy node that adds a reference to the root node, preventing 1043 // it from being deleted. (This matters if the root is an operand of the 1044 // dead node.) 1045 HandleSDNode Dummy(getRoot()); 1046 1047 RemoveDeadNodes(DeadNodes); 1048 } 1049 1050 void SelectionDAG::DeleteNode(SDNode *N) { 1051 // First take this out of the appropriate CSE map. 1052 RemoveNodeFromCSEMaps(N); 1053 1054 // Finally, remove uses due to operands of this node, remove from the 1055 // AllNodes list, and delete the node. 1056 DeleteNodeNotInCSEMaps(N); 1057 } 1058 1059 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 1060 assert(N->getIterator() != AllNodes.begin() && 1061 "Cannot delete the entry node!"); 1062 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 1063 1064 // Drop all of the operands and decrement used node's use counts. 1065 N->DropOperands(); 1066 1067 DeallocateNode(N); 1068 } 1069 1070 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 1071 assert(!(V->isVariadic() && isParameter)); 1072 if (isParameter) 1073 ByvalParmDbgValues.push_back(V); 1074 else 1075 DbgValues.push_back(V); 1076 for (const SDNode *Node : V->getSDNodes()) 1077 if (Node) 1078 DbgValMap[Node].push_back(V); 1079 } 1080 1081 void SDDbgInfo::erase(const SDNode *Node) { 1082 DbgValMapType::iterator I = DbgValMap.find(Node); 1083 if (I == DbgValMap.end()) 1084 return; 1085 for (auto &Val: I->second) 1086 Val->setIsInvalidated(); 1087 DbgValMap.erase(I); 1088 } 1089 1090 void SelectionDAG::DeallocateNode(SDNode *N) { 1091 // If we have operands, deallocate them. 1092 removeOperands(N); 1093 1094 NodeAllocator.Deallocate(AllNodes.remove(N)); 1095 1096 // Set the opcode to DELETED_NODE to help catch bugs when node 1097 // memory is reallocated. 1098 // FIXME: There are places in SDag that have grown a dependency on the opcode 1099 // value in the released node. 1100 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 1101 N->NodeType = ISD::DELETED_NODE; 1102 1103 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 1104 // them and forget about that node. 1105 DbgInfo->erase(N); 1106 1107 // Invalidate extra info. 1108 SDEI.erase(N); 1109 } 1110 1111 #ifndef NDEBUG 1112 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 1113 static void VerifySDNode(SDNode *N) { 1114 switch (N->getOpcode()) { 1115 default: 1116 break; 1117 case ISD::BUILD_PAIR: { 1118 EVT VT = N->getValueType(0); 1119 assert(N->getNumValues() == 1 && "Too many results!"); 1120 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1121 "Wrong return type!"); 1122 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1123 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1124 "Mismatched operand types!"); 1125 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1126 "Wrong operand type!"); 1127 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1128 "Wrong return type size"); 1129 break; 1130 } 1131 case ISD::BUILD_VECTOR: { 1132 assert(N->getNumValues() == 1 && "Too many results!"); 1133 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1134 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1135 "Wrong number of operands!"); 1136 EVT EltVT = N->getValueType(0).getVectorElementType(); 1137 for (const SDUse &Op : N->ops()) { 1138 assert((Op.getValueType() == EltVT || 1139 (EltVT.isInteger() && Op.getValueType().isInteger() && 1140 EltVT.bitsLE(Op.getValueType()))) && 1141 "Wrong operand type!"); 1142 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1143 "Operands must all have the same type"); 1144 } 1145 break; 1146 } 1147 } 1148 } 1149 #endif // NDEBUG 1150 1151 /// Insert a newly allocated node into the DAG. 1152 /// 1153 /// Handles insertion into the all nodes list and CSE map, as well as 1154 /// verification and other common operations when a new node is allocated. 1155 void SelectionDAG::InsertNode(SDNode *N) { 1156 AllNodes.push_back(N); 1157 #ifndef NDEBUG 1158 N->PersistentId = NextPersistentId++; 1159 VerifySDNode(N); 1160 #endif 1161 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1162 DUL->NodeInserted(N); 1163 } 1164 1165 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1166 /// correspond to it. This is useful when we're about to delete or repurpose 1167 /// the node. We don't want future request for structurally identical nodes 1168 /// to return N anymore. 1169 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1170 bool Erased = false; 1171 switch (N->getOpcode()) { 1172 case ISD::HANDLENODE: return false; // noop. 1173 case ISD::CONDCODE: 1174 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1175 "Cond code doesn't exist!"); 1176 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1177 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1178 break; 1179 case ISD::ExternalSymbol: 1180 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1181 break; 1182 case ISD::TargetExternalSymbol: { 1183 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1184 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1185 ESN->getSymbol(), ESN->getTargetFlags())); 1186 break; 1187 } 1188 case ISD::MCSymbol: { 1189 auto *MCSN = cast<MCSymbolSDNode>(N); 1190 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1191 break; 1192 } 1193 case ISD::VALUETYPE: { 1194 EVT VT = cast<VTSDNode>(N)->getVT(); 1195 if (VT.isExtended()) { 1196 Erased = ExtendedValueTypeNodes.erase(VT); 1197 } else { 1198 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1199 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1200 } 1201 break; 1202 } 1203 default: 1204 // Remove it from the CSE Map. 1205 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1206 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1207 Erased = CSEMap.RemoveNode(N); 1208 break; 1209 } 1210 #ifndef NDEBUG 1211 // Verify that the node was actually in one of the CSE maps, unless it has a 1212 // glue result (which cannot be CSE'd) or is one of the special cases that are 1213 // not subject to CSE. 1214 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1215 !N->isMachineOpcode() && !doNotCSE(N)) { 1216 N->dump(this); 1217 dbgs() << "\n"; 1218 llvm_unreachable("Node is not in map!"); 1219 } 1220 #endif 1221 return Erased; 1222 } 1223 1224 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1225 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1226 /// node already exists, in which case transfer all its users to the existing 1227 /// node. This transfer can potentially trigger recursive merging. 1228 void 1229 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1230 // For node types that aren't CSE'd, just act as if no identical node 1231 // already exists. 1232 if (!doNotCSE(N)) { 1233 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1234 if (Existing != N) { 1235 // If there was already an existing matching node, use ReplaceAllUsesWith 1236 // to replace the dead one with the existing one. This can cause 1237 // recursive merging of other unrelated nodes down the line. 1238 ReplaceAllUsesWith(N, Existing); 1239 1240 // N is now dead. Inform the listeners and delete it. 1241 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1242 DUL->NodeDeleted(N, Existing); 1243 DeleteNodeNotInCSEMaps(N); 1244 return; 1245 } 1246 } 1247 1248 // If the node doesn't already exist, we updated it. Inform listeners. 1249 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1250 DUL->NodeUpdated(N); 1251 } 1252 1253 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1254 /// were replaced with those specified. If this node is never memoized, 1255 /// return null, otherwise return a pointer to the slot it would take. If a 1256 /// node already exists with these operands, the slot will be non-null. 1257 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1258 void *&InsertPos) { 1259 if (doNotCSE(N)) 1260 return nullptr; 1261 1262 SDValue Ops[] = { Op }; 1263 FoldingSetNodeID ID; 1264 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1265 AddNodeIDCustom(ID, N); 1266 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1267 if (Node) 1268 Node->intersectFlagsWith(N->getFlags()); 1269 return Node; 1270 } 1271 1272 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1273 /// were replaced with those specified. If this node is never memoized, 1274 /// return null, otherwise return a pointer to the slot it would take. If a 1275 /// node already exists with these operands, the slot will be non-null. 1276 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1277 SDValue Op1, SDValue Op2, 1278 void *&InsertPos) { 1279 if (doNotCSE(N)) 1280 return nullptr; 1281 1282 SDValue Ops[] = { Op1, Op2 }; 1283 FoldingSetNodeID ID; 1284 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1285 AddNodeIDCustom(ID, N); 1286 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1287 if (Node) 1288 Node->intersectFlagsWith(N->getFlags()); 1289 return Node; 1290 } 1291 1292 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1293 /// were replaced with those specified. If this node is never memoized, 1294 /// return null, otherwise return a pointer to the slot it would take. If a 1295 /// node already exists with these operands, the slot will be non-null. 1296 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1297 void *&InsertPos) { 1298 if (doNotCSE(N)) 1299 return nullptr; 1300 1301 FoldingSetNodeID ID; 1302 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1303 AddNodeIDCustom(ID, N); 1304 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1305 if (Node) 1306 Node->intersectFlagsWith(N->getFlags()); 1307 return Node; 1308 } 1309 1310 Align SelectionDAG::getEVTAlign(EVT VT) const { 1311 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0) 1312 : VT.getTypeForEVT(*getContext()); 1313 1314 return getDataLayout().getABITypeAlign(Ty); 1315 } 1316 1317 // EntryNode could meaningfully have debug info if we can find it... 1318 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOptLevel OL) 1319 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(), 1320 getVTList(MVT::Other, MVT::Glue)), 1321 Root(getEntryNode()) { 1322 InsertNode(&EntryNode); 1323 DbgInfo = new SDDbgInfo(); 1324 } 1325 1326 void SelectionDAG::init(MachineFunction &NewMF, 1327 OptimizationRemarkEmitter &NewORE, Pass *PassPtr, 1328 const TargetLibraryInfo *LibraryInfo, 1329 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin, 1330 BlockFrequencyInfo *BFIin, 1331 FunctionVarLocs const *VarLocs) { 1332 MF = &NewMF; 1333 SDAGISelPass = PassPtr; 1334 ORE = &NewORE; 1335 TLI = getSubtarget().getTargetLowering(); 1336 TSI = getSubtarget().getSelectionDAGInfo(); 1337 LibInfo = LibraryInfo; 1338 Context = &MF->getFunction().getContext(); 1339 UA = NewUA; 1340 PSI = PSIin; 1341 BFI = BFIin; 1342 FnVarLocs = VarLocs; 1343 } 1344 1345 SelectionDAG::~SelectionDAG() { 1346 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1347 allnodes_clear(); 1348 OperandRecycler.clear(OperandAllocator); 1349 delete DbgInfo; 1350 } 1351 1352 bool SelectionDAG::shouldOptForSize() const { 1353 return MF->getFunction().hasOptSize() || 1354 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1355 } 1356 1357 void SelectionDAG::allnodes_clear() { 1358 assert(&*AllNodes.begin() == &EntryNode); 1359 AllNodes.remove(AllNodes.begin()); 1360 while (!AllNodes.empty()) 1361 DeallocateNode(&AllNodes.front()); 1362 #ifndef NDEBUG 1363 NextPersistentId = 0; 1364 #endif 1365 } 1366 1367 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1368 void *&InsertPos) { 1369 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1370 if (N) { 1371 switch (N->getOpcode()) { 1372 default: break; 1373 case ISD::Constant: 1374 case ISD::ConstantFP: 1375 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1376 "debug location. Use another overload."); 1377 } 1378 } 1379 return N; 1380 } 1381 1382 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1383 const SDLoc &DL, void *&InsertPos) { 1384 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1385 if (N) { 1386 switch (N->getOpcode()) { 1387 case ISD::Constant: 1388 case ISD::ConstantFP: 1389 // Erase debug location from the node if the node is used at several 1390 // different places. Do not propagate one location to all uses as it 1391 // will cause a worse single stepping debugging experience. 1392 if (N->getDebugLoc() != DL.getDebugLoc()) 1393 N->setDebugLoc(DebugLoc()); 1394 break; 1395 default: 1396 // When the node's point of use is located earlier in the instruction 1397 // sequence than its prior point of use, update its debug info to the 1398 // earlier location. 1399 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1400 N->setDebugLoc(DL.getDebugLoc()); 1401 break; 1402 } 1403 } 1404 return N; 1405 } 1406 1407 void SelectionDAG::clear() { 1408 allnodes_clear(); 1409 OperandRecycler.clear(OperandAllocator); 1410 OperandAllocator.Reset(); 1411 CSEMap.clear(); 1412 1413 ExtendedValueTypeNodes.clear(); 1414 ExternalSymbols.clear(); 1415 TargetExternalSymbols.clear(); 1416 MCSymbols.clear(); 1417 SDEI.clear(); 1418 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1419 static_cast<CondCodeSDNode*>(nullptr)); 1420 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1421 static_cast<SDNode*>(nullptr)); 1422 1423 EntryNode.UseList = nullptr; 1424 InsertNode(&EntryNode); 1425 Root = getEntryNode(); 1426 DbgInfo->clear(); 1427 } 1428 1429 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1430 return VT.bitsGT(Op.getValueType()) 1431 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1432 : getNode(ISD::FP_ROUND, DL, VT, Op, 1433 getIntPtrConstant(0, DL, /*isTarget=*/true)); 1434 } 1435 1436 std::pair<SDValue, SDValue> 1437 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1438 const SDLoc &DL, EVT VT) { 1439 assert(!VT.bitsEq(Op.getValueType()) && 1440 "Strict no-op FP extend/round not allowed."); 1441 SDValue Res = 1442 VT.bitsGT(Op.getValueType()) 1443 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1444 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1445 {Chain, Op, getIntPtrConstant(0, DL)}); 1446 1447 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1448 } 1449 1450 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1451 return VT.bitsGT(Op.getValueType()) ? 1452 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1453 getNode(ISD::TRUNCATE, DL, VT, Op); 1454 } 1455 1456 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1457 return VT.bitsGT(Op.getValueType()) ? 1458 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1459 getNode(ISD::TRUNCATE, DL, VT, Op); 1460 } 1461 1462 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1463 return VT.bitsGT(Op.getValueType()) ? 1464 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1465 getNode(ISD::TRUNCATE, DL, VT, Op); 1466 } 1467 1468 SDValue SelectionDAG::getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, 1469 EVT VT) { 1470 assert(!VT.isVector()); 1471 auto Type = Op.getValueType(); 1472 SDValue DestOp; 1473 if (Type == VT) 1474 return Op; 1475 auto Size = Op.getValueSizeInBits(); 1476 DestOp = getBitcast(MVT::getIntegerVT(Size), Op); 1477 if (DestOp.getValueType() == VT) 1478 return DestOp; 1479 1480 return getAnyExtOrTrunc(DestOp, DL, VT); 1481 } 1482 1483 SDValue SelectionDAG::getBitcastedSExtOrTrunc(SDValue Op, const SDLoc &DL, 1484 EVT VT) { 1485 assert(!VT.isVector()); 1486 auto Type = Op.getValueType(); 1487 SDValue DestOp; 1488 if (Type == VT) 1489 return Op; 1490 auto Size = Op.getValueSizeInBits(); 1491 DestOp = getBitcast(MVT::getIntegerVT(Size), Op); 1492 if (DestOp.getValueType() == VT) 1493 return DestOp; 1494 1495 return getSExtOrTrunc(DestOp, DL, VT); 1496 } 1497 1498 SDValue SelectionDAG::getBitcastedZExtOrTrunc(SDValue Op, const SDLoc &DL, 1499 EVT VT) { 1500 assert(!VT.isVector()); 1501 auto Type = Op.getValueType(); 1502 SDValue DestOp; 1503 if (Type == VT) 1504 return Op; 1505 auto Size = Op.getValueSizeInBits(); 1506 DestOp = getBitcast(MVT::getIntegerVT(Size), Op); 1507 if (DestOp.getValueType() == VT) 1508 return DestOp; 1509 1510 return getZExtOrTrunc(DestOp, DL, VT); 1511 } 1512 1513 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1514 EVT OpVT) { 1515 if (VT.bitsLE(Op.getValueType())) 1516 return getNode(ISD::TRUNCATE, SL, VT, Op); 1517 1518 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1519 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1520 } 1521 1522 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1523 EVT OpVT = Op.getValueType(); 1524 assert(VT.isInteger() && OpVT.isInteger() && 1525 "Cannot getZeroExtendInReg FP types"); 1526 assert(VT.isVector() == OpVT.isVector() && 1527 "getZeroExtendInReg type should be vector iff the operand " 1528 "type is vector!"); 1529 assert((!VT.isVector() || 1530 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1531 "Vector element counts must match in getZeroExtendInReg"); 1532 assert(VT.bitsLE(OpVT) && "Not extending!"); 1533 if (OpVT == VT) 1534 return Op; 1535 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1536 VT.getScalarSizeInBits()); 1537 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1538 } 1539 1540 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1541 // Only unsigned pointer semantics are supported right now. In the future this 1542 // might delegate to TLI to check pointer signedness. 1543 return getZExtOrTrunc(Op, DL, VT); 1544 } 1545 1546 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1547 // Only unsigned pointer semantics are supported right now. In the future this 1548 // might delegate to TLI to check pointer signedness. 1549 return getZeroExtendInReg(Op, DL, VT); 1550 } 1551 1552 SDValue SelectionDAG::getNegative(SDValue Val, const SDLoc &DL, EVT VT) { 1553 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val); 1554 } 1555 1556 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1557 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1558 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1559 } 1560 1561 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1562 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1563 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1564 } 1565 1566 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val, 1567 SDValue Mask, SDValue EVL, EVT VT) { 1568 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1569 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL); 1570 } 1571 1572 SDValue SelectionDAG::getVPPtrExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, 1573 SDValue Mask, SDValue EVL) { 1574 return getVPZExtOrTrunc(DL, VT, Op, Mask, EVL); 1575 } 1576 1577 SDValue SelectionDAG::getVPZExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, 1578 SDValue Mask, SDValue EVL) { 1579 if (VT.bitsGT(Op.getValueType())) 1580 return getNode(ISD::VP_ZERO_EXTEND, DL, VT, Op, Mask, EVL); 1581 if (VT.bitsLT(Op.getValueType())) 1582 return getNode(ISD::VP_TRUNCATE, DL, VT, Op, Mask, EVL); 1583 return Op; 1584 } 1585 1586 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1587 EVT OpVT) { 1588 if (!V) 1589 return getConstant(0, DL, VT); 1590 1591 switch (TLI->getBooleanContents(OpVT)) { 1592 case TargetLowering::ZeroOrOneBooleanContent: 1593 case TargetLowering::UndefinedBooleanContent: 1594 return getConstant(1, DL, VT); 1595 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1596 return getAllOnesConstant(DL, VT); 1597 } 1598 llvm_unreachable("Unexpected boolean content enum!"); 1599 } 1600 1601 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1602 bool isT, bool isO) { 1603 EVT EltVT = VT.getScalarType(); 1604 assert((EltVT.getSizeInBits() >= 64 || 1605 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1606 "getConstant with a uint64_t value that doesn't fit in the type!"); 1607 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1608 } 1609 1610 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1611 bool isT, bool isO) { 1612 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1613 } 1614 1615 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1616 EVT VT, bool isT, bool isO) { 1617 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1618 1619 EVT EltVT = VT.getScalarType(); 1620 const ConstantInt *Elt = &Val; 1621 1622 // In some cases the vector type is legal but the element type is illegal and 1623 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1624 // inserted value (the type does not need to match the vector element type). 1625 // Any extra bits introduced will be truncated away. 1626 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1627 TargetLowering::TypePromoteInteger) { 1628 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1629 APInt NewVal; 1630 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT)) 1631 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits()); 1632 else 1633 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1634 Elt = ConstantInt::get(*getContext(), NewVal); 1635 } 1636 // In other cases the element type is illegal and needs to be expanded, for 1637 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1638 // the value into n parts and use a vector type with n-times the elements. 1639 // Then bitcast to the type requested. 1640 // Legalizing constants too early makes the DAGCombiner's job harder so we 1641 // only legalize if the DAG tells us we must produce legal types. 1642 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1643 TLI->getTypeAction(*getContext(), EltVT) == 1644 TargetLowering::TypeExpandInteger) { 1645 const APInt &NewVal = Elt->getValue(); 1646 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1647 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1648 1649 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1650 if (VT.isScalableVector() || 1651 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) { 1652 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1653 "Can only handle an even split!"); 1654 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1655 1656 SmallVector<SDValue, 2> ScalarParts; 1657 for (unsigned i = 0; i != Parts; ++i) 1658 ScalarParts.push_back(getConstant( 1659 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1660 ViaEltVT, isT, isO)); 1661 1662 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1663 } 1664 1665 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1666 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1667 1668 // Check the temporary vector is the correct size. If this fails then 1669 // getTypeToTransformTo() probably returned a type whose size (in bits) 1670 // isn't a power-of-2 factor of the requested type size. 1671 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1672 1673 SmallVector<SDValue, 2> EltParts; 1674 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1675 EltParts.push_back(getConstant( 1676 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1677 ViaEltVT, isT, isO)); 1678 1679 // EltParts is currently in little endian order. If we actually want 1680 // big-endian order then reverse it now. 1681 if (getDataLayout().isBigEndian()) 1682 std::reverse(EltParts.begin(), EltParts.end()); 1683 1684 // The elements must be reversed when the element order is different 1685 // to the endianness of the elements (because the BITCAST is itself a 1686 // vector shuffle in this situation). However, we do not need any code to 1687 // perform this reversal because getConstant() is producing a vector 1688 // splat. 1689 // This situation occurs in MIPS MSA. 1690 1691 SmallVector<SDValue, 8> Ops; 1692 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1693 llvm::append_range(Ops, EltParts); 1694 1695 SDValue V = 1696 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1697 return V; 1698 } 1699 1700 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1701 "APInt size does not match type size!"); 1702 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1703 FoldingSetNodeID ID; 1704 AddNodeIDNode(ID, Opc, getVTList(EltVT), std::nullopt); 1705 ID.AddPointer(Elt); 1706 ID.AddBoolean(isO); 1707 void *IP = nullptr; 1708 SDNode *N = nullptr; 1709 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1710 if (!VT.isVector()) 1711 return SDValue(N, 0); 1712 1713 if (!N) { 1714 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1715 CSEMap.InsertNode(N, IP); 1716 InsertNode(N); 1717 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1718 } 1719 1720 SDValue Result(N, 0); 1721 if (VT.isVector()) 1722 Result = getSplat(VT, DL, Result); 1723 return Result; 1724 } 1725 1726 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1727 bool isTarget) { 1728 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1729 } 1730 1731 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1732 const SDLoc &DL, bool LegalTypes) { 1733 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1734 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1735 return getConstant(Val, DL, ShiftVT); 1736 } 1737 1738 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1739 bool isTarget) { 1740 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1741 } 1742 1743 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1744 bool isTarget) { 1745 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1746 } 1747 1748 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1749 EVT VT, bool isTarget) { 1750 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1751 1752 EVT EltVT = VT.getScalarType(); 1753 1754 // Do the map lookup using the actual bit pattern for the floating point 1755 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1756 // we don't have issues with SNANs. 1757 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1758 FoldingSetNodeID ID; 1759 AddNodeIDNode(ID, Opc, getVTList(EltVT), std::nullopt); 1760 ID.AddPointer(&V); 1761 void *IP = nullptr; 1762 SDNode *N = nullptr; 1763 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1764 if (!VT.isVector()) 1765 return SDValue(N, 0); 1766 1767 if (!N) { 1768 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1769 CSEMap.InsertNode(N, IP); 1770 InsertNode(N); 1771 } 1772 1773 SDValue Result(N, 0); 1774 if (VT.isVector()) 1775 Result = getSplat(VT, DL, Result); 1776 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1777 return Result; 1778 } 1779 1780 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1781 bool isTarget) { 1782 EVT EltVT = VT.getScalarType(); 1783 if (EltVT == MVT::f32) 1784 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1785 if (EltVT == MVT::f64) 1786 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1787 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1788 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1789 bool Ignored; 1790 APFloat APF = APFloat(Val); 1791 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1792 &Ignored); 1793 return getConstantFP(APF, DL, VT, isTarget); 1794 } 1795 llvm_unreachable("Unsupported type in getConstantFP"); 1796 } 1797 1798 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1799 EVT VT, int64_t Offset, bool isTargetGA, 1800 unsigned TargetFlags) { 1801 assert((TargetFlags == 0 || isTargetGA) && 1802 "Cannot set target flags on target-independent globals"); 1803 1804 // Truncate (with sign-extension) the offset value to the pointer size. 1805 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1806 if (BitWidth < 64) 1807 Offset = SignExtend64(Offset, BitWidth); 1808 1809 unsigned Opc; 1810 if (GV->isThreadLocal()) 1811 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1812 else 1813 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1814 1815 FoldingSetNodeID ID; 1816 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1817 ID.AddPointer(GV); 1818 ID.AddInteger(Offset); 1819 ID.AddInteger(TargetFlags); 1820 void *IP = nullptr; 1821 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1822 return SDValue(E, 0); 1823 1824 auto *N = newSDNode<GlobalAddressSDNode>( 1825 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1826 CSEMap.InsertNode(N, IP); 1827 InsertNode(N); 1828 return SDValue(N, 0); 1829 } 1830 1831 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1832 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1833 FoldingSetNodeID ID; 1834 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1835 ID.AddInteger(FI); 1836 void *IP = nullptr; 1837 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1838 return SDValue(E, 0); 1839 1840 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1841 CSEMap.InsertNode(N, IP); 1842 InsertNode(N); 1843 return SDValue(N, 0); 1844 } 1845 1846 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1847 unsigned TargetFlags) { 1848 assert((TargetFlags == 0 || isTarget) && 1849 "Cannot set target flags on target-independent jump tables"); 1850 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1851 FoldingSetNodeID ID; 1852 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1853 ID.AddInteger(JTI); 1854 ID.AddInteger(TargetFlags); 1855 void *IP = nullptr; 1856 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1857 return SDValue(E, 0); 1858 1859 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1860 CSEMap.InsertNode(N, IP); 1861 InsertNode(N); 1862 return SDValue(N, 0); 1863 } 1864 1865 SDValue SelectionDAG::getJumpTableDebugInfo(int JTI, SDValue Chain, 1866 const SDLoc &DL) { 1867 EVT PTy = getTargetLoweringInfo().getPointerTy(getDataLayout()); 1868 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Glue, Chain, 1869 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true)); 1870 } 1871 1872 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1873 MaybeAlign Alignment, int Offset, 1874 bool isTarget, unsigned TargetFlags) { 1875 assert((TargetFlags == 0 || isTarget) && 1876 "Cannot set target flags on target-independent globals"); 1877 if (!Alignment) 1878 Alignment = shouldOptForSize() 1879 ? getDataLayout().getABITypeAlign(C->getType()) 1880 : getDataLayout().getPrefTypeAlign(C->getType()); 1881 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1882 FoldingSetNodeID ID; 1883 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1884 ID.AddInteger(Alignment->value()); 1885 ID.AddInteger(Offset); 1886 ID.AddPointer(C); 1887 ID.AddInteger(TargetFlags); 1888 void *IP = nullptr; 1889 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1890 return SDValue(E, 0); 1891 1892 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1893 TargetFlags); 1894 CSEMap.InsertNode(N, IP); 1895 InsertNode(N); 1896 SDValue V = SDValue(N, 0); 1897 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1898 return V; 1899 } 1900 1901 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1902 MaybeAlign Alignment, int Offset, 1903 bool isTarget, unsigned TargetFlags) { 1904 assert((TargetFlags == 0 || isTarget) && 1905 "Cannot set target flags on target-independent globals"); 1906 if (!Alignment) 1907 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1908 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1909 FoldingSetNodeID ID; 1910 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1911 ID.AddInteger(Alignment->value()); 1912 ID.AddInteger(Offset); 1913 C->addSelectionDAGCSEId(ID); 1914 ID.AddInteger(TargetFlags); 1915 void *IP = nullptr; 1916 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1917 return SDValue(E, 0); 1918 1919 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1920 TargetFlags); 1921 CSEMap.InsertNode(N, IP); 1922 InsertNode(N); 1923 return SDValue(N, 0); 1924 } 1925 1926 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1927 FoldingSetNodeID ID; 1928 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), std::nullopt); 1929 ID.AddPointer(MBB); 1930 void *IP = nullptr; 1931 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1932 return SDValue(E, 0); 1933 1934 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1935 CSEMap.InsertNode(N, IP); 1936 InsertNode(N); 1937 return SDValue(N, 0); 1938 } 1939 1940 SDValue SelectionDAG::getValueType(EVT VT) { 1941 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1942 ValueTypeNodes.size()) 1943 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1944 1945 SDNode *&N = VT.isExtended() ? 1946 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1947 1948 if (N) return SDValue(N, 0); 1949 N = newSDNode<VTSDNode>(VT); 1950 InsertNode(N); 1951 return SDValue(N, 0); 1952 } 1953 1954 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1955 SDNode *&N = ExternalSymbols[Sym]; 1956 if (N) return SDValue(N, 0); 1957 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1958 InsertNode(N); 1959 return SDValue(N, 0); 1960 } 1961 1962 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1963 SDNode *&N = MCSymbols[Sym]; 1964 if (N) 1965 return SDValue(N, 0); 1966 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1967 InsertNode(N); 1968 return SDValue(N, 0); 1969 } 1970 1971 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1972 unsigned TargetFlags) { 1973 SDNode *&N = 1974 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1975 if (N) return SDValue(N, 0); 1976 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1977 InsertNode(N); 1978 return SDValue(N, 0); 1979 } 1980 1981 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1982 if ((unsigned)Cond >= CondCodeNodes.size()) 1983 CondCodeNodes.resize(Cond+1); 1984 1985 if (!CondCodeNodes[Cond]) { 1986 auto *N = newSDNode<CondCodeSDNode>(Cond); 1987 CondCodeNodes[Cond] = N; 1988 InsertNode(N); 1989 } 1990 1991 return SDValue(CondCodeNodes[Cond], 0); 1992 } 1993 1994 SDValue SelectionDAG::getVScale(const SDLoc &DL, EVT VT, APInt MulImm, 1995 bool ConstantFold) { 1996 assert(MulImm.getBitWidth() == VT.getSizeInBits() && 1997 "APInt size does not match type size!"); 1998 1999 if (MulImm == 0) 2000 return getConstant(0, DL, VT); 2001 2002 if (ConstantFold) { 2003 const MachineFunction &MF = getMachineFunction(); 2004 const Function &F = MF.getFunction(); 2005 ConstantRange CR = getVScaleRange(&F, 64); 2006 if (const APInt *C = CR.getSingleElement()) 2007 return getConstant(MulImm * C->getZExtValue(), DL, VT); 2008 } 2009 2010 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT)); 2011 } 2012 2013 SDValue SelectionDAG::getElementCount(const SDLoc &DL, EVT VT, ElementCount EC, 2014 bool ConstantFold) { 2015 if (EC.isScalable()) 2016 return getVScale(DL, VT, 2017 APInt(VT.getSizeInBits(), EC.getKnownMinValue())); 2018 2019 return getConstant(EC.getKnownMinValue(), DL, VT); 2020 } 2021 2022 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 2023 APInt One(ResVT.getScalarSizeInBits(), 1); 2024 return getStepVector(DL, ResVT, One); 2025 } 2026 2027 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 2028 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 2029 if (ResVT.isScalableVector()) 2030 return getNode( 2031 ISD::STEP_VECTOR, DL, ResVT, 2032 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 2033 2034 SmallVector<SDValue, 16> OpsStepConstants; 2035 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 2036 OpsStepConstants.push_back( 2037 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 2038 return getBuildVector(ResVT, DL, OpsStepConstants); 2039 } 2040 2041 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 2042 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 2043 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 2044 std::swap(N1, N2); 2045 ShuffleVectorSDNode::commuteMask(M); 2046 } 2047 2048 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 2049 SDValue N2, ArrayRef<int> Mask) { 2050 assert(VT.getVectorNumElements() == Mask.size() && 2051 "Must have the same number of vector elements as mask elements!"); 2052 assert(VT == N1.getValueType() && VT == N2.getValueType() && 2053 "Invalid VECTOR_SHUFFLE"); 2054 2055 // Canonicalize shuffle undef, undef -> undef 2056 if (N1.isUndef() && N2.isUndef()) 2057 return getUNDEF(VT); 2058 2059 // Validate that all indices in Mask are within the range of the elements 2060 // input to the shuffle. 2061 int NElts = Mask.size(); 2062 assert(llvm::all_of(Mask, 2063 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 2064 "Index out of range"); 2065 2066 // Copy the mask so we can do any needed cleanup. 2067 SmallVector<int, 8> MaskVec(Mask); 2068 2069 // Canonicalize shuffle v, v -> v, undef 2070 if (N1 == N2) { 2071 N2 = getUNDEF(VT); 2072 for (int i = 0; i != NElts; ++i) 2073 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 2074 } 2075 2076 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 2077 if (N1.isUndef()) 2078 commuteShuffle(N1, N2, MaskVec); 2079 2080 if (TLI->hasVectorBlend()) { 2081 // If shuffling a splat, try to blend the splat instead. We do this here so 2082 // that even when this arises during lowering we don't have to re-handle it. 2083 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 2084 BitVector UndefElements; 2085 SDValue Splat = BV->getSplatValue(&UndefElements); 2086 if (!Splat) 2087 return; 2088 2089 for (int i = 0; i < NElts; ++i) { 2090 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 2091 continue; 2092 2093 // If this input comes from undef, mark it as such. 2094 if (UndefElements[MaskVec[i] - Offset]) { 2095 MaskVec[i] = -1; 2096 continue; 2097 } 2098 2099 // If we can blend a non-undef lane, use that instead. 2100 if (!UndefElements[i]) 2101 MaskVec[i] = i + Offset; 2102 } 2103 }; 2104 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 2105 BlendSplat(N1BV, 0); 2106 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 2107 BlendSplat(N2BV, NElts); 2108 } 2109 2110 // Canonicalize all index into lhs, -> shuffle lhs, undef 2111 // Canonicalize all index into rhs, -> shuffle rhs, undef 2112 bool AllLHS = true, AllRHS = true; 2113 bool N2Undef = N2.isUndef(); 2114 for (int i = 0; i != NElts; ++i) { 2115 if (MaskVec[i] >= NElts) { 2116 if (N2Undef) 2117 MaskVec[i] = -1; 2118 else 2119 AllLHS = false; 2120 } else if (MaskVec[i] >= 0) { 2121 AllRHS = false; 2122 } 2123 } 2124 if (AllLHS && AllRHS) 2125 return getUNDEF(VT); 2126 if (AllLHS && !N2Undef) 2127 N2 = getUNDEF(VT); 2128 if (AllRHS) { 2129 N1 = getUNDEF(VT); 2130 commuteShuffle(N1, N2, MaskVec); 2131 } 2132 // Reset our undef status after accounting for the mask. 2133 N2Undef = N2.isUndef(); 2134 // Re-check whether both sides ended up undef. 2135 if (N1.isUndef() && N2Undef) 2136 return getUNDEF(VT); 2137 2138 // If Identity shuffle return that node. 2139 bool Identity = true, AllSame = true; 2140 for (int i = 0; i != NElts; ++i) { 2141 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 2142 if (MaskVec[i] != MaskVec[0]) AllSame = false; 2143 } 2144 if (Identity && NElts) 2145 return N1; 2146 2147 // Shuffling a constant splat doesn't change the result. 2148 if (N2Undef) { 2149 SDValue V = N1; 2150 2151 // Look through any bitcasts. We check that these don't change the number 2152 // (and size) of elements and just changes their types. 2153 while (V.getOpcode() == ISD::BITCAST) 2154 V = V->getOperand(0); 2155 2156 // A splat should always show up as a build vector node. 2157 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2158 BitVector UndefElements; 2159 SDValue Splat = BV->getSplatValue(&UndefElements); 2160 // If this is a splat of an undef, shuffling it is also undef. 2161 if (Splat && Splat.isUndef()) 2162 return getUNDEF(VT); 2163 2164 bool SameNumElts = 2165 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 2166 2167 // We only have a splat which can skip shuffles if there is a splatted 2168 // value and no undef lanes rearranged by the shuffle. 2169 if (Splat && UndefElements.none()) { 2170 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 2171 // number of elements match or the value splatted is a zero constant. 2172 if (SameNumElts || isNullConstant(Splat)) 2173 return N1; 2174 } 2175 2176 // If the shuffle itself creates a splat, build the vector directly. 2177 if (AllSame && SameNumElts) { 2178 EVT BuildVT = BV->getValueType(0); 2179 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2180 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2181 2182 // We may have jumped through bitcasts, so the type of the 2183 // BUILD_VECTOR may not match the type of the shuffle. 2184 if (BuildVT != VT) 2185 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2186 return NewBV; 2187 } 2188 } 2189 } 2190 2191 FoldingSetNodeID ID; 2192 SDValue Ops[2] = { N1, N2 }; 2193 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2194 for (int i = 0; i != NElts; ++i) 2195 ID.AddInteger(MaskVec[i]); 2196 2197 void* IP = nullptr; 2198 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2199 return SDValue(E, 0); 2200 2201 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2202 // SDNode doesn't have access to it. This memory will be "leaked" when 2203 // the node is deallocated, but recovered when the NodeAllocator is released. 2204 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2205 llvm::copy(MaskVec, MaskAlloc); 2206 2207 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2208 dl.getDebugLoc(), MaskAlloc); 2209 createOperands(N, Ops); 2210 2211 CSEMap.InsertNode(N, IP); 2212 InsertNode(N); 2213 SDValue V = SDValue(N, 0); 2214 NewSDValueDbgMsg(V, "Creating new node: ", this); 2215 return V; 2216 } 2217 2218 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2219 EVT VT = SV.getValueType(0); 2220 SmallVector<int, 8> MaskVec(SV.getMask()); 2221 ShuffleVectorSDNode::commuteMask(MaskVec); 2222 2223 SDValue Op0 = SV.getOperand(0); 2224 SDValue Op1 = SV.getOperand(1); 2225 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2226 } 2227 2228 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2229 FoldingSetNodeID ID; 2230 AddNodeIDNode(ID, ISD::Register, getVTList(VT), std::nullopt); 2231 ID.AddInteger(RegNo); 2232 void *IP = nullptr; 2233 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2234 return SDValue(E, 0); 2235 2236 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2237 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA); 2238 CSEMap.InsertNode(N, IP); 2239 InsertNode(N); 2240 return SDValue(N, 0); 2241 } 2242 2243 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2244 FoldingSetNodeID ID; 2245 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), std::nullopt); 2246 ID.AddPointer(RegMask); 2247 void *IP = nullptr; 2248 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2249 return SDValue(E, 0); 2250 2251 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2252 CSEMap.InsertNode(N, IP); 2253 InsertNode(N); 2254 return SDValue(N, 0); 2255 } 2256 2257 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2258 MCSymbol *Label) { 2259 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2260 } 2261 2262 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2263 SDValue Root, MCSymbol *Label) { 2264 FoldingSetNodeID ID; 2265 SDValue Ops[] = { Root }; 2266 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2267 ID.AddPointer(Label); 2268 void *IP = nullptr; 2269 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2270 return SDValue(E, 0); 2271 2272 auto *N = 2273 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2274 createOperands(N, Ops); 2275 2276 CSEMap.InsertNode(N, IP); 2277 InsertNode(N); 2278 return SDValue(N, 0); 2279 } 2280 2281 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2282 int64_t Offset, bool isTarget, 2283 unsigned TargetFlags) { 2284 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2285 2286 FoldingSetNodeID ID; 2287 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 2288 ID.AddPointer(BA); 2289 ID.AddInteger(Offset); 2290 ID.AddInteger(TargetFlags); 2291 void *IP = nullptr; 2292 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2293 return SDValue(E, 0); 2294 2295 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2296 CSEMap.InsertNode(N, IP); 2297 InsertNode(N); 2298 return SDValue(N, 0); 2299 } 2300 2301 SDValue SelectionDAG::getSrcValue(const Value *V) { 2302 FoldingSetNodeID ID; 2303 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), std::nullopt); 2304 ID.AddPointer(V); 2305 2306 void *IP = nullptr; 2307 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2308 return SDValue(E, 0); 2309 2310 auto *N = newSDNode<SrcValueSDNode>(V); 2311 CSEMap.InsertNode(N, IP); 2312 InsertNode(N); 2313 return SDValue(N, 0); 2314 } 2315 2316 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2317 FoldingSetNodeID ID; 2318 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), std::nullopt); 2319 ID.AddPointer(MD); 2320 2321 void *IP = nullptr; 2322 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2323 return SDValue(E, 0); 2324 2325 auto *N = newSDNode<MDNodeSDNode>(MD); 2326 CSEMap.InsertNode(N, IP); 2327 InsertNode(N); 2328 return SDValue(N, 0); 2329 } 2330 2331 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2332 if (VT == V.getValueType()) 2333 return V; 2334 2335 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2336 } 2337 2338 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2339 unsigned SrcAS, unsigned DestAS) { 2340 SDValue Ops[] = {Ptr}; 2341 FoldingSetNodeID ID; 2342 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2343 ID.AddInteger(SrcAS); 2344 ID.AddInteger(DestAS); 2345 2346 void *IP = nullptr; 2347 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2348 return SDValue(E, 0); 2349 2350 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2351 VT, SrcAS, DestAS); 2352 createOperands(N, Ops); 2353 2354 CSEMap.InsertNode(N, IP); 2355 InsertNode(N); 2356 return SDValue(N, 0); 2357 } 2358 2359 SDValue SelectionDAG::getFreeze(SDValue V) { 2360 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2361 } 2362 2363 /// getShiftAmountOperand - Return the specified value casted to 2364 /// the target's desired shift amount type. 2365 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2366 EVT OpTy = Op.getValueType(); 2367 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2368 if (OpTy == ShTy || OpTy.isVector()) return Op; 2369 2370 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2371 } 2372 2373 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2374 SDLoc dl(Node); 2375 const TargetLowering &TLI = getTargetLoweringInfo(); 2376 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2377 EVT VT = Node->getValueType(0); 2378 SDValue Tmp1 = Node->getOperand(0); 2379 SDValue Tmp2 = Node->getOperand(1); 2380 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2381 2382 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2383 Tmp2, MachinePointerInfo(V)); 2384 SDValue VAList = VAListLoad; 2385 2386 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2387 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2388 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2389 2390 VAList = 2391 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2392 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2393 } 2394 2395 // Increment the pointer, VAList, to the next vaarg 2396 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2397 getConstant(getDataLayout().getTypeAllocSize( 2398 VT.getTypeForEVT(*getContext())), 2399 dl, VAList.getValueType())); 2400 // Store the incremented VAList to the legalized pointer 2401 Tmp1 = 2402 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2403 // Load the actual argument out of the pointer VAList 2404 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2405 } 2406 2407 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2408 SDLoc dl(Node); 2409 const TargetLowering &TLI = getTargetLoweringInfo(); 2410 // This defaults to loading a pointer from the input and storing it to the 2411 // output, returning the chain. 2412 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2413 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2414 SDValue Tmp1 = 2415 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2416 Node->getOperand(2), MachinePointerInfo(VS)); 2417 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2418 MachinePointerInfo(VD)); 2419 } 2420 2421 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2422 const DataLayout &DL = getDataLayout(); 2423 Type *Ty = VT.getTypeForEVT(*getContext()); 2424 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2425 2426 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2427 return RedAlign; 2428 2429 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2430 const Align StackAlign = TFI->getStackAlign(); 2431 2432 // See if we can choose a smaller ABI alignment in cases where it's an 2433 // illegal vector type that will get broken down. 2434 if (RedAlign > StackAlign) { 2435 EVT IntermediateVT; 2436 MVT RegisterVT; 2437 unsigned NumIntermediates; 2438 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2439 NumIntermediates, RegisterVT); 2440 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2441 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2442 if (RedAlign2 < RedAlign) 2443 RedAlign = RedAlign2; 2444 } 2445 2446 return RedAlign; 2447 } 2448 2449 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2450 MachineFrameInfo &MFI = MF->getFrameInfo(); 2451 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2452 int StackID = 0; 2453 if (Bytes.isScalable()) 2454 StackID = TFI->getStackIDForScalableVectors(); 2455 // The stack id gives an indication of whether the object is scalable or 2456 // not, so it's safe to pass in the minimum size here. 2457 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment, 2458 false, nullptr, StackID); 2459 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2460 } 2461 2462 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2463 Type *Ty = VT.getTypeForEVT(*getContext()); 2464 Align StackAlign = 2465 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2466 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2467 } 2468 2469 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2470 TypeSize VT1Size = VT1.getStoreSize(); 2471 TypeSize VT2Size = VT2.getStoreSize(); 2472 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2473 "Don't know how to choose the maximum size when creating a stack " 2474 "temporary"); 2475 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue() 2476 ? VT1Size 2477 : VT2Size; 2478 2479 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2480 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2481 const DataLayout &DL = getDataLayout(); 2482 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2483 return CreateStackTemporary(Bytes, Align); 2484 } 2485 2486 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2487 ISD::CondCode Cond, const SDLoc &dl) { 2488 EVT OpVT = N1.getValueType(); 2489 2490 auto GetUndefBooleanConstant = [&]() { 2491 if (VT.getScalarType() == MVT::i1 || 2492 TLI->getBooleanContents(OpVT) == 2493 TargetLowering::UndefinedBooleanContent) 2494 return getUNDEF(VT); 2495 // ZeroOrOne / ZeroOrNegative require specific values for the high bits, 2496 // so we cannot use getUNDEF(). Return zero instead. 2497 return getConstant(0, dl, VT); 2498 }; 2499 2500 // These setcc operations always fold. 2501 switch (Cond) { 2502 default: break; 2503 case ISD::SETFALSE: 2504 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2505 case ISD::SETTRUE: 2506 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2507 2508 case ISD::SETOEQ: 2509 case ISD::SETOGT: 2510 case ISD::SETOGE: 2511 case ISD::SETOLT: 2512 case ISD::SETOLE: 2513 case ISD::SETONE: 2514 case ISD::SETO: 2515 case ISD::SETUO: 2516 case ISD::SETUEQ: 2517 case ISD::SETUNE: 2518 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2519 break; 2520 } 2521 2522 if (OpVT.isInteger()) { 2523 // For EQ and NE, we can always pick a value for the undef to make the 2524 // predicate pass or fail, so we can return undef. 2525 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2526 // icmp eq/ne X, undef -> undef. 2527 if ((N1.isUndef() || N2.isUndef()) && 2528 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2529 return GetUndefBooleanConstant(); 2530 2531 // If both operands are undef, we can return undef for int comparison. 2532 // icmp undef, undef -> undef. 2533 if (N1.isUndef() && N2.isUndef()) 2534 return GetUndefBooleanConstant(); 2535 2536 // icmp X, X -> true/false 2537 // icmp X, undef -> true/false because undef could be X. 2538 if (N1.isUndef() || N2.isUndef() || N1 == N2) 2539 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2540 } 2541 2542 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2543 const APInt &C2 = N2C->getAPIntValue(); 2544 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2545 const APInt &C1 = N1C->getAPIntValue(); 2546 2547 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2548 dl, VT, OpVT); 2549 } 2550 } 2551 2552 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2553 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2554 2555 if (N1CFP && N2CFP) { 2556 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2557 switch (Cond) { 2558 default: break; 2559 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2560 return GetUndefBooleanConstant(); 2561 [[fallthrough]]; 2562 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2563 OpVT); 2564 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2565 return GetUndefBooleanConstant(); 2566 [[fallthrough]]; 2567 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2568 R==APFloat::cmpLessThan, dl, VT, 2569 OpVT); 2570 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2571 return GetUndefBooleanConstant(); 2572 [[fallthrough]]; 2573 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2574 OpVT); 2575 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2576 return GetUndefBooleanConstant(); 2577 [[fallthrough]]; 2578 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2579 VT, OpVT); 2580 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2581 return GetUndefBooleanConstant(); 2582 [[fallthrough]]; 2583 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2584 R==APFloat::cmpEqual, dl, VT, 2585 OpVT); 2586 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2587 return GetUndefBooleanConstant(); 2588 [[fallthrough]]; 2589 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2590 R==APFloat::cmpEqual, dl, VT, OpVT); 2591 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2592 OpVT); 2593 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2594 OpVT); 2595 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2596 R==APFloat::cmpEqual, dl, VT, 2597 OpVT); 2598 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2599 OpVT); 2600 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2601 R==APFloat::cmpLessThan, dl, VT, 2602 OpVT); 2603 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2604 R==APFloat::cmpUnordered, dl, VT, 2605 OpVT); 2606 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2607 VT, OpVT); 2608 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2609 OpVT); 2610 } 2611 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2612 // Ensure that the constant occurs on the RHS. 2613 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2614 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2615 return SDValue(); 2616 return getSetCC(dl, VT, N2, N1, SwappedCond); 2617 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2618 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2619 // If an operand is known to be a nan (or undef that could be a nan), we can 2620 // fold it. 2621 // Choosing NaN for the undef will always make unordered comparison succeed 2622 // and ordered comparison fails. 2623 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2624 switch (ISD::getUnorderedFlavor(Cond)) { 2625 default: 2626 llvm_unreachable("Unknown flavor!"); 2627 case 0: // Known false. 2628 return getBoolConstant(false, dl, VT, OpVT); 2629 case 1: // Known true. 2630 return getBoolConstant(true, dl, VT, OpVT); 2631 case 2: // Undefined. 2632 return GetUndefBooleanConstant(); 2633 } 2634 } 2635 2636 // Could not fold it. 2637 return SDValue(); 2638 } 2639 2640 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2641 /// use this predicate to simplify operations downstream. 2642 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2643 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2644 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2645 } 2646 2647 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2648 /// this predicate to simplify operations downstream. Mask is known to be zero 2649 /// for bits that V cannot have. 2650 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2651 unsigned Depth) const { 2652 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2653 } 2654 2655 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2656 /// DemandedElts. We use this predicate to simplify operations downstream. 2657 /// Mask is known to be zero for bits that V cannot have. 2658 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2659 const APInt &DemandedElts, 2660 unsigned Depth) const { 2661 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2662 } 2663 2664 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in 2665 /// DemandedElts. We use this predicate to simplify operations downstream. 2666 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts, 2667 unsigned Depth /* = 0 */) const { 2668 return computeKnownBits(V, DemandedElts, Depth).isZero(); 2669 } 2670 2671 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2672 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2673 unsigned Depth) const { 2674 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2675 } 2676 2677 APInt SelectionDAG::computeVectorKnownZeroElements(SDValue Op, 2678 const APInt &DemandedElts, 2679 unsigned Depth) const { 2680 EVT VT = Op.getValueType(); 2681 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!"); 2682 2683 unsigned NumElts = VT.getVectorNumElements(); 2684 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask."); 2685 2686 APInt KnownZeroElements = APInt::getZero(NumElts); 2687 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) { 2688 if (!DemandedElts[EltIdx]) 2689 continue; // Don't query elements that are not demanded. 2690 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx); 2691 if (MaskedVectorIsZero(Op, Mask, Depth)) 2692 KnownZeroElements.setBit(EltIdx); 2693 } 2694 return KnownZeroElements; 2695 } 2696 2697 /// isSplatValue - Return true if the vector V has the same value 2698 /// across all DemandedElts. For scalable vectors, we don't know the 2699 /// number of lanes at compile time. Instead, we use a 1 bit APInt 2700 /// to represent a conservative value for all lanes; that is, that 2701 /// one bit value is implicitly splatted across all lanes. 2702 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2703 APInt &UndefElts, unsigned Depth) const { 2704 unsigned Opcode = V.getOpcode(); 2705 EVT VT = V.getValueType(); 2706 assert(VT.isVector() && "Vector type expected"); 2707 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) && 2708 "scalable demanded bits are ignored"); 2709 2710 if (!DemandedElts) 2711 return false; // No demanded elts, better to assume we don't know anything. 2712 2713 if (Depth >= MaxRecursionDepth) 2714 return false; // Limit search depth. 2715 2716 // Deal with some common cases here that work for both fixed and scalable 2717 // vector types. 2718 switch (Opcode) { 2719 case ISD::SPLAT_VECTOR: 2720 UndefElts = V.getOperand(0).isUndef() 2721 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2722 : APInt(DemandedElts.getBitWidth(), 0); 2723 return true; 2724 case ISD::ADD: 2725 case ISD::SUB: 2726 case ISD::AND: 2727 case ISD::XOR: 2728 case ISD::OR: { 2729 APInt UndefLHS, UndefRHS; 2730 SDValue LHS = V.getOperand(0); 2731 SDValue RHS = V.getOperand(1); 2732 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2733 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2734 UndefElts = UndefLHS | UndefRHS; 2735 return true; 2736 } 2737 return false; 2738 } 2739 case ISD::ABS: 2740 case ISD::TRUNCATE: 2741 case ISD::SIGN_EXTEND: 2742 case ISD::ZERO_EXTEND: 2743 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2744 default: 2745 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2746 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2747 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this, 2748 Depth); 2749 break; 2750 } 2751 2752 // We don't support other cases than those above for scalable vectors at 2753 // the moment. 2754 if (VT.isScalableVector()) 2755 return false; 2756 2757 unsigned NumElts = VT.getVectorNumElements(); 2758 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2759 UndefElts = APInt::getZero(NumElts); 2760 2761 switch (Opcode) { 2762 case ISD::BUILD_VECTOR: { 2763 SDValue Scl; 2764 for (unsigned i = 0; i != NumElts; ++i) { 2765 SDValue Op = V.getOperand(i); 2766 if (Op.isUndef()) { 2767 UndefElts.setBit(i); 2768 continue; 2769 } 2770 if (!DemandedElts[i]) 2771 continue; 2772 if (Scl && Scl != Op) 2773 return false; 2774 Scl = Op; 2775 } 2776 return true; 2777 } 2778 case ISD::VECTOR_SHUFFLE: { 2779 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2780 APInt DemandedLHS = APInt::getZero(NumElts); 2781 APInt DemandedRHS = APInt::getZero(NumElts); 2782 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2783 for (int i = 0; i != (int)NumElts; ++i) { 2784 int M = Mask[i]; 2785 if (M < 0) { 2786 UndefElts.setBit(i); 2787 continue; 2788 } 2789 if (!DemandedElts[i]) 2790 continue; 2791 if (M < (int)NumElts) 2792 DemandedLHS.setBit(M); 2793 else 2794 DemandedRHS.setBit(M - NumElts); 2795 } 2796 2797 // If we aren't demanding either op, assume there's no splat. 2798 // If we are demanding both ops, assume there's no splat. 2799 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2800 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2801 return false; 2802 2803 // See if the demanded elts of the source op is a splat or we only demand 2804 // one element, which should always be a splat. 2805 // TODO: Handle source ops splats with undefs. 2806 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2807 APInt SrcUndefs; 2808 return (SrcElts.popcount() == 1) || 2809 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2810 (SrcElts & SrcUndefs).isZero()); 2811 }; 2812 if (!DemandedLHS.isZero()) 2813 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2814 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2815 } 2816 case ISD::EXTRACT_SUBVECTOR: { 2817 // Offset the demanded elts by the subvector index. 2818 SDValue Src = V.getOperand(0); 2819 // We don't support scalable vectors at the moment. 2820 if (Src.getValueType().isScalableVector()) 2821 return false; 2822 uint64_t Idx = V.getConstantOperandVal(1); 2823 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2824 APInt UndefSrcElts; 2825 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 2826 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2827 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2828 return true; 2829 } 2830 break; 2831 } 2832 case ISD::ANY_EXTEND_VECTOR_INREG: 2833 case ISD::SIGN_EXTEND_VECTOR_INREG: 2834 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2835 // Widen the demanded elts by the src element count. 2836 SDValue Src = V.getOperand(0); 2837 // We don't support scalable vectors at the moment. 2838 if (Src.getValueType().isScalableVector()) 2839 return false; 2840 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2841 APInt UndefSrcElts; 2842 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 2843 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2844 UndefElts = UndefSrcElts.trunc(NumElts); 2845 return true; 2846 } 2847 break; 2848 } 2849 case ISD::BITCAST: { 2850 SDValue Src = V.getOperand(0); 2851 EVT SrcVT = Src.getValueType(); 2852 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2853 unsigned BitWidth = VT.getScalarSizeInBits(); 2854 2855 // Ignore bitcasts from unsupported types. 2856 // TODO: Add fp support? 2857 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2858 break; 2859 2860 // Bitcast 'small element' vector to 'large element' vector. 2861 if ((BitWidth % SrcBitWidth) == 0) { 2862 // See if each sub element is a splat. 2863 unsigned Scale = BitWidth / SrcBitWidth; 2864 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2865 APInt ScaledDemandedElts = 2866 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2867 for (unsigned I = 0; I != Scale; ++I) { 2868 APInt SubUndefElts; 2869 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2870 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2871 SubDemandedElts &= ScaledDemandedElts; 2872 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2873 return false; 2874 // TODO: Add support for merging sub undef elements. 2875 if (!SubUndefElts.isZero()) 2876 return false; 2877 } 2878 return true; 2879 } 2880 break; 2881 } 2882 } 2883 2884 // Fallback - this is a splat if all demanded elts are the same constant. 2885 if (computeKnownBits(V, DemandedElts, Depth).isConstant()) { 2886 UndefElts = ~DemandedElts; 2887 return true; 2888 } 2889 2890 return false; 2891 } 2892 2893 /// Helper wrapper to main isSplatValue function. 2894 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2895 EVT VT = V.getValueType(); 2896 assert(VT.isVector() && "Vector type expected"); 2897 2898 APInt UndefElts; 2899 // Since the number of lanes in a scalable vector is unknown at compile time, 2900 // we track one bit which is implicitly broadcast to all lanes. This means 2901 // that all lanes in a scalable vector are considered demanded. 2902 APInt DemandedElts 2903 = APInt::getAllOnes(VT.isScalableVector() ? 1 : VT.getVectorNumElements()); 2904 return isSplatValue(V, DemandedElts, UndefElts) && 2905 (AllowUndefs || !UndefElts); 2906 } 2907 2908 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2909 V = peekThroughExtractSubvectors(V); 2910 2911 EVT VT = V.getValueType(); 2912 unsigned Opcode = V.getOpcode(); 2913 switch (Opcode) { 2914 default: { 2915 APInt UndefElts; 2916 // Since the number of lanes in a scalable vector is unknown at compile time, 2917 // we track one bit which is implicitly broadcast to all lanes. This means 2918 // that all lanes in a scalable vector are considered demanded. 2919 APInt DemandedElts 2920 = APInt::getAllOnes(VT.isScalableVector() ? 1 : VT.getVectorNumElements()); 2921 2922 if (isSplatValue(V, DemandedElts, UndefElts)) { 2923 if (VT.isScalableVector()) { 2924 // DemandedElts and UndefElts are ignored for scalable vectors, since 2925 // the only supported cases are SPLAT_VECTOR nodes. 2926 SplatIdx = 0; 2927 } else { 2928 // Handle case where all demanded elements are UNDEF. 2929 if (DemandedElts.isSubsetOf(UndefElts)) { 2930 SplatIdx = 0; 2931 return getUNDEF(VT); 2932 } 2933 SplatIdx = (UndefElts & DemandedElts).countr_one(); 2934 } 2935 return V; 2936 } 2937 break; 2938 } 2939 case ISD::SPLAT_VECTOR: 2940 SplatIdx = 0; 2941 return V; 2942 case ISD::VECTOR_SHUFFLE: { 2943 assert(!VT.isScalableVector()); 2944 // Check if this is a shuffle node doing a splat. 2945 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2946 // getTargetVShiftNode currently struggles without the splat source. 2947 auto *SVN = cast<ShuffleVectorSDNode>(V); 2948 if (!SVN->isSplat()) 2949 break; 2950 int Idx = SVN->getSplatIndex(); 2951 int NumElts = V.getValueType().getVectorNumElements(); 2952 SplatIdx = Idx % NumElts; 2953 return V.getOperand(Idx / NumElts); 2954 } 2955 } 2956 2957 return SDValue(); 2958 } 2959 2960 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2961 int SplatIdx; 2962 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2963 EVT SVT = SrcVector.getValueType().getScalarType(); 2964 EVT LegalSVT = SVT; 2965 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2966 if (!SVT.isInteger()) 2967 return SDValue(); 2968 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2969 if (LegalSVT.bitsLT(SVT)) 2970 return SDValue(); 2971 } 2972 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2973 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2974 } 2975 return SDValue(); 2976 } 2977 2978 const APInt * 2979 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2980 const APInt &DemandedElts) const { 2981 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2982 V.getOpcode() == ISD::SRA) && 2983 "Unknown shift node"); 2984 unsigned BitWidth = V.getScalarValueSizeInBits(); 2985 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2986 // Shifting more than the bitwidth is not valid. 2987 const APInt &ShAmt = SA->getAPIntValue(); 2988 if (ShAmt.ult(BitWidth)) 2989 return &ShAmt; 2990 } 2991 return nullptr; 2992 } 2993 2994 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2995 SDValue V, const APInt &DemandedElts) const { 2996 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2997 V.getOpcode() == ISD::SRA) && 2998 "Unknown shift node"); 2999 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 3000 return ValidAmt; 3001 unsigned BitWidth = V.getScalarValueSizeInBits(); 3002 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 3003 if (!BV) 3004 return nullptr; 3005 const APInt *MinShAmt = nullptr; 3006 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 3007 if (!DemandedElts[i]) 3008 continue; 3009 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 3010 if (!SA) 3011 return nullptr; 3012 // Shifting more than the bitwidth is not valid. 3013 const APInt &ShAmt = SA->getAPIntValue(); 3014 if (ShAmt.uge(BitWidth)) 3015 return nullptr; 3016 if (MinShAmt && MinShAmt->ule(ShAmt)) 3017 continue; 3018 MinShAmt = &ShAmt; 3019 } 3020 return MinShAmt; 3021 } 3022 3023 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 3024 SDValue V, const APInt &DemandedElts) const { 3025 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 3026 V.getOpcode() == ISD::SRA) && 3027 "Unknown shift node"); 3028 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 3029 return ValidAmt; 3030 unsigned BitWidth = V.getScalarValueSizeInBits(); 3031 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 3032 if (!BV) 3033 return nullptr; 3034 const APInt *MaxShAmt = nullptr; 3035 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 3036 if (!DemandedElts[i]) 3037 continue; 3038 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 3039 if (!SA) 3040 return nullptr; 3041 // Shifting more than the bitwidth is not valid. 3042 const APInt &ShAmt = SA->getAPIntValue(); 3043 if (ShAmt.uge(BitWidth)) 3044 return nullptr; 3045 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 3046 continue; 3047 MaxShAmt = &ShAmt; 3048 } 3049 return MaxShAmt; 3050 } 3051 3052 /// Determine which bits of Op are known to be either zero or one and return 3053 /// them in Known. For vectors, the known bits are those that are shared by 3054 /// every vector element. 3055 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 3056 EVT VT = Op.getValueType(); 3057 3058 // Since the number of lanes in a scalable vector is unknown at compile time, 3059 // we track one bit which is implicitly broadcast to all lanes. This means 3060 // that all lanes in a scalable vector are considered demanded. 3061 APInt DemandedElts = VT.isFixedLengthVector() 3062 ? APInt::getAllOnes(VT.getVectorNumElements()) 3063 : APInt(1, 1); 3064 return computeKnownBits(Op, DemandedElts, Depth); 3065 } 3066 3067 /// Determine which bits of Op are known to be either zero or one and return 3068 /// them in Known. The DemandedElts argument allows us to only collect the known 3069 /// bits that are shared by the requested vector elements. 3070 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 3071 unsigned Depth) const { 3072 unsigned BitWidth = Op.getScalarValueSizeInBits(); 3073 3074 KnownBits Known(BitWidth); // Don't know anything. 3075 3076 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3077 // We know all of the bits for a constant! 3078 return KnownBits::makeConstant(C->getAPIntValue()); 3079 } 3080 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 3081 // We know all of the bits for a constant fp! 3082 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 3083 } 3084 3085 if (Depth >= MaxRecursionDepth) 3086 return Known; // Limit search depth. 3087 3088 KnownBits Known2; 3089 unsigned NumElts = DemandedElts.getBitWidth(); 3090 assert((!Op.getValueType().isFixedLengthVector() || 3091 NumElts == Op.getValueType().getVectorNumElements()) && 3092 "Unexpected vector size"); 3093 3094 if (!DemandedElts) 3095 return Known; // No demanded elts, better to assume we don't know anything. 3096 3097 unsigned Opcode = Op.getOpcode(); 3098 switch (Opcode) { 3099 case ISD::MERGE_VALUES: 3100 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts, 3101 Depth + 1); 3102 case ISD::SPLAT_VECTOR: { 3103 SDValue SrcOp = Op.getOperand(0); 3104 assert(SrcOp.getValueSizeInBits() >= BitWidth && 3105 "Expected SPLAT_VECTOR implicit truncation"); 3106 // Implicitly truncate the bits to match the official semantics of 3107 // SPLAT_VECTOR. 3108 Known = computeKnownBits(SrcOp, Depth + 1).trunc(BitWidth); 3109 break; 3110 } 3111 case ISD::SPLAT_VECTOR_PARTS: { 3112 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits(); 3113 assert(ScalarSize * Op.getNumOperands() == BitWidth && 3114 "Expected SPLAT_VECTOR_PARTS scalars to cover element width"); 3115 for (auto [I, SrcOp] : enumerate(Op->ops())) { 3116 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I); 3117 } 3118 break; 3119 } 3120 case ISD::BUILD_VECTOR: 3121 assert(!Op.getValueType().isScalableVector()); 3122 // Collect the known bits that are shared by every demanded vector element. 3123 Known.Zero.setAllBits(); Known.One.setAllBits(); 3124 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 3125 if (!DemandedElts[i]) 3126 continue; 3127 3128 SDValue SrcOp = Op.getOperand(i); 3129 Known2 = computeKnownBits(SrcOp, Depth + 1); 3130 3131 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3132 if (SrcOp.getValueSizeInBits() != BitWidth) { 3133 assert(SrcOp.getValueSizeInBits() > BitWidth && 3134 "Expected BUILD_VECTOR implicit truncation"); 3135 Known2 = Known2.trunc(BitWidth); 3136 } 3137 3138 // Known bits are the values that are shared by every demanded element. 3139 Known = Known.intersectWith(Known2); 3140 3141 // If we don't know any bits, early out. 3142 if (Known.isUnknown()) 3143 break; 3144 } 3145 break; 3146 case ISD::VECTOR_SHUFFLE: { 3147 assert(!Op.getValueType().isScalableVector()); 3148 // Collect the known bits that are shared by every vector element referenced 3149 // by the shuffle. 3150 APInt DemandedLHS, DemandedRHS; 3151 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3152 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3153 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts, 3154 DemandedLHS, DemandedRHS)) 3155 break; 3156 3157 // Known bits are the values that are shared by every demanded element. 3158 Known.Zero.setAllBits(); Known.One.setAllBits(); 3159 if (!!DemandedLHS) { 3160 SDValue LHS = Op.getOperand(0); 3161 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 3162 Known = Known.intersectWith(Known2); 3163 } 3164 // If we don't know any bits, early out. 3165 if (Known.isUnknown()) 3166 break; 3167 if (!!DemandedRHS) { 3168 SDValue RHS = Op.getOperand(1); 3169 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3170 Known = Known.intersectWith(Known2); 3171 } 3172 break; 3173 } 3174 case ISD::VSCALE: { 3175 const Function &F = getMachineFunction().getFunction(); 3176 const APInt &Multiplier = Op.getConstantOperandAPInt(0); 3177 Known = getVScaleRange(&F, BitWidth).multiply(Multiplier).toKnownBits(); 3178 break; 3179 } 3180 case ISD::CONCAT_VECTORS: { 3181 if (Op.getValueType().isScalableVector()) 3182 break; 3183 // Split DemandedElts and test each of the demanded subvectors. 3184 Known.Zero.setAllBits(); Known.One.setAllBits(); 3185 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3186 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3187 unsigned NumSubVectors = Op.getNumOperands(); 3188 for (unsigned i = 0; i != NumSubVectors; ++i) { 3189 APInt DemandedSub = 3190 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3191 if (!!DemandedSub) { 3192 SDValue Sub = Op.getOperand(i); 3193 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3194 Known = Known.intersectWith(Known2); 3195 } 3196 // If we don't know any bits, early out. 3197 if (Known.isUnknown()) 3198 break; 3199 } 3200 break; 3201 } 3202 case ISD::INSERT_SUBVECTOR: { 3203 if (Op.getValueType().isScalableVector()) 3204 break; 3205 // Demand any elements from the subvector and the remainder from the src its 3206 // inserted into. 3207 SDValue Src = Op.getOperand(0); 3208 SDValue Sub = Op.getOperand(1); 3209 uint64_t Idx = Op.getConstantOperandVal(2); 3210 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3211 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3212 APInt DemandedSrcElts = DemandedElts; 3213 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3214 3215 Known.One.setAllBits(); 3216 Known.Zero.setAllBits(); 3217 if (!!DemandedSubElts) { 3218 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3219 if (Known.isUnknown()) 3220 break; // early-out. 3221 } 3222 if (!!DemandedSrcElts) { 3223 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3224 Known = Known.intersectWith(Known2); 3225 } 3226 break; 3227 } 3228 case ISD::EXTRACT_SUBVECTOR: { 3229 // Offset the demanded elts by the subvector index. 3230 SDValue Src = Op.getOperand(0); 3231 // Bail until we can represent demanded elements for scalable vectors. 3232 if (Op.getValueType().isScalableVector() || Src.getValueType().isScalableVector()) 3233 break; 3234 uint64_t Idx = Op.getConstantOperandVal(1); 3235 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3236 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3237 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3238 break; 3239 } 3240 case ISD::SCALAR_TO_VECTOR: { 3241 if (Op.getValueType().isScalableVector()) 3242 break; 3243 // We know about scalar_to_vector as much as we know about it source, 3244 // which becomes the first element of otherwise unknown vector. 3245 if (DemandedElts != 1) 3246 break; 3247 3248 SDValue N0 = Op.getOperand(0); 3249 Known = computeKnownBits(N0, Depth + 1); 3250 if (N0.getValueSizeInBits() != BitWidth) 3251 Known = Known.trunc(BitWidth); 3252 3253 break; 3254 } 3255 case ISD::BITCAST: { 3256 if (Op.getValueType().isScalableVector()) 3257 break; 3258 3259 SDValue N0 = Op.getOperand(0); 3260 EVT SubVT = N0.getValueType(); 3261 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3262 3263 // Ignore bitcasts from unsupported types. 3264 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3265 break; 3266 3267 // Fast handling of 'identity' bitcasts. 3268 if (BitWidth == SubBitWidth) { 3269 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3270 break; 3271 } 3272 3273 bool IsLE = getDataLayout().isLittleEndian(); 3274 3275 // Bitcast 'small element' vector to 'large element' scalar/vector. 3276 if ((BitWidth % SubBitWidth) == 0) { 3277 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3278 3279 // Collect known bits for the (larger) output by collecting the known 3280 // bits from each set of sub elements and shift these into place. 3281 // We need to separately call computeKnownBits for each set of 3282 // sub elements as the knownbits for each is likely to be different. 3283 unsigned SubScale = BitWidth / SubBitWidth; 3284 APInt SubDemandedElts(NumElts * SubScale, 0); 3285 for (unsigned i = 0; i != NumElts; ++i) 3286 if (DemandedElts[i]) 3287 SubDemandedElts.setBit(i * SubScale); 3288 3289 for (unsigned i = 0; i != SubScale; ++i) { 3290 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3291 Depth + 1); 3292 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3293 Known.insertBits(Known2, SubBitWidth * Shifts); 3294 } 3295 } 3296 3297 // Bitcast 'large element' scalar/vector to 'small element' vector. 3298 if ((SubBitWidth % BitWidth) == 0) { 3299 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3300 3301 // Collect known bits for the (smaller) output by collecting the known 3302 // bits from the overlapping larger input elements and extracting the 3303 // sub sections we actually care about. 3304 unsigned SubScale = SubBitWidth / BitWidth; 3305 APInt SubDemandedElts = 3306 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3307 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3308 3309 Known.Zero.setAllBits(); Known.One.setAllBits(); 3310 for (unsigned i = 0; i != NumElts; ++i) 3311 if (DemandedElts[i]) { 3312 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3313 unsigned Offset = (Shifts % SubScale) * BitWidth; 3314 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset)); 3315 // If we don't know any bits, early out. 3316 if (Known.isUnknown()) 3317 break; 3318 } 3319 } 3320 break; 3321 } 3322 case ISD::AND: 3323 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3324 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3325 3326 Known &= Known2; 3327 break; 3328 case ISD::OR: 3329 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3330 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3331 3332 Known |= Known2; 3333 break; 3334 case ISD::XOR: 3335 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3336 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3337 3338 Known ^= Known2; 3339 break; 3340 case ISD::MUL: { 3341 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3342 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3343 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3344 // TODO: SelfMultiply can be poison, but not undef. 3345 if (SelfMultiply) 3346 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3347 Op.getOperand(0), DemandedElts, false, Depth + 1); 3348 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3349 3350 // If the multiplication is known not to overflow, the product of a number 3351 // with itself is non-negative. Only do this if we didn't already computed 3352 // the opposite value for the sign bit. 3353 if (Op->getFlags().hasNoSignedWrap() && 3354 Op.getOperand(0) == Op.getOperand(1) && 3355 !Known.isNegative()) 3356 Known.makeNonNegative(); 3357 break; 3358 } 3359 case ISD::MULHU: { 3360 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3361 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3362 Known = KnownBits::mulhu(Known, Known2); 3363 break; 3364 } 3365 case ISD::MULHS: { 3366 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3367 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3368 Known = KnownBits::mulhs(Known, Known2); 3369 break; 3370 } 3371 case ISD::UMUL_LOHI: { 3372 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3373 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3374 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3375 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3376 if (Op.getResNo() == 0) 3377 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3378 else 3379 Known = KnownBits::mulhu(Known, Known2); 3380 break; 3381 } 3382 case ISD::SMUL_LOHI: { 3383 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3384 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3385 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3386 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3387 if (Op.getResNo() == 0) 3388 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3389 else 3390 Known = KnownBits::mulhs(Known, Known2); 3391 break; 3392 } 3393 case ISD::AVGCEILU: { 3394 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3395 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3396 Known = Known.zext(BitWidth + 1); 3397 Known2 = Known2.zext(BitWidth + 1); 3398 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3399 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3400 Known = Known.extractBits(BitWidth, 1); 3401 break; 3402 } 3403 case ISD::SELECT: 3404 case ISD::VSELECT: 3405 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3406 // If we don't know any bits, early out. 3407 if (Known.isUnknown()) 3408 break; 3409 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3410 3411 // Only known if known in both the LHS and RHS. 3412 Known = Known.intersectWith(Known2); 3413 break; 3414 case ISD::SELECT_CC: 3415 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3416 // If we don't know any bits, early out. 3417 if (Known.isUnknown()) 3418 break; 3419 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3420 3421 // Only known if known in both the LHS and RHS. 3422 Known = Known.intersectWith(Known2); 3423 break; 3424 case ISD::SMULO: 3425 case ISD::UMULO: 3426 if (Op.getResNo() != 1) 3427 break; 3428 // The boolean result conforms to getBooleanContents. 3429 // If we know the result of a setcc has the top bits zero, use this info. 3430 // We know that we have an integer-based boolean since these operations 3431 // are only available for integer. 3432 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3433 TargetLowering::ZeroOrOneBooleanContent && 3434 BitWidth > 1) 3435 Known.Zero.setBitsFrom(1); 3436 break; 3437 case ISD::SETCC: 3438 case ISD::SETCCCARRY: 3439 case ISD::STRICT_FSETCC: 3440 case ISD::STRICT_FSETCCS: { 3441 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3442 // If we know the result of a setcc has the top bits zero, use this info. 3443 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3444 TargetLowering::ZeroOrOneBooleanContent && 3445 BitWidth > 1) 3446 Known.Zero.setBitsFrom(1); 3447 break; 3448 } 3449 case ISD::SHL: 3450 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3451 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3452 Known = KnownBits::shl(Known, Known2); 3453 3454 // Minimum shift low bits are known zero. 3455 if (const APInt *ShMinAmt = 3456 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3457 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3458 break; 3459 case ISD::SRL: 3460 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3461 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3462 Known = KnownBits::lshr(Known, Known2); 3463 3464 // Minimum shift high bits are known zero. 3465 if (const APInt *ShMinAmt = 3466 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3467 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3468 break; 3469 case ISD::SRA: 3470 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3471 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3472 Known = KnownBits::ashr(Known, Known2); 3473 break; 3474 case ISD::FSHL: 3475 case ISD::FSHR: 3476 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3477 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3478 3479 // For fshl, 0-shift returns the 1st arg. 3480 // For fshr, 0-shift returns the 2nd arg. 3481 if (Amt == 0) { 3482 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3483 DemandedElts, Depth + 1); 3484 break; 3485 } 3486 3487 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3488 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3489 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3490 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3491 if (Opcode == ISD::FSHL) { 3492 Known.One <<= Amt; 3493 Known.Zero <<= Amt; 3494 Known2.One.lshrInPlace(BitWidth - Amt); 3495 Known2.Zero.lshrInPlace(BitWidth - Amt); 3496 } else { 3497 Known.One <<= BitWidth - Amt; 3498 Known.Zero <<= BitWidth - Amt; 3499 Known2.One.lshrInPlace(Amt); 3500 Known2.Zero.lshrInPlace(Amt); 3501 } 3502 Known = Known.unionWith(Known2); 3503 } 3504 break; 3505 case ISD::SHL_PARTS: 3506 case ISD::SRA_PARTS: 3507 case ISD::SRL_PARTS: { 3508 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3509 3510 // Collect lo/hi source values and concatenate. 3511 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits(); 3512 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits(); 3513 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3514 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3515 Known = Known2.concat(Known); 3516 3517 // Collect shift amount. 3518 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3519 3520 if (Opcode == ISD::SHL_PARTS) 3521 Known = KnownBits::shl(Known, Known2); 3522 else if (Opcode == ISD::SRA_PARTS) 3523 Known = KnownBits::ashr(Known, Known2); 3524 else // if (Opcode == ISD::SRL_PARTS) 3525 Known = KnownBits::lshr(Known, Known2); 3526 3527 // TODO: Minimum shift low/high bits are known zero. 3528 3529 if (Op.getResNo() == 0) 3530 Known = Known.extractBits(LoBits, 0); 3531 else 3532 Known = Known.extractBits(HiBits, LoBits); 3533 break; 3534 } 3535 case ISD::SIGN_EXTEND_INREG: { 3536 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3537 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3538 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3539 break; 3540 } 3541 case ISD::CTTZ: 3542 case ISD::CTTZ_ZERO_UNDEF: { 3543 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3544 // If we have a known 1, its position is our upper bound. 3545 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3546 unsigned LowBits = llvm::bit_width(PossibleTZ); 3547 Known.Zero.setBitsFrom(LowBits); 3548 break; 3549 } 3550 case ISD::CTLZ: 3551 case ISD::CTLZ_ZERO_UNDEF: { 3552 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3553 // If we have a known 1, its position is our upper bound. 3554 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3555 unsigned LowBits = llvm::bit_width(PossibleLZ); 3556 Known.Zero.setBitsFrom(LowBits); 3557 break; 3558 } 3559 case ISD::CTPOP: { 3560 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3561 // If we know some of the bits are zero, they can't be one. 3562 unsigned PossibleOnes = Known2.countMaxPopulation(); 3563 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes)); 3564 break; 3565 } 3566 case ISD::PARITY: { 3567 // Parity returns 0 everywhere but the LSB. 3568 Known.Zero.setBitsFrom(1); 3569 break; 3570 } 3571 case ISD::LOAD: { 3572 LoadSDNode *LD = cast<LoadSDNode>(Op); 3573 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3574 if (ISD::isNON_EXTLoad(LD) && Cst) { 3575 // Determine any common known bits from the loaded constant pool value. 3576 Type *CstTy = Cst->getType(); 3577 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() && 3578 !Op.getValueType().isScalableVector()) { 3579 // If its a vector splat, then we can (quickly) reuse the scalar path. 3580 // NOTE: We assume all elements match and none are UNDEF. 3581 if (CstTy->isVectorTy()) { 3582 if (const Constant *Splat = Cst->getSplatValue()) { 3583 Cst = Splat; 3584 CstTy = Cst->getType(); 3585 } 3586 } 3587 // TODO - do we need to handle different bitwidths? 3588 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3589 // Iterate across all vector elements finding common known bits. 3590 Known.One.setAllBits(); 3591 Known.Zero.setAllBits(); 3592 for (unsigned i = 0; i != NumElts; ++i) { 3593 if (!DemandedElts[i]) 3594 continue; 3595 if (Constant *Elt = Cst->getAggregateElement(i)) { 3596 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3597 const APInt &Value = CInt->getValue(); 3598 Known.One &= Value; 3599 Known.Zero &= ~Value; 3600 continue; 3601 } 3602 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3603 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3604 Known.One &= Value; 3605 Known.Zero &= ~Value; 3606 continue; 3607 } 3608 } 3609 Known.One.clearAllBits(); 3610 Known.Zero.clearAllBits(); 3611 break; 3612 } 3613 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3614 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3615 Known = KnownBits::makeConstant(CInt->getValue()); 3616 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3617 Known = 3618 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3619 } 3620 } 3621 } 3622 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3623 // If this is a ZEXTLoad and we are looking at the loaded value. 3624 EVT VT = LD->getMemoryVT(); 3625 unsigned MemBits = VT.getScalarSizeInBits(); 3626 Known.Zero.setBitsFrom(MemBits); 3627 } else if (const MDNode *Ranges = LD->getRanges()) { 3628 EVT VT = LD->getValueType(0); 3629 3630 // TODO: Handle for extending loads 3631 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 3632 if (VT.isVector()) { 3633 // Handle truncation to the first demanded element. 3634 // TODO: Figure out which demanded elements are covered 3635 if (DemandedElts != 1 || !getDataLayout().isLittleEndian()) 3636 break; 3637 3638 // Handle the case where a load has a vector type, but scalar memory 3639 // with an attached range. 3640 EVT MemVT = LD->getMemoryVT(); 3641 KnownBits KnownFull(MemVT.getSizeInBits()); 3642 3643 computeKnownBitsFromRangeMetadata(*Ranges, KnownFull); 3644 Known = KnownFull.trunc(BitWidth); 3645 } else 3646 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3647 } 3648 } 3649 break; 3650 } 3651 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3652 if (Op.getValueType().isScalableVector()) 3653 break; 3654 EVT InVT = Op.getOperand(0).getValueType(); 3655 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3656 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3657 Known = Known.zext(BitWidth); 3658 break; 3659 } 3660 case ISD::ZERO_EXTEND: { 3661 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3662 Known = Known.zext(BitWidth); 3663 break; 3664 } 3665 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3666 if (Op.getValueType().isScalableVector()) 3667 break; 3668 EVT InVT = Op.getOperand(0).getValueType(); 3669 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3670 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3671 // If the sign bit is known to be zero or one, then sext will extend 3672 // it to the top bits, else it will just zext. 3673 Known = Known.sext(BitWidth); 3674 break; 3675 } 3676 case ISD::SIGN_EXTEND: { 3677 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3678 // If the sign bit is known to be zero or one, then sext will extend 3679 // it to the top bits, else it will just zext. 3680 Known = Known.sext(BitWidth); 3681 break; 3682 } 3683 case ISD::ANY_EXTEND_VECTOR_INREG: { 3684 if (Op.getValueType().isScalableVector()) 3685 break; 3686 EVT InVT = Op.getOperand(0).getValueType(); 3687 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3688 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3689 Known = Known.anyext(BitWidth); 3690 break; 3691 } 3692 case ISD::ANY_EXTEND: { 3693 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3694 Known = Known.anyext(BitWidth); 3695 break; 3696 } 3697 case ISD::TRUNCATE: { 3698 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3699 Known = Known.trunc(BitWidth); 3700 break; 3701 } 3702 case ISD::AssertZext: { 3703 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3704 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3705 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3706 Known.Zero |= (~InMask); 3707 Known.One &= (~Known.Zero); 3708 break; 3709 } 3710 case ISD::AssertAlign: { 3711 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3712 assert(LogOfAlign != 0); 3713 3714 // TODO: Should use maximum with source 3715 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3716 // well as clearing one bits. 3717 Known.Zero.setLowBits(LogOfAlign); 3718 Known.One.clearLowBits(LogOfAlign); 3719 break; 3720 } 3721 case ISD::FGETSIGN: 3722 // All bits are zero except the low bit. 3723 Known.Zero.setBitsFrom(1); 3724 break; 3725 case ISD::ADD: 3726 case ISD::SUB: { 3727 SDNodeFlags Flags = Op.getNode()->getFlags(); 3728 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3729 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3730 Known = KnownBits::computeForAddSub(Op.getOpcode() == ISD::ADD, 3731 Flags.hasNoSignedWrap(), Known, Known2); 3732 break; 3733 } 3734 case ISD::USUBO: 3735 case ISD::SSUBO: 3736 case ISD::USUBO_CARRY: 3737 case ISD::SSUBO_CARRY: 3738 if (Op.getResNo() == 1) { 3739 // If we know the result of a setcc has the top bits zero, use this info. 3740 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3741 TargetLowering::ZeroOrOneBooleanContent && 3742 BitWidth > 1) 3743 Known.Zero.setBitsFrom(1); 3744 break; 3745 } 3746 [[fallthrough]]; 3747 case ISD::SUBC: { 3748 assert(Op.getResNo() == 0 && 3749 "We only compute knownbits for the difference here."); 3750 3751 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in. 3752 KnownBits Borrow(1); 3753 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) { 3754 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3755 // Borrow has bit width 1 3756 Borrow = Borrow.trunc(1); 3757 } else { 3758 Borrow.setAllZero(); 3759 } 3760 3761 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3762 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3763 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow); 3764 break; 3765 } 3766 case ISD::UADDO: 3767 case ISD::SADDO: 3768 case ISD::UADDO_CARRY: 3769 case ISD::SADDO_CARRY: 3770 if (Op.getResNo() == 1) { 3771 // If we know the result of a setcc has the top bits zero, use this info. 3772 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3773 TargetLowering::ZeroOrOneBooleanContent && 3774 BitWidth > 1) 3775 Known.Zero.setBitsFrom(1); 3776 break; 3777 } 3778 [[fallthrough]]; 3779 case ISD::ADDC: 3780 case ISD::ADDE: { 3781 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3782 3783 // With ADDE and UADDO_CARRY, a carry bit may be added in. 3784 KnownBits Carry(1); 3785 if (Opcode == ISD::ADDE) 3786 // Can't track carry from glue, set carry to unknown. 3787 Carry.resetAll(); 3788 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) { 3789 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3790 // Carry has bit width 1 3791 Carry = Carry.trunc(1); 3792 } else { 3793 Carry.setAllZero(); 3794 } 3795 3796 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3797 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3798 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3799 break; 3800 } 3801 case ISD::UDIV: { 3802 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3803 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3804 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact()); 3805 break; 3806 } 3807 case ISD::SDIV: { 3808 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3809 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3810 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact()); 3811 break; 3812 } 3813 case ISD::SREM: { 3814 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3815 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3816 Known = KnownBits::srem(Known, Known2); 3817 break; 3818 } 3819 case ISD::UREM: { 3820 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3821 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3822 Known = KnownBits::urem(Known, Known2); 3823 break; 3824 } 3825 case ISD::EXTRACT_ELEMENT: { 3826 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3827 const unsigned Index = Op.getConstantOperandVal(1); 3828 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3829 3830 // Remove low part of known bits mask 3831 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3832 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3833 3834 // Remove high part of known bit mask 3835 Known = Known.trunc(EltBitWidth); 3836 break; 3837 } 3838 case ISD::EXTRACT_VECTOR_ELT: { 3839 SDValue InVec = Op.getOperand(0); 3840 SDValue EltNo = Op.getOperand(1); 3841 EVT VecVT = InVec.getValueType(); 3842 // computeKnownBits not yet implemented for scalable vectors. 3843 if (VecVT.isScalableVector()) 3844 break; 3845 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3846 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3847 3848 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3849 // anything about the extended bits. 3850 if (BitWidth > EltBitWidth) 3851 Known = Known.trunc(EltBitWidth); 3852 3853 // If we know the element index, just demand that vector element, else for 3854 // an unknown element index, ignore DemandedElts and demand them all. 3855 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3856 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3857 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3858 DemandedSrcElts = 3859 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3860 3861 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3862 if (BitWidth > EltBitWidth) 3863 Known = Known.anyext(BitWidth); 3864 break; 3865 } 3866 case ISD::INSERT_VECTOR_ELT: { 3867 if (Op.getValueType().isScalableVector()) 3868 break; 3869 3870 // If we know the element index, split the demand between the 3871 // source vector and the inserted element, otherwise assume we need 3872 // the original demanded vector elements and the value. 3873 SDValue InVec = Op.getOperand(0); 3874 SDValue InVal = Op.getOperand(1); 3875 SDValue EltNo = Op.getOperand(2); 3876 bool DemandedVal = true; 3877 APInt DemandedVecElts = DemandedElts; 3878 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3879 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3880 unsigned EltIdx = CEltNo->getZExtValue(); 3881 DemandedVal = !!DemandedElts[EltIdx]; 3882 DemandedVecElts.clearBit(EltIdx); 3883 } 3884 Known.One.setAllBits(); 3885 Known.Zero.setAllBits(); 3886 if (DemandedVal) { 3887 Known2 = computeKnownBits(InVal, Depth + 1); 3888 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth)); 3889 } 3890 if (!!DemandedVecElts) { 3891 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3892 Known = Known.intersectWith(Known2); 3893 } 3894 break; 3895 } 3896 case ISD::BITREVERSE: { 3897 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3898 Known = Known2.reverseBits(); 3899 break; 3900 } 3901 case ISD::BSWAP: { 3902 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3903 Known = Known2.byteSwap(); 3904 break; 3905 } 3906 case ISD::ABS: { 3907 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3908 Known = Known2.abs(); 3909 break; 3910 } 3911 case ISD::USUBSAT: { 3912 // The result of usubsat will never be larger than the LHS. 3913 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3914 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3915 break; 3916 } 3917 case ISD::UMIN: { 3918 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3919 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3920 Known = KnownBits::umin(Known, Known2); 3921 break; 3922 } 3923 case ISD::UMAX: { 3924 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3925 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3926 Known = KnownBits::umax(Known, Known2); 3927 break; 3928 } 3929 case ISD::SMIN: 3930 case ISD::SMAX: { 3931 // If we have a clamp pattern, we know that the number of sign bits will be 3932 // the minimum of the clamp min/max range. 3933 bool IsMax = (Opcode == ISD::SMAX); 3934 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3935 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3936 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3937 CstHigh = 3938 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3939 if (CstLow && CstHigh) { 3940 if (!IsMax) 3941 std::swap(CstLow, CstHigh); 3942 3943 const APInt &ValueLow = CstLow->getAPIntValue(); 3944 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3945 if (ValueLow.sle(ValueHigh)) { 3946 unsigned LowSignBits = ValueLow.getNumSignBits(); 3947 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3948 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3949 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3950 Known.One.setHighBits(MinSignBits); 3951 break; 3952 } 3953 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3954 Known.Zero.setHighBits(MinSignBits); 3955 break; 3956 } 3957 } 3958 } 3959 3960 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3961 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3962 if (IsMax) 3963 Known = KnownBits::smax(Known, Known2); 3964 else 3965 Known = KnownBits::smin(Known, Known2); 3966 3967 // For SMAX, if CstLow is non-negative we know the result will be 3968 // non-negative and thus all sign bits are 0. 3969 // TODO: There's an equivalent of this for smin with negative constant for 3970 // known ones. 3971 if (IsMax && CstLow) { 3972 const APInt &ValueLow = CstLow->getAPIntValue(); 3973 if (ValueLow.isNonNegative()) { 3974 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3975 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits())); 3976 } 3977 } 3978 3979 break; 3980 } 3981 case ISD::FP_TO_UINT_SAT: { 3982 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3983 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3984 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3985 break; 3986 } 3987 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3988 if (Op.getResNo() == 1) { 3989 // The boolean result conforms to getBooleanContents. 3990 // If we know the result of a setcc has the top bits zero, use this info. 3991 // We know that we have an integer-based boolean since these operations 3992 // are only available for integer. 3993 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3994 TargetLowering::ZeroOrOneBooleanContent && 3995 BitWidth > 1) 3996 Known.Zero.setBitsFrom(1); 3997 break; 3998 } 3999 [[fallthrough]]; 4000 case ISD::ATOMIC_CMP_SWAP: 4001 case ISD::ATOMIC_SWAP: 4002 case ISD::ATOMIC_LOAD_ADD: 4003 case ISD::ATOMIC_LOAD_SUB: 4004 case ISD::ATOMIC_LOAD_AND: 4005 case ISD::ATOMIC_LOAD_CLR: 4006 case ISD::ATOMIC_LOAD_OR: 4007 case ISD::ATOMIC_LOAD_XOR: 4008 case ISD::ATOMIC_LOAD_NAND: 4009 case ISD::ATOMIC_LOAD_MIN: 4010 case ISD::ATOMIC_LOAD_MAX: 4011 case ISD::ATOMIC_LOAD_UMIN: 4012 case ISD::ATOMIC_LOAD_UMAX: 4013 case ISD::ATOMIC_LOAD: { 4014 unsigned MemBits = 4015 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4016 // If we are looking at the loaded value. 4017 if (Op.getResNo() == 0) { 4018 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4019 Known.Zero.setBitsFrom(MemBits); 4020 } 4021 break; 4022 } 4023 case ISD::FrameIndex: 4024 case ISD::TargetFrameIndex: 4025 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 4026 Known, getMachineFunction()); 4027 break; 4028 4029 default: 4030 if (Opcode < ISD::BUILTIN_OP_END) 4031 break; 4032 [[fallthrough]]; 4033 case ISD::INTRINSIC_WO_CHAIN: 4034 case ISD::INTRINSIC_W_CHAIN: 4035 case ISD::INTRINSIC_VOID: 4036 // TODO: Probably okay to remove after audit; here to reduce change size 4037 // in initial enablement patch for scalable vectors 4038 if (Op.getValueType().isScalableVector()) 4039 break; 4040 4041 // Allow the target to implement this method for its nodes. 4042 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 4043 break; 4044 } 4045 4046 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 4047 return Known; 4048 } 4049 4050 /// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind. 4051 static SelectionDAG::OverflowKind mapOverflowResult(ConstantRange::OverflowResult OR) { 4052 switch (OR) { 4053 case ConstantRange::OverflowResult::MayOverflow: 4054 return SelectionDAG::OFK_Sometime; 4055 case ConstantRange::OverflowResult::AlwaysOverflowsLow: 4056 case ConstantRange::OverflowResult::AlwaysOverflowsHigh: 4057 return SelectionDAG::OFK_Always; 4058 case ConstantRange::OverflowResult::NeverOverflows: 4059 return SelectionDAG::OFK_Never; 4060 } 4061 llvm_unreachable("Unknown OverflowResult"); 4062 } 4063 4064 SelectionDAG::OverflowKind 4065 SelectionDAG::computeOverflowForSignedAdd(SDValue N0, SDValue N1) const { 4066 // X + 0 never overflow 4067 if (isNullConstant(N1)) 4068 return OFK_Never; 4069 4070 // If both operands each have at least two sign bits, the addition 4071 // cannot overflow. 4072 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1) 4073 return OFK_Never; 4074 4075 // TODO: Add ConstantRange::signedAddMayOverflow handling. 4076 return OFK_Sometime; 4077 } 4078 4079 SelectionDAG::OverflowKind 4080 SelectionDAG::computeOverflowForUnsignedAdd(SDValue N0, SDValue N1) const { 4081 // X + 0 never overflow 4082 if (isNullConstant(N1)) 4083 return OFK_Never; 4084 4085 // mulhi + 1 never overflow 4086 KnownBits N1Known = computeKnownBits(N1); 4087 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 4088 N1Known.getMaxValue().ult(2)) 4089 return OFK_Never; 4090 4091 KnownBits N0Known = computeKnownBits(N0); 4092 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 && 4093 N0Known.getMaxValue().ult(2)) 4094 return OFK_Never; 4095 4096 // Fallback to ConstantRange::unsignedAddMayOverflow handling. 4097 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false); 4098 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false); 4099 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range)); 4100 } 4101 4102 SelectionDAG::OverflowKind 4103 SelectionDAG::computeOverflowForSignedSub(SDValue N0, SDValue N1) const { 4104 // X - 0 never overflow 4105 if (isNullConstant(N1)) 4106 return OFK_Never; 4107 4108 // If both operands each have at least two sign bits, the subtraction 4109 // cannot overflow. 4110 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1) 4111 return OFK_Never; 4112 4113 KnownBits N0Known = computeKnownBits(N0); 4114 KnownBits N1Known = computeKnownBits(N1); 4115 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true); 4116 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true); 4117 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range)); 4118 } 4119 4120 SelectionDAG::OverflowKind 4121 SelectionDAG::computeOverflowForUnsignedSub(SDValue N0, SDValue N1) const { 4122 // X - 0 never overflow 4123 if (isNullConstant(N1)) 4124 return OFK_Never; 4125 4126 KnownBits N0Known = computeKnownBits(N0); 4127 KnownBits N1Known = computeKnownBits(N1); 4128 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false); 4129 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false); 4130 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range)); 4131 } 4132 4133 SelectionDAG::OverflowKind 4134 SelectionDAG::computeOverflowForUnsignedMul(SDValue N0, SDValue N1) const { 4135 // X * 0 and X * 1 never overflow. 4136 if (isNullConstant(N1) || isOneConstant(N1)) 4137 return OFK_Never; 4138 4139 KnownBits N0Known = computeKnownBits(N0); 4140 KnownBits N1Known = computeKnownBits(N1); 4141 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false); 4142 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false); 4143 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range)); 4144 } 4145 4146 SelectionDAG::OverflowKind 4147 SelectionDAG::computeOverflowForSignedMul(SDValue N0, SDValue N1) const { 4148 // X * 0 and X * 1 never overflow. 4149 if (isNullConstant(N1) || isOneConstant(N1)) 4150 return OFK_Never; 4151 4152 // Get the size of the result. 4153 unsigned BitWidth = N0.getScalarValueSizeInBits(); 4154 4155 // Sum of the sign bits. 4156 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1); 4157 4158 // If we have enough sign bits, then there's no overflow. 4159 if (SignBits > BitWidth + 1) 4160 return OFK_Never; 4161 4162 if (SignBits == BitWidth + 1) { 4163 // The overflow occurs when the true multiplication of the 4164 // the operands is the minimum negative number. 4165 KnownBits N0Known = computeKnownBits(N0); 4166 KnownBits N1Known = computeKnownBits(N1); 4167 // If one of the operands is non-negative, then there's no 4168 // overflow. 4169 if (N0Known.isNonNegative() || N1Known.isNonNegative()) 4170 return OFK_Never; 4171 } 4172 4173 return OFK_Sometime; 4174 } 4175 4176 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val, unsigned Depth) const { 4177 if (Depth >= MaxRecursionDepth) 4178 return false; // Limit search depth. 4179 4180 EVT OpVT = Val.getValueType(); 4181 unsigned BitWidth = OpVT.getScalarSizeInBits(); 4182 4183 // Is the constant a known power of 2? 4184 if (ISD::matchUnaryPredicate(Val, [BitWidth](ConstantSDNode *C) { 4185 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 4186 })) 4187 return true; 4188 4189 // A left-shift of a constant one will have exactly one bit set because 4190 // shifting the bit off the end is undefined. 4191 if (Val.getOpcode() == ISD::SHL) { 4192 auto *C = isConstOrConstSplat(Val.getOperand(0)); 4193 if (C && C->getAPIntValue() == 1) 4194 return true; 4195 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1) && 4196 isKnownNeverZero(Val, Depth); 4197 } 4198 4199 // Similarly, a logical right-shift of a constant sign-bit will have exactly 4200 // one bit set. 4201 if (Val.getOpcode() == ISD::SRL) { 4202 auto *C = isConstOrConstSplat(Val.getOperand(0)); 4203 if (C && C->getAPIntValue().isSignMask()) 4204 return true; 4205 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1) && 4206 isKnownNeverZero(Val, Depth); 4207 } 4208 4209 if (Val.getOpcode() == ISD::ROTL || Val.getOpcode() == ISD::ROTR) 4210 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1); 4211 4212 // Are all operands of a build vector constant powers of two? 4213 if (Val.getOpcode() == ISD::BUILD_VECTOR) 4214 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 4215 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 4216 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 4217 return false; 4218 })) 4219 return true; 4220 4221 // Is the operand of a splat vector a constant power of two? 4222 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 4223 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 4224 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 4225 return true; 4226 4227 // vscale(power-of-two) is a power-of-two for some targets 4228 if (Val.getOpcode() == ISD::VSCALE && 4229 getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() && 4230 isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1)) 4231 return true; 4232 4233 if (Val.getOpcode() == ISD::SMIN || Val.getOpcode() == ISD::SMAX || 4234 Val.getOpcode() == ISD::UMIN || Val.getOpcode() == ISD::UMAX) 4235 return isKnownToBeAPowerOfTwo(Val.getOperand(1), Depth + 1) && 4236 isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1); 4237 4238 if (Val.getOpcode() == ISD::SELECT || Val.getOpcode() == ISD::VSELECT) 4239 return isKnownToBeAPowerOfTwo(Val.getOperand(2), Depth + 1) && 4240 isKnownToBeAPowerOfTwo(Val.getOperand(1), Depth + 1); 4241 4242 if (Val.getOpcode() == ISD::AND) { 4243 // Looking for `x & -x` pattern: 4244 // If x == 0: 4245 // x & -x -> 0 4246 // If x != 0: 4247 // x & -x -> non-zero pow2 4248 // so if we find the pattern return whether we know `x` is non-zero. 4249 for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) { 4250 SDValue NegOp = Val.getOperand(OpIdx); 4251 if (NegOp.getOpcode() == ISD::SUB && 4252 NegOp.getOperand(1) == Val.getOperand(1 - OpIdx) && 4253 isNullOrNullSplat(NegOp.getOperand(0))) 4254 return isKnownNeverZero(Val.getOperand(1 - OpIdx), Depth); 4255 } 4256 } 4257 4258 if (Val.getOpcode() == ISD::ZERO_EXTEND) 4259 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1); 4260 4261 // More could be done here, though the above checks are enough 4262 // to handle some common cases. 4263 return false; 4264 } 4265 4266 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 4267 EVT VT = Op.getValueType(); 4268 4269 // Since the number of lanes in a scalable vector is unknown at compile time, 4270 // we track one bit which is implicitly broadcast to all lanes. This means 4271 // that all lanes in a scalable vector are considered demanded. 4272 APInt DemandedElts = VT.isFixedLengthVector() 4273 ? APInt::getAllOnes(VT.getVectorNumElements()) 4274 : APInt(1, 1); 4275 return ComputeNumSignBits(Op, DemandedElts, Depth); 4276 } 4277 4278 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 4279 unsigned Depth) const { 4280 EVT VT = Op.getValueType(); 4281 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 4282 unsigned VTBits = VT.getScalarSizeInBits(); 4283 unsigned NumElts = DemandedElts.getBitWidth(); 4284 unsigned Tmp, Tmp2; 4285 unsigned FirstAnswer = 1; 4286 4287 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 4288 const APInt &Val = C->getAPIntValue(); 4289 return Val.getNumSignBits(); 4290 } 4291 4292 if (Depth >= MaxRecursionDepth) 4293 return 1; // Limit search depth. 4294 4295 if (!DemandedElts) 4296 return 1; // No demanded elts, better to assume we don't know anything. 4297 4298 unsigned Opcode = Op.getOpcode(); 4299 switch (Opcode) { 4300 default: break; 4301 case ISD::AssertSext: 4302 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 4303 return VTBits-Tmp+1; 4304 case ISD::AssertZext: 4305 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 4306 return VTBits-Tmp; 4307 case ISD::MERGE_VALUES: 4308 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts, 4309 Depth + 1); 4310 case ISD::SPLAT_VECTOR: { 4311 // Check if the sign bits of source go down as far as the truncated value. 4312 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits(); 4313 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4314 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4315 return NumSrcSignBits - (NumSrcBits - VTBits); 4316 break; 4317 } 4318 case ISD::BUILD_VECTOR: 4319 assert(!VT.isScalableVector()); 4320 Tmp = VTBits; 4321 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 4322 if (!DemandedElts[i]) 4323 continue; 4324 4325 SDValue SrcOp = Op.getOperand(i); 4326 // BUILD_VECTOR can implicitly truncate sources, we handle this specially 4327 // for constant nodes to ensure we only look at the sign bits. 4328 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SrcOp)) { 4329 APInt T = C->getAPIntValue().trunc(VTBits); 4330 Tmp2 = T.getNumSignBits(); 4331 } else { 4332 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 4333 4334 if (SrcOp.getValueSizeInBits() != VTBits) { 4335 assert(SrcOp.getValueSizeInBits() > VTBits && 4336 "Expected BUILD_VECTOR implicit truncation"); 4337 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 4338 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 4339 } 4340 } 4341 Tmp = std::min(Tmp, Tmp2); 4342 } 4343 return Tmp; 4344 4345 case ISD::VECTOR_SHUFFLE: { 4346 // Collect the minimum number of sign bits that are shared by every vector 4347 // element referenced by the shuffle. 4348 APInt DemandedLHS, DemandedRHS; 4349 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4350 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 4351 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts, 4352 DemandedLHS, DemandedRHS)) 4353 return 1; 4354 4355 Tmp = std::numeric_limits<unsigned>::max(); 4356 if (!!DemandedLHS) 4357 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 4358 if (!!DemandedRHS) { 4359 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 4360 Tmp = std::min(Tmp, Tmp2); 4361 } 4362 // If we don't know anything, early out and try computeKnownBits fall-back. 4363 if (Tmp == 1) 4364 break; 4365 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4366 return Tmp; 4367 } 4368 4369 case ISD::BITCAST: { 4370 if (VT.isScalableVector()) 4371 break; 4372 SDValue N0 = Op.getOperand(0); 4373 EVT SrcVT = N0.getValueType(); 4374 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 4375 4376 // Ignore bitcasts from unsupported types.. 4377 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 4378 break; 4379 4380 // Fast handling of 'identity' bitcasts. 4381 if (VTBits == SrcBits) 4382 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 4383 4384 bool IsLE = getDataLayout().isLittleEndian(); 4385 4386 // Bitcast 'large element' scalar/vector to 'small element' vector. 4387 if ((SrcBits % VTBits) == 0) { 4388 assert(VT.isVector() && "Expected bitcast to vector"); 4389 4390 unsigned Scale = SrcBits / VTBits; 4391 APInt SrcDemandedElts = 4392 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 4393 4394 // Fast case - sign splat can be simply split across the small elements. 4395 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 4396 if (Tmp == SrcBits) 4397 return VTBits; 4398 4399 // Slow case - determine how far the sign extends into each sub-element. 4400 Tmp2 = VTBits; 4401 for (unsigned i = 0; i != NumElts; ++i) 4402 if (DemandedElts[i]) { 4403 unsigned SubOffset = i % Scale; 4404 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 4405 SubOffset = SubOffset * VTBits; 4406 if (Tmp <= SubOffset) 4407 return 1; 4408 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 4409 } 4410 return Tmp2; 4411 } 4412 break; 4413 } 4414 4415 case ISD::FP_TO_SINT_SAT: 4416 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 4417 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4418 return VTBits - Tmp + 1; 4419 case ISD::SIGN_EXTEND: 4420 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 4421 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 4422 case ISD::SIGN_EXTEND_INREG: 4423 // Max of the input and what this extends. 4424 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4425 Tmp = VTBits-Tmp+1; 4426 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4427 return std::max(Tmp, Tmp2); 4428 case ISD::SIGN_EXTEND_VECTOR_INREG: { 4429 if (VT.isScalableVector()) 4430 break; 4431 SDValue Src = Op.getOperand(0); 4432 EVT SrcVT = Src.getValueType(); 4433 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements()); 4434 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4435 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4436 } 4437 case ISD::SRA: 4438 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4439 // SRA X, C -> adds C sign bits. 4440 if (const APInt *ShAmt = 4441 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4442 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4443 return Tmp; 4444 case ISD::SHL: 4445 if (const APInt *ShAmt = 4446 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4447 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4448 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4449 if (ShAmt->ult(Tmp)) 4450 return Tmp - ShAmt->getZExtValue(); 4451 } 4452 break; 4453 case ISD::AND: 4454 case ISD::OR: 4455 case ISD::XOR: // NOT is handled here. 4456 // Logical binary ops preserve the number of sign bits at the worst. 4457 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4458 if (Tmp != 1) { 4459 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4460 FirstAnswer = std::min(Tmp, Tmp2); 4461 // We computed what we know about the sign bits as our first 4462 // answer. Now proceed to the generic code that uses 4463 // computeKnownBits, and pick whichever answer is better. 4464 } 4465 break; 4466 4467 case ISD::SELECT: 4468 case ISD::VSELECT: 4469 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4470 if (Tmp == 1) return 1; // Early out. 4471 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4472 return std::min(Tmp, Tmp2); 4473 case ISD::SELECT_CC: 4474 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4475 if (Tmp == 1) return 1; // Early out. 4476 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4477 return std::min(Tmp, Tmp2); 4478 4479 case ISD::SMIN: 4480 case ISD::SMAX: { 4481 // If we have a clamp pattern, we know that the number of sign bits will be 4482 // the minimum of the clamp min/max range. 4483 bool IsMax = (Opcode == ISD::SMAX); 4484 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4485 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4486 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4487 CstHigh = 4488 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4489 if (CstLow && CstHigh) { 4490 if (!IsMax) 4491 std::swap(CstLow, CstHigh); 4492 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4493 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4494 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4495 return std::min(Tmp, Tmp2); 4496 } 4497 } 4498 4499 // Fallback - just get the minimum number of sign bits of the operands. 4500 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4501 if (Tmp == 1) 4502 return 1; // Early out. 4503 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4504 return std::min(Tmp, Tmp2); 4505 } 4506 case ISD::UMIN: 4507 case ISD::UMAX: 4508 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4509 if (Tmp == 1) 4510 return 1; // Early out. 4511 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4512 return std::min(Tmp, Tmp2); 4513 case ISD::SADDO: 4514 case ISD::UADDO: 4515 case ISD::SADDO_CARRY: 4516 case ISD::UADDO_CARRY: 4517 case ISD::SSUBO: 4518 case ISD::USUBO: 4519 case ISD::SSUBO_CARRY: 4520 case ISD::USUBO_CARRY: 4521 case ISD::SMULO: 4522 case ISD::UMULO: 4523 if (Op.getResNo() != 1) 4524 break; 4525 // The boolean result conforms to getBooleanContents. Fall through. 4526 // If setcc returns 0/-1, all bits are sign bits. 4527 // We know that we have an integer-based boolean since these operations 4528 // are only available for integer. 4529 if (TLI->getBooleanContents(VT.isVector(), false) == 4530 TargetLowering::ZeroOrNegativeOneBooleanContent) 4531 return VTBits; 4532 break; 4533 case ISD::SETCC: 4534 case ISD::SETCCCARRY: 4535 case ISD::STRICT_FSETCC: 4536 case ISD::STRICT_FSETCCS: { 4537 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4538 // If setcc returns 0/-1, all bits are sign bits. 4539 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4540 TargetLowering::ZeroOrNegativeOneBooleanContent) 4541 return VTBits; 4542 break; 4543 } 4544 case ISD::ROTL: 4545 case ISD::ROTR: 4546 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4547 4548 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4549 if (Tmp == VTBits) 4550 return VTBits; 4551 4552 if (ConstantSDNode *C = 4553 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4554 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4555 4556 // Handle rotate right by N like a rotate left by 32-N. 4557 if (Opcode == ISD::ROTR) 4558 RotAmt = (VTBits - RotAmt) % VTBits; 4559 4560 // If we aren't rotating out all of the known-in sign bits, return the 4561 // number that are left. This handles rotl(sext(x), 1) for example. 4562 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4563 } 4564 break; 4565 case ISD::ADD: 4566 case ISD::ADDC: 4567 // Add can have at most one carry bit. Thus we know that the output 4568 // is, at worst, one more bit than the inputs. 4569 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4570 if (Tmp == 1) return 1; // Early out. 4571 4572 // Special case decrementing a value (ADD X, -1): 4573 if (ConstantSDNode *CRHS = 4574 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4575 if (CRHS->isAllOnes()) { 4576 KnownBits Known = 4577 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4578 4579 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4580 // sign bits set. 4581 if ((Known.Zero | 1).isAllOnes()) 4582 return VTBits; 4583 4584 // If we are subtracting one from a positive number, there is no carry 4585 // out of the result. 4586 if (Known.isNonNegative()) 4587 return Tmp; 4588 } 4589 4590 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4591 if (Tmp2 == 1) return 1; // Early out. 4592 return std::min(Tmp, Tmp2) - 1; 4593 case ISD::SUB: 4594 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4595 if (Tmp2 == 1) return 1; // Early out. 4596 4597 // Handle NEG. 4598 if (ConstantSDNode *CLHS = 4599 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4600 if (CLHS->isZero()) { 4601 KnownBits Known = 4602 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4603 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4604 // sign bits set. 4605 if ((Known.Zero | 1).isAllOnes()) 4606 return VTBits; 4607 4608 // If the input is known to be positive (the sign bit is known clear), 4609 // the output of the NEG has the same number of sign bits as the input. 4610 if (Known.isNonNegative()) 4611 return Tmp2; 4612 4613 // Otherwise, we treat this like a SUB. 4614 } 4615 4616 // Sub can have at most one carry bit. Thus we know that the output 4617 // is, at worst, one more bit than the inputs. 4618 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4619 if (Tmp == 1) return 1; // Early out. 4620 return std::min(Tmp, Tmp2) - 1; 4621 case ISD::MUL: { 4622 // The output of the Mul can be at most twice the valid bits in the inputs. 4623 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4624 if (SignBitsOp0 == 1) 4625 break; 4626 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4627 if (SignBitsOp1 == 1) 4628 break; 4629 unsigned OutValidBits = 4630 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4631 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4632 } 4633 case ISD::SREM: 4634 // The sign bit is the LHS's sign bit, except when the result of the 4635 // remainder is zero. The magnitude of the result should be less than or 4636 // equal to the magnitude of the LHS. Therefore, the result should have 4637 // at least as many sign bits as the left hand side. 4638 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4639 case ISD::TRUNCATE: { 4640 // Check if the sign bits of source go down as far as the truncated value. 4641 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4642 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4643 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4644 return NumSrcSignBits - (NumSrcBits - VTBits); 4645 break; 4646 } 4647 case ISD::EXTRACT_ELEMENT: { 4648 if (VT.isScalableVector()) 4649 break; 4650 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4651 const int BitWidth = Op.getValueSizeInBits(); 4652 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4653 4654 // Get reverse index (starting from 1), Op1 value indexes elements from 4655 // little end. Sign starts at big end. 4656 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4657 4658 // If the sign portion ends in our element the subtraction gives correct 4659 // result. Otherwise it gives either negative or > bitwidth result 4660 return std::clamp(KnownSign - rIndex * BitWidth, 0, BitWidth); 4661 } 4662 case ISD::INSERT_VECTOR_ELT: { 4663 if (VT.isScalableVector()) 4664 break; 4665 // If we know the element index, split the demand between the 4666 // source vector and the inserted element, otherwise assume we need 4667 // the original demanded vector elements and the value. 4668 SDValue InVec = Op.getOperand(0); 4669 SDValue InVal = Op.getOperand(1); 4670 SDValue EltNo = Op.getOperand(2); 4671 bool DemandedVal = true; 4672 APInt DemandedVecElts = DemandedElts; 4673 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4674 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4675 unsigned EltIdx = CEltNo->getZExtValue(); 4676 DemandedVal = !!DemandedElts[EltIdx]; 4677 DemandedVecElts.clearBit(EltIdx); 4678 } 4679 Tmp = std::numeric_limits<unsigned>::max(); 4680 if (DemandedVal) { 4681 // TODO - handle implicit truncation of inserted elements. 4682 if (InVal.getScalarValueSizeInBits() != VTBits) 4683 break; 4684 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4685 Tmp = std::min(Tmp, Tmp2); 4686 } 4687 if (!!DemandedVecElts) { 4688 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4689 Tmp = std::min(Tmp, Tmp2); 4690 } 4691 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4692 return Tmp; 4693 } 4694 case ISD::EXTRACT_VECTOR_ELT: { 4695 assert(!VT.isScalableVector()); 4696 SDValue InVec = Op.getOperand(0); 4697 SDValue EltNo = Op.getOperand(1); 4698 EVT VecVT = InVec.getValueType(); 4699 // ComputeNumSignBits not yet implemented for scalable vectors. 4700 if (VecVT.isScalableVector()) 4701 break; 4702 const unsigned BitWidth = Op.getValueSizeInBits(); 4703 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4704 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4705 4706 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4707 // anything about sign bits. But if the sizes match we can derive knowledge 4708 // about sign bits from the vector operand. 4709 if (BitWidth != EltBitWidth) 4710 break; 4711 4712 // If we know the element index, just demand that vector element, else for 4713 // an unknown element index, ignore DemandedElts and demand them all. 4714 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4715 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4716 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4717 DemandedSrcElts = 4718 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4719 4720 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4721 } 4722 case ISD::EXTRACT_SUBVECTOR: { 4723 // Offset the demanded elts by the subvector index. 4724 SDValue Src = Op.getOperand(0); 4725 // Bail until we can represent demanded elements for scalable vectors. 4726 if (Src.getValueType().isScalableVector()) 4727 break; 4728 uint64_t Idx = Op.getConstantOperandVal(1); 4729 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4730 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 4731 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4732 } 4733 case ISD::CONCAT_VECTORS: { 4734 if (VT.isScalableVector()) 4735 break; 4736 // Determine the minimum number of sign bits across all demanded 4737 // elts of the input vectors. Early out if the result is already 1. 4738 Tmp = std::numeric_limits<unsigned>::max(); 4739 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4740 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4741 unsigned NumSubVectors = Op.getNumOperands(); 4742 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4743 APInt DemandedSub = 4744 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4745 if (!DemandedSub) 4746 continue; 4747 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4748 Tmp = std::min(Tmp, Tmp2); 4749 } 4750 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4751 return Tmp; 4752 } 4753 case ISD::INSERT_SUBVECTOR: { 4754 if (VT.isScalableVector()) 4755 break; 4756 // Demand any elements from the subvector and the remainder from the src its 4757 // inserted into. 4758 SDValue Src = Op.getOperand(0); 4759 SDValue Sub = Op.getOperand(1); 4760 uint64_t Idx = Op.getConstantOperandVal(2); 4761 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4762 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4763 APInt DemandedSrcElts = DemandedElts; 4764 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4765 4766 Tmp = std::numeric_limits<unsigned>::max(); 4767 if (!!DemandedSubElts) { 4768 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4769 if (Tmp == 1) 4770 return 1; // early-out 4771 } 4772 if (!!DemandedSrcElts) { 4773 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4774 Tmp = std::min(Tmp, Tmp2); 4775 } 4776 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4777 return Tmp; 4778 } 4779 case ISD::LOAD: { 4780 LoadSDNode *LD = cast<LoadSDNode>(Op); 4781 if (const MDNode *Ranges = LD->getRanges()) { 4782 if (DemandedElts != 1) 4783 break; 4784 4785 ConstantRange CR = getConstantRangeFromMetadata(*Ranges); 4786 if (VTBits > CR.getBitWidth()) { 4787 switch (LD->getExtensionType()) { 4788 case ISD::SEXTLOAD: 4789 CR = CR.signExtend(VTBits); 4790 break; 4791 case ISD::ZEXTLOAD: 4792 CR = CR.zeroExtend(VTBits); 4793 break; 4794 default: 4795 break; 4796 } 4797 } 4798 4799 if (VTBits != CR.getBitWidth()) 4800 break; 4801 return std::min(CR.getSignedMin().getNumSignBits(), 4802 CR.getSignedMax().getNumSignBits()); 4803 } 4804 4805 break; 4806 } 4807 case ISD::ATOMIC_CMP_SWAP: 4808 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4809 case ISD::ATOMIC_SWAP: 4810 case ISD::ATOMIC_LOAD_ADD: 4811 case ISD::ATOMIC_LOAD_SUB: 4812 case ISD::ATOMIC_LOAD_AND: 4813 case ISD::ATOMIC_LOAD_CLR: 4814 case ISD::ATOMIC_LOAD_OR: 4815 case ISD::ATOMIC_LOAD_XOR: 4816 case ISD::ATOMIC_LOAD_NAND: 4817 case ISD::ATOMIC_LOAD_MIN: 4818 case ISD::ATOMIC_LOAD_MAX: 4819 case ISD::ATOMIC_LOAD_UMIN: 4820 case ISD::ATOMIC_LOAD_UMAX: 4821 case ISD::ATOMIC_LOAD: { 4822 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4823 // If we are looking at the loaded value. 4824 if (Op.getResNo() == 0) { 4825 if (Tmp == VTBits) 4826 return 1; // early-out 4827 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4828 return VTBits - Tmp + 1; 4829 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4830 return VTBits - Tmp; 4831 } 4832 break; 4833 } 4834 } 4835 4836 // If we are looking at the loaded value of the SDNode. 4837 if (Op.getResNo() == 0) { 4838 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4839 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4840 unsigned ExtType = LD->getExtensionType(); 4841 switch (ExtType) { 4842 default: break; 4843 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4844 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4845 return VTBits - Tmp + 1; 4846 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4847 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4848 return VTBits - Tmp; 4849 case ISD::NON_EXTLOAD: 4850 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4851 // We only need to handle vectors - computeKnownBits should handle 4852 // scalar cases. 4853 Type *CstTy = Cst->getType(); 4854 if (CstTy->isVectorTy() && !VT.isScalableVector() && 4855 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4856 VTBits == CstTy->getScalarSizeInBits()) { 4857 Tmp = VTBits; 4858 for (unsigned i = 0; i != NumElts; ++i) { 4859 if (!DemandedElts[i]) 4860 continue; 4861 if (Constant *Elt = Cst->getAggregateElement(i)) { 4862 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4863 const APInt &Value = CInt->getValue(); 4864 Tmp = std::min(Tmp, Value.getNumSignBits()); 4865 continue; 4866 } 4867 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4868 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4869 Tmp = std::min(Tmp, Value.getNumSignBits()); 4870 continue; 4871 } 4872 } 4873 // Unknown type. Conservatively assume no bits match sign bit. 4874 return 1; 4875 } 4876 return Tmp; 4877 } 4878 } 4879 break; 4880 } 4881 } 4882 } 4883 4884 // Allow the target to implement this method for its nodes. 4885 if (Opcode >= ISD::BUILTIN_OP_END || 4886 Opcode == ISD::INTRINSIC_WO_CHAIN || 4887 Opcode == ISD::INTRINSIC_W_CHAIN || 4888 Opcode == ISD::INTRINSIC_VOID) { 4889 // TODO: This can probably be removed once target code is audited. This 4890 // is here purely to reduce patch size and review complexity. 4891 if (!VT.isScalableVector()) { 4892 unsigned NumBits = 4893 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4894 if (NumBits > 1) 4895 FirstAnswer = std::max(FirstAnswer, NumBits); 4896 } 4897 } 4898 4899 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4900 // use this information. 4901 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4902 return std::max(FirstAnswer, Known.countMinSignBits()); 4903 } 4904 4905 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4906 unsigned Depth) const { 4907 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4908 return Op.getScalarValueSizeInBits() - SignBits + 1; 4909 } 4910 4911 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4912 const APInt &DemandedElts, 4913 unsigned Depth) const { 4914 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4915 return Op.getScalarValueSizeInBits() - SignBits + 1; 4916 } 4917 4918 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4919 unsigned Depth) const { 4920 // Early out for FREEZE. 4921 if (Op.getOpcode() == ISD::FREEZE) 4922 return true; 4923 4924 // TODO: Assume we don't know anything for now. 4925 EVT VT = Op.getValueType(); 4926 if (VT.isScalableVector()) 4927 return false; 4928 4929 APInt DemandedElts = VT.isVector() 4930 ? APInt::getAllOnes(VT.getVectorNumElements()) 4931 : APInt(1, 1); 4932 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4933 } 4934 4935 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4936 const APInt &DemandedElts, 4937 bool PoisonOnly, 4938 unsigned Depth) const { 4939 unsigned Opcode = Op.getOpcode(); 4940 4941 // Early out for FREEZE. 4942 if (Opcode == ISD::FREEZE) 4943 return true; 4944 4945 if (Depth >= MaxRecursionDepth) 4946 return false; // Limit search depth. 4947 4948 if (isIntOrFPConstant(Op)) 4949 return true; 4950 4951 switch (Opcode) { 4952 case ISD::VALUETYPE: 4953 case ISD::FrameIndex: 4954 case ISD::TargetFrameIndex: 4955 return true; 4956 4957 case ISD::UNDEF: 4958 return PoisonOnly; 4959 4960 case ISD::BUILD_VECTOR: 4961 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4962 // this shouldn't affect the result. 4963 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4964 if (!DemandedElts[i]) 4965 continue; 4966 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4967 Depth + 1)) 4968 return false; 4969 } 4970 return true; 4971 4972 // TODO: Search for noundef attributes from library functions. 4973 4974 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4975 4976 default: 4977 // Allow the target to implement this method for its nodes. 4978 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4979 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4980 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4981 Op, DemandedElts, *this, PoisonOnly, Depth); 4982 break; 4983 } 4984 4985 // If Op can't create undef/poison and none of its operands are undef/poison 4986 // then Op is never undef/poison. 4987 // NOTE: TargetNodes should handle this in themselves in 4988 // isGuaranteedNotToBeUndefOrPoisonForTargetNode. 4989 return !canCreateUndefOrPoison(Op, PoisonOnly, /*ConsiderFlags*/ true, 4990 Depth) && 4991 all_of(Op->ops(), [&](SDValue V) { 4992 return isGuaranteedNotToBeUndefOrPoison(V, PoisonOnly, Depth + 1); 4993 }); 4994 } 4995 4996 bool SelectionDAG::canCreateUndefOrPoison(SDValue Op, bool PoisonOnly, 4997 bool ConsiderFlags, 4998 unsigned Depth) const { 4999 // TODO: Assume we don't know anything for now. 5000 EVT VT = Op.getValueType(); 5001 if (VT.isScalableVector()) 5002 return true; 5003 5004 APInt DemandedElts = VT.isVector() 5005 ? APInt::getAllOnes(VT.getVectorNumElements()) 5006 : APInt(1, 1); 5007 return canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly, ConsiderFlags, 5008 Depth); 5009 } 5010 5011 bool SelectionDAG::canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts, 5012 bool PoisonOnly, bool ConsiderFlags, 5013 unsigned Depth) const { 5014 // TODO: Assume we don't know anything for now. 5015 EVT VT = Op.getValueType(); 5016 if (VT.isScalableVector()) 5017 return true; 5018 5019 unsigned Opcode = Op.getOpcode(); 5020 switch (Opcode) { 5021 case ISD::FREEZE: 5022 case ISD::CONCAT_VECTORS: 5023 case ISD::INSERT_SUBVECTOR: 5024 case ISD::AND: 5025 case ISD::XOR: 5026 case ISD::ROTL: 5027 case ISD::ROTR: 5028 case ISD::FSHL: 5029 case ISD::FSHR: 5030 case ISD::BSWAP: 5031 case ISD::CTPOP: 5032 case ISD::BITREVERSE: 5033 case ISD::PARITY: 5034 case ISD::SIGN_EXTEND: 5035 case ISD::TRUNCATE: 5036 case ISD::SIGN_EXTEND_INREG: 5037 case ISD::SIGN_EXTEND_VECTOR_INREG: 5038 case ISD::ZERO_EXTEND_VECTOR_INREG: 5039 case ISD::BITCAST: 5040 case ISD::BUILD_VECTOR: 5041 case ISD::BUILD_PAIR: 5042 return false; 5043 5044 // Matches hasPoisonGeneratingFlags(). 5045 case ISD::ZERO_EXTEND: 5046 return ConsiderFlags && Op->getFlags().hasNonNeg(); 5047 5048 case ISD::ADD: 5049 case ISD::SUB: 5050 case ISD::MUL: 5051 // Matches hasPoisonGeneratingFlags(). 5052 return ConsiderFlags && (Op->getFlags().hasNoSignedWrap() || 5053 Op->getFlags().hasNoUnsignedWrap()); 5054 5055 case ISD::SHL: 5056 // If the max shift amount isn't in range, then the shift can create poison. 5057 if (!getValidMaximumShiftAmountConstant(Op, DemandedElts)) 5058 return true; 5059 5060 // Matches hasPoisonGeneratingFlags(). 5061 return ConsiderFlags && (Op->getFlags().hasNoSignedWrap() || 5062 Op->getFlags().hasNoUnsignedWrap()); 5063 5064 // Matches hasPoisonGeneratingFlags(). 5065 case ISD::OR: 5066 return ConsiderFlags && Op->getFlags().hasDisjoint(); 5067 5068 case ISD::INSERT_VECTOR_ELT:{ 5069 // Ensure that the element index is in bounds. 5070 EVT VecVT = Op.getOperand(0).getValueType(); 5071 KnownBits KnownIdx = computeKnownBits(Op.getOperand(2), Depth + 1); 5072 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements()); 5073 } 5074 5075 default: 5076 // Allow the target to implement this method for its nodes. 5077 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 5078 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 5079 return TLI->canCreateUndefOrPoisonForTargetNode( 5080 Op, DemandedElts, *this, PoisonOnly, ConsiderFlags, Depth); 5081 break; 5082 } 5083 5084 // Be conservative and return true. 5085 return true; 5086 } 5087 5088 bool SelectionDAG::isADDLike(SDValue Op) const { 5089 unsigned Opcode = Op.getOpcode(); 5090 if (Opcode == ISD::OR) 5091 return Op->getFlags().hasDisjoint() || 5092 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1)); 5093 if (Opcode == ISD::XOR) 5094 return isMinSignedConstant(Op.getOperand(1)); 5095 return false; 5096 } 5097 5098 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 5099 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 5100 !isa<ConstantSDNode>(Op.getOperand(1))) 5101 return false; 5102 5103 if (Op.getOpcode() == ISD::OR && 5104 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 5105 return false; 5106 5107 return true; 5108 } 5109 5110 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 5111 // If we're told that NaNs won't happen, assume they won't. 5112 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 5113 return true; 5114 5115 if (Depth >= MaxRecursionDepth) 5116 return false; // Limit search depth. 5117 5118 // If the value is a constant, we can obviously see if it is a NaN or not. 5119 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 5120 return !C->getValueAPF().isNaN() || 5121 (SNaN && !C->getValueAPF().isSignaling()); 5122 } 5123 5124 unsigned Opcode = Op.getOpcode(); 5125 switch (Opcode) { 5126 case ISD::FADD: 5127 case ISD::FSUB: 5128 case ISD::FMUL: 5129 case ISD::FDIV: 5130 case ISD::FREM: 5131 case ISD::FSIN: 5132 case ISD::FCOS: 5133 case ISD::FMA: 5134 case ISD::FMAD: { 5135 if (SNaN) 5136 return true; 5137 // TODO: Need isKnownNeverInfinity 5138 return false; 5139 } 5140 case ISD::FCANONICALIZE: 5141 case ISD::FEXP: 5142 case ISD::FEXP2: 5143 case ISD::FEXP10: 5144 case ISD::FTRUNC: 5145 case ISD::FFLOOR: 5146 case ISD::FCEIL: 5147 case ISD::FROUND: 5148 case ISD::FROUNDEVEN: 5149 case ISD::FRINT: 5150 case ISD::LRINT: 5151 case ISD::LLRINT: 5152 case ISD::FNEARBYINT: 5153 case ISD::FLDEXP: { 5154 if (SNaN) 5155 return true; 5156 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 5157 } 5158 case ISD::FABS: 5159 case ISD::FNEG: 5160 case ISD::FCOPYSIGN: { 5161 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 5162 } 5163 case ISD::SELECT: 5164 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 5165 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 5166 case ISD::FP_EXTEND: 5167 case ISD::FP_ROUND: { 5168 if (SNaN) 5169 return true; 5170 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 5171 } 5172 case ISD::SINT_TO_FP: 5173 case ISD::UINT_TO_FP: 5174 return true; 5175 case ISD::FSQRT: // Need is known positive 5176 case ISD::FLOG: 5177 case ISD::FLOG2: 5178 case ISD::FLOG10: 5179 case ISD::FPOWI: 5180 case ISD::FPOW: { 5181 if (SNaN) 5182 return true; 5183 // TODO: Refine on operand 5184 return false; 5185 } 5186 case ISD::FMINNUM: 5187 case ISD::FMAXNUM: { 5188 // Only one needs to be known not-nan, since it will be returned if the 5189 // other ends up being one. 5190 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 5191 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 5192 } 5193 case ISD::FMINNUM_IEEE: 5194 case ISD::FMAXNUM_IEEE: { 5195 if (SNaN) 5196 return true; 5197 // This can return a NaN if either operand is an sNaN, or if both operands 5198 // are NaN. 5199 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 5200 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 5201 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 5202 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 5203 } 5204 case ISD::FMINIMUM: 5205 case ISD::FMAXIMUM: { 5206 // TODO: Does this quiet or return the origina NaN as-is? 5207 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 5208 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 5209 } 5210 case ISD::EXTRACT_VECTOR_ELT: { 5211 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 5212 } 5213 case ISD::BUILD_VECTOR: { 5214 for (const SDValue &Opnd : Op->ops()) 5215 if (!isKnownNeverNaN(Opnd, SNaN, Depth + 1)) 5216 return false; 5217 return true; 5218 } 5219 default: 5220 if (Opcode >= ISD::BUILTIN_OP_END || 5221 Opcode == ISD::INTRINSIC_WO_CHAIN || 5222 Opcode == ISD::INTRINSIC_W_CHAIN || 5223 Opcode == ISD::INTRINSIC_VOID) { 5224 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 5225 } 5226 5227 return false; 5228 } 5229 } 5230 5231 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 5232 assert(Op.getValueType().isFloatingPoint() && 5233 "Floating point type expected"); 5234 5235 // If the value is a constant, we can obviously see if it is a zero or not. 5236 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 5237 return !C->isZero(); 5238 5239 // Return false if we find any zero in a vector. 5240 if (Op->getOpcode() == ISD::BUILD_VECTOR || 5241 Op->getOpcode() == ISD::SPLAT_VECTOR) { 5242 for (const SDValue &OpVal : Op->op_values()) { 5243 if (OpVal.isUndef()) 5244 return false; 5245 if (auto *C = dyn_cast<ConstantFPSDNode>(OpVal)) 5246 if (C->isZero()) 5247 return false; 5248 } 5249 return true; 5250 } 5251 return false; 5252 } 5253 5254 bool SelectionDAG::isKnownNeverZero(SDValue Op, unsigned Depth) const { 5255 if (Depth >= MaxRecursionDepth) 5256 return false; // Limit search depth. 5257 5258 assert(!Op.getValueType().isFloatingPoint() && 5259 "Floating point types unsupported - use isKnownNeverZeroFloat"); 5260 5261 // If the value is a constant, we can obviously see if it is a zero or not. 5262 if (ISD::matchUnaryPredicate(Op, 5263 [](ConstantSDNode *C) { return !C->isZero(); })) 5264 return true; 5265 5266 // TODO: Recognize more cases here. Most of the cases are also incomplete to 5267 // some degree. 5268 switch (Op.getOpcode()) { 5269 default: 5270 break; 5271 5272 case ISD::OR: 5273 return isKnownNeverZero(Op.getOperand(1), Depth + 1) || 5274 isKnownNeverZero(Op.getOperand(0), Depth + 1); 5275 5276 case ISD::VSELECT: 5277 case ISD::SELECT: 5278 return isKnownNeverZero(Op.getOperand(1), Depth + 1) && 5279 isKnownNeverZero(Op.getOperand(2), Depth + 1); 5280 5281 case ISD::SHL: { 5282 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap()) 5283 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5284 KnownBits ValKnown = computeKnownBits(Op.getOperand(0), Depth + 1); 5285 // 1 << X is never zero. 5286 if (ValKnown.One[0]) 5287 return true; 5288 // If max shift cnt of known ones is non-zero, result is non-zero. 5289 APInt MaxCnt = computeKnownBits(Op.getOperand(1), Depth + 1).getMaxValue(); 5290 if (MaxCnt.ult(ValKnown.getBitWidth()) && 5291 !ValKnown.One.shl(MaxCnt).isZero()) 5292 return true; 5293 break; 5294 } 5295 case ISD::UADDSAT: 5296 case ISD::UMAX: 5297 return isKnownNeverZero(Op.getOperand(1), Depth + 1) || 5298 isKnownNeverZero(Op.getOperand(0), Depth + 1); 5299 5300 // TODO for smin/smax: If either operand is known negative/positive 5301 // respectively we don't need the other to be known at all. 5302 case ISD::SMAX: 5303 case ISD::SMIN: 5304 case ISD::UMIN: 5305 return isKnownNeverZero(Op.getOperand(1), Depth + 1) && 5306 isKnownNeverZero(Op.getOperand(0), Depth + 1); 5307 5308 case ISD::ROTL: 5309 case ISD::ROTR: 5310 case ISD::BITREVERSE: 5311 case ISD::BSWAP: 5312 case ISD::CTPOP: 5313 case ISD::ABS: 5314 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5315 5316 case ISD::SRA: 5317 case ISD::SRL: { 5318 if (Op->getFlags().hasExact()) 5319 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5320 KnownBits ValKnown = computeKnownBits(Op.getOperand(0), Depth + 1); 5321 if (ValKnown.isNegative()) 5322 return true; 5323 // If max shift cnt of known ones is non-zero, result is non-zero. 5324 APInt MaxCnt = computeKnownBits(Op.getOperand(1), Depth + 1).getMaxValue(); 5325 if (MaxCnt.ult(ValKnown.getBitWidth()) && 5326 !ValKnown.One.lshr(MaxCnt).isZero()) 5327 return true; 5328 break; 5329 } 5330 case ISD::UDIV: 5331 case ISD::SDIV: 5332 // div exact can only produce a zero if the dividend is zero. 5333 // TODO: For udiv this is also true if Op1 u<= Op0 5334 if (Op->getFlags().hasExact()) 5335 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5336 break; 5337 5338 case ISD::ADD: 5339 if (Op->getFlags().hasNoUnsignedWrap()) 5340 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) || 5341 isKnownNeverZero(Op.getOperand(0), Depth + 1)) 5342 return true; 5343 // TODO: There are a lot more cases we can prove for add. 5344 break; 5345 5346 case ISD::SUB: { 5347 if (isNullConstant(Op.getOperand(0))) 5348 return isKnownNeverZero(Op.getOperand(1), Depth + 1); 5349 5350 std::optional<bool> ne = 5351 KnownBits::ne(computeKnownBits(Op.getOperand(0), Depth + 1), 5352 computeKnownBits(Op.getOperand(1), Depth + 1)); 5353 return ne && *ne; 5354 } 5355 5356 case ISD::MUL: 5357 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap()) 5358 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) && 5359 isKnownNeverZero(Op.getOperand(0), Depth + 1)) 5360 return true; 5361 break; 5362 5363 case ISD::ZERO_EXTEND: 5364 case ISD::SIGN_EXTEND: 5365 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5366 } 5367 5368 return computeKnownBits(Op, Depth).isNonZero(); 5369 } 5370 5371 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 5372 // Check the obvious case. 5373 if (A == B) return true; 5374 5375 // For negative and positive zero. 5376 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 5377 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 5378 if (CA->isZero() && CB->isZero()) return true; 5379 5380 // Otherwise they may not be equal. 5381 return false; 5382 } 5383 5384 // Only bits set in Mask must be negated, other bits may be arbitrary. 5385 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) { 5386 if (isBitwiseNot(V, AllowUndefs)) 5387 return V.getOperand(0); 5388 5389 // Handle any_extend (not (truncate X)) pattern, where Mask only sets 5390 // bits in the non-extended part. 5391 ConstantSDNode *MaskC = isConstOrConstSplat(Mask); 5392 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND) 5393 return SDValue(); 5394 SDValue ExtArg = V.getOperand(0); 5395 if (ExtArg.getScalarValueSizeInBits() >= 5396 MaskC->getAPIntValue().getActiveBits() && 5397 isBitwiseNot(ExtArg, AllowUndefs) && 5398 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE && 5399 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType()) 5400 return ExtArg.getOperand(0).getOperand(0); 5401 return SDValue(); 5402 } 5403 5404 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) { 5405 // Match masked merge pattern (X & ~M) op (Y & M) 5406 // Including degenerate case (X & ~M) op M 5407 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask, 5408 SDValue Other) { 5409 if (SDValue NotOperand = 5410 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) { 5411 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND || 5412 NotOperand->getOpcode() == ISD::TRUNCATE) 5413 NotOperand = NotOperand->getOperand(0); 5414 5415 if (Other == NotOperand) 5416 return true; 5417 if (Other->getOpcode() == ISD::AND) 5418 return NotOperand == Other->getOperand(0) || 5419 NotOperand == Other->getOperand(1); 5420 } 5421 return false; 5422 }; 5423 5424 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE) 5425 A = A->getOperand(0); 5426 5427 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE) 5428 B = B->getOperand(0); 5429 5430 if (A->getOpcode() == ISD::AND) 5431 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) || 5432 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B); 5433 return false; 5434 } 5435 5436 // FIXME: unify with llvm::haveNoCommonBitsSet. 5437 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 5438 assert(A.getValueType() == B.getValueType() && 5439 "Values must have the same type"); 5440 if (haveNoCommonBitsSetCommutative(A, B) || 5441 haveNoCommonBitsSetCommutative(B, A)) 5442 return true; 5443 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 5444 computeKnownBits(B)); 5445 } 5446 5447 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 5448 SelectionDAG &DAG) { 5449 if (cast<ConstantSDNode>(Step)->isZero()) 5450 return DAG.getConstant(0, DL, VT); 5451 5452 return SDValue(); 5453 } 5454 5455 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 5456 ArrayRef<SDValue> Ops, 5457 SelectionDAG &DAG) { 5458 int NumOps = Ops.size(); 5459 assert(NumOps != 0 && "Can't build an empty vector!"); 5460 assert(!VT.isScalableVector() && 5461 "BUILD_VECTOR cannot be used with scalable types"); 5462 assert(VT.getVectorNumElements() == (unsigned)NumOps && 5463 "Incorrect element count in BUILD_VECTOR!"); 5464 5465 // BUILD_VECTOR of UNDEFs is UNDEF. 5466 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 5467 return DAG.getUNDEF(VT); 5468 5469 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 5470 SDValue IdentitySrc; 5471 bool IsIdentity = true; 5472 for (int i = 0; i != NumOps; ++i) { 5473 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5474 Ops[i].getOperand(0).getValueType() != VT || 5475 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 5476 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 5477 Ops[i].getConstantOperandAPInt(1) != i) { 5478 IsIdentity = false; 5479 break; 5480 } 5481 IdentitySrc = Ops[i].getOperand(0); 5482 } 5483 if (IsIdentity) 5484 return IdentitySrc; 5485 5486 return SDValue(); 5487 } 5488 5489 /// Try to simplify vector concatenation to an input value, undef, or build 5490 /// vector. 5491 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 5492 ArrayRef<SDValue> Ops, 5493 SelectionDAG &DAG) { 5494 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 5495 assert(llvm::all_of(Ops, 5496 [Ops](SDValue Op) { 5497 return Ops[0].getValueType() == Op.getValueType(); 5498 }) && 5499 "Concatenation of vectors with inconsistent value types!"); 5500 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 5501 VT.getVectorElementCount() && 5502 "Incorrect element count in vector concatenation!"); 5503 5504 if (Ops.size() == 1) 5505 return Ops[0]; 5506 5507 // Concat of UNDEFs is UNDEF. 5508 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 5509 return DAG.getUNDEF(VT); 5510 5511 // Scan the operands and look for extract operations from a single source 5512 // that correspond to insertion at the same location via this concatenation: 5513 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 5514 SDValue IdentitySrc; 5515 bool IsIdentity = true; 5516 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 5517 SDValue Op = Ops[i]; 5518 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 5519 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 5520 Op.getOperand(0).getValueType() != VT || 5521 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 5522 Op.getConstantOperandVal(1) != IdentityIndex) { 5523 IsIdentity = false; 5524 break; 5525 } 5526 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 5527 "Unexpected identity source vector for concat of extracts"); 5528 IdentitySrc = Op.getOperand(0); 5529 } 5530 if (IsIdentity) { 5531 assert(IdentitySrc && "Failed to set source vector of extracts"); 5532 return IdentitySrc; 5533 } 5534 5535 // The code below this point is only designed to work for fixed width 5536 // vectors, so we bail out for now. 5537 if (VT.isScalableVector()) 5538 return SDValue(); 5539 5540 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 5541 // simplified to one big BUILD_VECTOR. 5542 // FIXME: Add support for SCALAR_TO_VECTOR as well. 5543 EVT SVT = VT.getScalarType(); 5544 SmallVector<SDValue, 16> Elts; 5545 for (SDValue Op : Ops) { 5546 EVT OpVT = Op.getValueType(); 5547 if (Op.isUndef()) 5548 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 5549 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 5550 Elts.append(Op->op_begin(), Op->op_end()); 5551 else 5552 return SDValue(); 5553 } 5554 5555 // BUILD_VECTOR requires all inputs to be of the same type, find the 5556 // maximum type and extend them all. 5557 for (SDValue Op : Elts) 5558 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 5559 5560 if (SVT.bitsGT(VT.getScalarType())) { 5561 for (SDValue &Op : Elts) { 5562 if (Op.isUndef()) 5563 Op = DAG.getUNDEF(SVT); 5564 else 5565 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 5566 ? DAG.getZExtOrTrunc(Op, DL, SVT) 5567 : DAG.getSExtOrTrunc(Op, DL, SVT); 5568 } 5569 } 5570 5571 SDValue V = DAG.getBuildVector(VT, DL, Elts); 5572 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 5573 return V; 5574 } 5575 5576 /// Gets or creates the specified node. 5577 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 5578 FoldingSetNodeID ID; 5579 AddNodeIDNode(ID, Opcode, getVTList(VT), std::nullopt); 5580 void *IP = nullptr; 5581 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5582 return SDValue(E, 0); 5583 5584 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 5585 getVTList(VT)); 5586 CSEMap.InsertNode(N, IP); 5587 5588 InsertNode(N); 5589 SDValue V = SDValue(N, 0); 5590 NewSDValueDbgMsg(V, "Creating new node: ", this); 5591 return V; 5592 } 5593 5594 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5595 SDValue N1) { 5596 SDNodeFlags Flags; 5597 if (Inserter) 5598 Flags = Inserter->getFlags(); 5599 return getNode(Opcode, DL, VT, N1, Flags); 5600 } 5601 5602 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5603 SDValue N1, const SDNodeFlags Flags) { 5604 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!"); 5605 5606 // Constant fold unary operations with a vector integer or float operand. 5607 switch (Opcode) { 5608 default: 5609 // FIXME: Entirely reasonable to perform folding of other unary 5610 // operations here as the need arises. 5611 break; 5612 case ISD::FNEG: 5613 case ISD::FABS: 5614 case ISD::FCEIL: 5615 case ISD::FTRUNC: 5616 case ISD::FFLOOR: 5617 case ISD::FP_EXTEND: 5618 case ISD::FP_TO_SINT: 5619 case ISD::FP_TO_UINT: 5620 case ISD::FP_TO_FP16: 5621 case ISD::FP_TO_BF16: 5622 case ISD::TRUNCATE: 5623 case ISD::ANY_EXTEND: 5624 case ISD::ZERO_EXTEND: 5625 case ISD::SIGN_EXTEND: 5626 case ISD::UINT_TO_FP: 5627 case ISD::SINT_TO_FP: 5628 case ISD::FP16_TO_FP: 5629 case ISD::BF16_TO_FP: 5630 case ISD::BITCAST: 5631 case ISD::ABS: 5632 case ISD::BITREVERSE: 5633 case ISD::BSWAP: 5634 case ISD::CTLZ: 5635 case ISD::CTLZ_ZERO_UNDEF: 5636 case ISD::CTTZ: 5637 case ISD::CTTZ_ZERO_UNDEF: 5638 case ISD::CTPOP: 5639 case ISD::STEP_VECTOR: { 5640 SDValue Ops = {N1}; 5641 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5642 return Fold; 5643 } 5644 } 5645 5646 unsigned OpOpcode = N1.getNode()->getOpcode(); 5647 switch (Opcode) { 5648 case ISD::STEP_VECTOR: 5649 assert(VT.isScalableVector() && 5650 "STEP_VECTOR can only be used with scalable types"); 5651 assert(OpOpcode == ISD::TargetConstant && 5652 VT.getVectorElementType() == N1.getValueType() && 5653 "Unexpected step operand"); 5654 break; 5655 case ISD::FREEZE: 5656 assert(VT == N1.getValueType() && "Unexpected VT!"); 5657 if (isGuaranteedNotToBeUndefOrPoison(N1, /*PoisonOnly*/ false, 5658 /*Depth*/ 1)) 5659 return N1; 5660 break; 5661 case ISD::TokenFactor: 5662 case ISD::MERGE_VALUES: 5663 case ISD::CONCAT_VECTORS: 5664 return N1; // Factor, merge or concat of one node? No need. 5665 case ISD::BUILD_VECTOR: { 5666 // Attempt to simplify BUILD_VECTOR. 5667 SDValue Ops[] = {N1}; 5668 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5669 return V; 5670 break; 5671 } 5672 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5673 case ISD::FP_EXTEND: 5674 assert(VT.isFloatingPoint() && N1.getValueType().isFloatingPoint() && 5675 "Invalid FP cast!"); 5676 if (N1.getValueType() == VT) return N1; // noop conversion. 5677 assert((!VT.isVector() || VT.getVectorElementCount() == 5678 N1.getValueType().getVectorElementCount()) && 5679 "Vector element count mismatch!"); 5680 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!"); 5681 if (N1.isUndef()) 5682 return getUNDEF(VT); 5683 break; 5684 case ISD::FP_TO_SINT: 5685 case ISD::FP_TO_UINT: 5686 if (N1.isUndef()) 5687 return getUNDEF(VT); 5688 break; 5689 case ISD::SINT_TO_FP: 5690 case ISD::UINT_TO_FP: 5691 // [us]itofp(undef) = 0, because the result value is bounded. 5692 if (N1.isUndef()) 5693 return getConstantFP(0.0, DL, VT); 5694 break; 5695 case ISD::SIGN_EXTEND: 5696 assert(VT.isInteger() && N1.getValueType().isInteger() && 5697 "Invalid SIGN_EXTEND!"); 5698 assert(VT.isVector() == N1.getValueType().isVector() && 5699 "SIGN_EXTEND result type type should be vector iff the operand " 5700 "type is vector!"); 5701 if (N1.getValueType() == VT) return N1; // noop extension 5702 assert((!VT.isVector() || VT.getVectorElementCount() == 5703 N1.getValueType().getVectorElementCount()) && 5704 "Vector element count mismatch!"); 5705 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!"); 5706 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5707 return getNode(OpOpcode, DL, VT, N1.getOperand(0)); 5708 if (OpOpcode == ISD::UNDEF) 5709 // sext(undef) = 0, because the top bits will all be the same. 5710 return getConstant(0, DL, VT); 5711 break; 5712 case ISD::ZERO_EXTEND: 5713 assert(VT.isInteger() && N1.getValueType().isInteger() && 5714 "Invalid ZERO_EXTEND!"); 5715 assert(VT.isVector() == N1.getValueType().isVector() && 5716 "ZERO_EXTEND result type type should be vector iff the operand " 5717 "type is vector!"); 5718 if (N1.getValueType() == VT) return N1; // noop extension 5719 assert((!VT.isVector() || VT.getVectorElementCount() == 5720 N1.getValueType().getVectorElementCount()) && 5721 "Vector element count mismatch!"); 5722 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!"); 5723 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5724 return getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0)); 5725 if (OpOpcode == ISD::UNDEF) 5726 // zext(undef) = 0, because the top bits will be zero. 5727 return getConstant(0, DL, VT); 5728 5729 // Skip unnecessary zext_inreg pattern: 5730 // (zext (trunc x)) -> x iff the upper bits are known zero. 5731 // TODO: Remove (zext (trunc (and x, c))) exception which some targets 5732 // use to recognise zext_inreg patterns. 5733 if (OpOpcode == ISD::TRUNCATE) { 5734 SDValue OpOp = N1.getOperand(0); 5735 if (OpOp.getValueType() == VT) { 5736 if (OpOp.getOpcode() != ISD::AND) { 5737 APInt HiBits = APInt::getBitsSetFrom(VT.getScalarSizeInBits(), 5738 N1.getScalarValueSizeInBits()); 5739 if (MaskedValueIsZero(OpOp, HiBits)) { 5740 transferDbgValues(N1, OpOp); 5741 return OpOp; 5742 } 5743 } 5744 } 5745 } 5746 break; 5747 case ISD::ANY_EXTEND: 5748 assert(VT.isInteger() && N1.getValueType().isInteger() && 5749 "Invalid ANY_EXTEND!"); 5750 assert(VT.isVector() == N1.getValueType().isVector() && 5751 "ANY_EXTEND result type type should be vector iff the operand " 5752 "type is vector!"); 5753 if (N1.getValueType() == VT) return N1; // noop extension 5754 assert((!VT.isVector() || VT.getVectorElementCount() == 5755 N1.getValueType().getVectorElementCount()) && 5756 "Vector element count mismatch!"); 5757 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!"); 5758 5759 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5760 OpOpcode == ISD::ANY_EXTEND) 5761 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5762 return getNode(OpOpcode, DL, VT, N1.getOperand(0)); 5763 if (OpOpcode == ISD::UNDEF) 5764 return getUNDEF(VT); 5765 5766 // (ext (trunc x)) -> x 5767 if (OpOpcode == ISD::TRUNCATE) { 5768 SDValue OpOp = N1.getOperand(0); 5769 if (OpOp.getValueType() == VT) { 5770 transferDbgValues(N1, OpOp); 5771 return OpOp; 5772 } 5773 } 5774 break; 5775 case ISD::TRUNCATE: 5776 assert(VT.isInteger() && N1.getValueType().isInteger() && 5777 "Invalid TRUNCATE!"); 5778 assert(VT.isVector() == N1.getValueType().isVector() && 5779 "TRUNCATE result type type should be vector iff the operand " 5780 "type is vector!"); 5781 if (N1.getValueType() == VT) return N1; // noop truncate 5782 assert((!VT.isVector() || VT.getVectorElementCount() == 5783 N1.getValueType().getVectorElementCount()) && 5784 "Vector element count mismatch!"); 5785 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!"); 5786 if (OpOpcode == ISD::TRUNCATE) 5787 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0)); 5788 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5789 OpOpcode == ISD::ANY_EXTEND) { 5790 // If the source is smaller than the dest, we still need an extend. 5791 if (N1.getOperand(0).getValueType().getScalarType().bitsLT( 5792 VT.getScalarType())) 5793 return getNode(OpOpcode, DL, VT, N1.getOperand(0)); 5794 if (N1.getOperand(0).getValueType().bitsGT(VT)) 5795 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0)); 5796 return N1.getOperand(0); 5797 } 5798 if (OpOpcode == ISD::UNDEF) 5799 return getUNDEF(VT); 5800 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5801 return getVScale(DL, VT, 5802 N1.getConstantOperandAPInt(0).trunc(VT.getSizeInBits())); 5803 break; 5804 case ISD::ANY_EXTEND_VECTOR_INREG: 5805 case ISD::ZERO_EXTEND_VECTOR_INREG: 5806 case ISD::SIGN_EXTEND_VECTOR_INREG: 5807 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5808 assert(N1.getValueType().bitsLE(VT) && 5809 "The input must be the same size or smaller than the result."); 5810 assert(VT.getVectorMinNumElements() < 5811 N1.getValueType().getVectorMinNumElements() && 5812 "The destination vector type must have fewer lanes than the input."); 5813 break; 5814 case ISD::ABS: 5815 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!"); 5816 if (OpOpcode == ISD::UNDEF) 5817 return getConstant(0, DL, VT); 5818 break; 5819 case ISD::BSWAP: 5820 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!"); 5821 assert((VT.getScalarSizeInBits() % 16 == 0) && 5822 "BSWAP types must be a multiple of 16 bits!"); 5823 if (OpOpcode == ISD::UNDEF) 5824 return getUNDEF(VT); 5825 // bswap(bswap(X)) -> X. 5826 if (OpOpcode == ISD::BSWAP) 5827 return N1.getOperand(0); 5828 break; 5829 case ISD::BITREVERSE: 5830 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!"); 5831 if (OpOpcode == ISD::UNDEF) 5832 return getUNDEF(VT); 5833 break; 5834 case ISD::BITCAST: 5835 assert(VT.getSizeInBits() == N1.getValueSizeInBits() && 5836 "Cannot BITCAST between types of different sizes!"); 5837 if (VT == N1.getValueType()) return N1; // noop conversion. 5838 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5839 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0)); 5840 if (OpOpcode == ISD::UNDEF) 5841 return getUNDEF(VT); 5842 break; 5843 case ISD::SCALAR_TO_VECTOR: 5844 assert(VT.isVector() && !N1.getValueType().isVector() && 5845 (VT.getVectorElementType() == N1.getValueType() || 5846 (VT.getVectorElementType().isInteger() && 5847 N1.getValueType().isInteger() && 5848 VT.getVectorElementType().bitsLE(N1.getValueType()))) && 5849 "Illegal SCALAR_TO_VECTOR node!"); 5850 if (OpOpcode == ISD::UNDEF) 5851 return getUNDEF(VT); 5852 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5853 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5854 isa<ConstantSDNode>(N1.getOperand(1)) && 5855 N1.getConstantOperandVal(1) == 0 && 5856 N1.getOperand(0).getValueType() == VT) 5857 return N1.getOperand(0); 5858 break; 5859 case ISD::FNEG: 5860 // Negation of an unknown bag of bits is still completely undefined. 5861 if (OpOpcode == ISD::UNDEF) 5862 return getUNDEF(VT); 5863 5864 if (OpOpcode == ISD::FNEG) // --X -> X 5865 return N1.getOperand(0); 5866 break; 5867 case ISD::FABS: 5868 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5869 return getNode(ISD::FABS, DL, VT, N1.getOperand(0)); 5870 break; 5871 case ISD::VSCALE: 5872 assert(VT == N1.getValueType() && "Unexpected VT!"); 5873 break; 5874 case ISD::CTPOP: 5875 if (N1.getValueType().getScalarType() == MVT::i1) 5876 return N1; 5877 break; 5878 case ISD::CTLZ: 5879 case ISD::CTTZ: 5880 if (N1.getValueType().getScalarType() == MVT::i1) 5881 return getNOT(DL, N1, N1.getValueType()); 5882 break; 5883 case ISD::VECREDUCE_ADD: 5884 if (N1.getValueType().getScalarType() == MVT::i1) 5885 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1); 5886 break; 5887 case ISD::VECREDUCE_SMIN: 5888 case ISD::VECREDUCE_UMAX: 5889 if (N1.getValueType().getScalarType() == MVT::i1) 5890 return getNode(ISD::VECREDUCE_OR, DL, VT, N1); 5891 break; 5892 case ISD::VECREDUCE_SMAX: 5893 case ISD::VECREDUCE_UMIN: 5894 if (N1.getValueType().getScalarType() == MVT::i1) 5895 return getNode(ISD::VECREDUCE_AND, DL, VT, N1); 5896 break; 5897 } 5898 5899 SDNode *N; 5900 SDVTList VTs = getVTList(VT); 5901 SDValue Ops[] = {N1}; 5902 if (VT != MVT::Glue) { // Don't CSE glue producing nodes 5903 FoldingSetNodeID ID; 5904 AddNodeIDNode(ID, Opcode, VTs, Ops); 5905 void *IP = nullptr; 5906 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5907 E->intersectFlagsWith(Flags); 5908 return SDValue(E, 0); 5909 } 5910 5911 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5912 N->setFlags(Flags); 5913 createOperands(N, Ops); 5914 CSEMap.InsertNode(N, IP); 5915 } else { 5916 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5917 createOperands(N, Ops); 5918 } 5919 5920 InsertNode(N); 5921 SDValue V = SDValue(N, 0); 5922 NewSDValueDbgMsg(V, "Creating new node: ", this); 5923 return V; 5924 } 5925 5926 static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5927 const APInt &C2) { 5928 switch (Opcode) { 5929 case ISD::ADD: return C1 + C2; 5930 case ISD::SUB: return C1 - C2; 5931 case ISD::MUL: return C1 * C2; 5932 case ISD::AND: return C1 & C2; 5933 case ISD::OR: return C1 | C2; 5934 case ISD::XOR: return C1 ^ C2; 5935 case ISD::SHL: return C1 << C2; 5936 case ISD::SRL: return C1.lshr(C2); 5937 case ISD::SRA: return C1.ashr(C2); 5938 case ISD::ROTL: return C1.rotl(C2); 5939 case ISD::ROTR: return C1.rotr(C2); 5940 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5941 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5942 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5943 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5944 case ISD::SADDSAT: return C1.sadd_sat(C2); 5945 case ISD::UADDSAT: return C1.uadd_sat(C2); 5946 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5947 case ISD::USUBSAT: return C1.usub_sat(C2); 5948 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5949 case ISD::USHLSAT: return C1.ushl_sat(C2); 5950 case ISD::UDIV: 5951 if (!C2.getBoolValue()) 5952 break; 5953 return C1.udiv(C2); 5954 case ISD::UREM: 5955 if (!C2.getBoolValue()) 5956 break; 5957 return C1.urem(C2); 5958 case ISD::SDIV: 5959 if (!C2.getBoolValue()) 5960 break; 5961 return C1.sdiv(C2); 5962 case ISD::SREM: 5963 if (!C2.getBoolValue()) 5964 break; 5965 return C1.srem(C2); 5966 case ISD::MULHS: { 5967 unsigned FullWidth = C1.getBitWidth() * 2; 5968 APInt C1Ext = C1.sext(FullWidth); 5969 APInt C2Ext = C2.sext(FullWidth); 5970 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5971 } 5972 case ISD::MULHU: { 5973 unsigned FullWidth = C1.getBitWidth() * 2; 5974 APInt C1Ext = C1.zext(FullWidth); 5975 APInt C2Ext = C2.zext(FullWidth); 5976 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5977 } 5978 case ISD::AVGFLOORS: { 5979 unsigned FullWidth = C1.getBitWidth() + 1; 5980 APInt C1Ext = C1.sext(FullWidth); 5981 APInt C2Ext = C2.sext(FullWidth); 5982 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5983 } 5984 case ISD::AVGFLOORU: { 5985 unsigned FullWidth = C1.getBitWidth() + 1; 5986 APInt C1Ext = C1.zext(FullWidth); 5987 APInt C2Ext = C2.zext(FullWidth); 5988 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5989 } 5990 case ISD::AVGCEILS: { 5991 unsigned FullWidth = C1.getBitWidth() + 1; 5992 APInt C1Ext = C1.sext(FullWidth); 5993 APInt C2Ext = C2.sext(FullWidth); 5994 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5995 } 5996 case ISD::AVGCEILU: { 5997 unsigned FullWidth = C1.getBitWidth() + 1; 5998 APInt C1Ext = C1.zext(FullWidth); 5999 APInt C2Ext = C2.zext(FullWidth); 6000 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 6001 } 6002 case ISD::ABDS: 6003 return APIntOps::smax(C1, C2) - APIntOps::smin(C1, C2); 6004 case ISD::ABDU: 6005 return APIntOps::umax(C1, C2) - APIntOps::umin(C1, C2); 6006 } 6007 return std::nullopt; 6008 } 6009 6010 // Handle constant folding with UNDEF. 6011 // TODO: Handle more cases. 6012 static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1, 6013 bool IsUndef1, const APInt &C2, 6014 bool IsUndef2) { 6015 if (!(IsUndef1 || IsUndef2)) 6016 return FoldValue(Opcode, C1, C2); 6017 6018 // Fold and(x, undef) -> 0 6019 // Fold mul(x, undef) -> 0 6020 if (Opcode == ISD::AND || Opcode == ISD::MUL) 6021 return APInt::getZero(C1.getBitWidth()); 6022 6023 return std::nullopt; 6024 } 6025 6026 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 6027 const GlobalAddressSDNode *GA, 6028 const SDNode *N2) { 6029 if (GA->getOpcode() != ISD::GlobalAddress) 6030 return SDValue(); 6031 if (!TLI->isOffsetFoldingLegal(GA)) 6032 return SDValue(); 6033 auto *C2 = dyn_cast<ConstantSDNode>(N2); 6034 if (!C2) 6035 return SDValue(); 6036 int64_t Offset = C2->getSExtValue(); 6037 switch (Opcode) { 6038 case ISD::ADD: break; 6039 case ISD::SUB: Offset = -uint64_t(Offset); break; 6040 default: return SDValue(); 6041 } 6042 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 6043 GA->getOffset() + uint64_t(Offset)); 6044 } 6045 6046 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 6047 switch (Opcode) { 6048 case ISD::SDIV: 6049 case ISD::UDIV: 6050 case ISD::SREM: 6051 case ISD::UREM: { 6052 // If a divisor is zero/undef or any element of a divisor vector is 6053 // zero/undef, the whole op is undef. 6054 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 6055 SDValue Divisor = Ops[1]; 6056 if (Divisor.isUndef() || isNullConstant(Divisor)) 6057 return true; 6058 6059 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 6060 llvm::any_of(Divisor->op_values(), 6061 [](SDValue V) { return V.isUndef() || 6062 isNullConstant(V); }); 6063 // TODO: Handle signed overflow. 6064 } 6065 // TODO: Handle oversized shifts. 6066 default: 6067 return false; 6068 } 6069 } 6070 6071 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 6072 EVT VT, ArrayRef<SDValue> Ops) { 6073 // If the opcode is a target-specific ISD node, there's nothing we can 6074 // do here and the operand rules may not line up with the below, so 6075 // bail early. 6076 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 6077 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 6078 // foldCONCAT_VECTORS in getNode before this is called. 6079 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 6080 return SDValue(); 6081 6082 unsigned NumOps = Ops.size(); 6083 if (NumOps == 0) 6084 return SDValue(); 6085 6086 if (isUndef(Opcode, Ops)) 6087 return getUNDEF(VT); 6088 6089 // Handle unary special cases. 6090 if (NumOps == 1) { 6091 SDValue N1 = Ops[0]; 6092 6093 // Constant fold unary operations with an integer constant operand. Even 6094 // opaque constant will be folded, because the folding of unary operations 6095 // doesn't create new constants with different values. Nevertheless, the 6096 // opaque flag is preserved during folding to prevent future folding with 6097 // other constants. 6098 if (auto *C = dyn_cast<ConstantSDNode>(N1)) { 6099 const APInt &Val = C->getAPIntValue(); 6100 switch (Opcode) { 6101 case ISD::SIGN_EXTEND: 6102 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 6103 C->isTargetOpcode(), C->isOpaque()); 6104 case ISD::TRUNCATE: 6105 if (C->isOpaque()) 6106 break; 6107 [[fallthrough]]; 6108 case ISD::ZERO_EXTEND: 6109 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 6110 C->isTargetOpcode(), C->isOpaque()); 6111 case ISD::ANY_EXTEND: 6112 // Some targets like RISCV prefer to sign extend some types. 6113 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT)) 6114 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 6115 C->isTargetOpcode(), C->isOpaque()); 6116 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 6117 C->isTargetOpcode(), C->isOpaque()); 6118 case ISD::ABS: 6119 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 6120 C->isOpaque()); 6121 case ISD::BITREVERSE: 6122 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 6123 C->isOpaque()); 6124 case ISD::BSWAP: 6125 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 6126 C->isOpaque()); 6127 case ISD::CTPOP: 6128 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(), 6129 C->isOpaque()); 6130 case ISD::CTLZ: 6131 case ISD::CTLZ_ZERO_UNDEF: 6132 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(), 6133 C->isOpaque()); 6134 case ISD::CTTZ: 6135 case ISD::CTTZ_ZERO_UNDEF: 6136 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(), 6137 C->isOpaque()); 6138 case ISD::UINT_TO_FP: 6139 case ISD::SINT_TO_FP: { 6140 APFloat apf(EVTToAPFloatSemantics(VT), 6141 APInt::getZero(VT.getSizeInBits())); 6142 (void)apf.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP, 6143 APFloat::rmNearestTiesToEven); 6144 return getConstantFP(apf, DL, VT); 6145 } 6146 case ISD::FP16_TO_FP: 6147 case ISD::BF16_TO_FP: { 6148 bool Ignored; 6149 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf() 6150 : APFloat::BFloat(), 6151 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 6152 6153 // This can return overflow, underflow, or inexact; we don't care. 6154 // FIXME need to be more flexible about rounding mode. 6155 (void)FPV.convert(EVTToAPFloatSemantics(VT), 6156 APFloat::rmNearestTiesToEven, &Ignored); 6157 return getConstantFP(FPV, DL, VT); 6158 } 6159 case ISD::STEP_VECTOR: 6160 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this)) 6161 return V; 6162 break; 6163 case ISD::BITCAST: 6164 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 6165 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 6166 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 6167 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 6168 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 6169 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 6170 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 6171 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 6172 break; 6173 } 6174 } 6175 6176 // Constant fold unary operations with a floating point constant operand. 6177 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) { 6178 APFloat V = C->getValueAPF(); // make copy 6179 switch (Opcode) { 6180 case ISD::FNEG: 6181 V.changeSign(); 6182 return getConstantFP(V, DL, VT); 6183 case ISD::FABS: 6184 V.clearSign(); 6185 return getConstantFP(V, DL, VT); 6186 case ISD::FCEIL: { 6187 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 6188 if (fs == APFloat::opOK || fs == APFloat::opInexact) 6189 return getConstantFP(V, DL, VT); 6190 return SDValue(); 6191 } 6192 case ISD::FTRUNC: { 6193 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 6194 if (fs == APFloat::opOK || fs == APFloat::opInexact) 6195 return getConstantFP(V, DL, VT); 6196 return SDValue(); 6197 } 6198 case ISD::FFLOOR: { 6199 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 6200 if (fs == APFloat::opOK || fs == APFloat::opInexact) 6201 return getConstantFP(V, DL, VT); 6202 return SDValue(); 6203 } 6204 case ISD::FP_EXTEND: { 6205 bool ignored; 6206 // This can return overflow, underflow, or inexact; we don't care. 6207 // FIXME need to be more flexible about rounding mode. 6208 (void)V.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 6209 &ignored); 6210 return getConstantFP(V, DL, VT); 6211 } 6212 case ISD::FP_TO_SINT: 6213 case ISD::FP_TO_UINT: { 6214 bool ignored; 6215 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 6216 // FIXME need to be more flexible about rounding mode. 6217 APFloat::opStatus s = 6218 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 6219 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 6220 break; 6221 return getConstant(IntVal, DL, VT); 6222 } 6223 case ISD::FP_TO_FP16: 6224 case ISD::FP_TO_BF16: { 6225 bool Ignored; 6226 // This can return overflow, underflow, or inexact; we don't care. 6227 // FIXME need to be more flexible about rounding mode. 6228 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf() 6229 : APFloat::BFloat(), 6230 APFloat::rmNearestTiesToEven, &Ignored); 6231 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 6232 } 6233 case ISD::BITCAST: 6234 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 6235 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, 6236 VT); 6237 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 6238 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, 6239 VT); 6240 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 6241 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, 6242 VT); 6243 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 6244 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 6245 break; 6246 } 6247 } 6248 6249 // Early-out if we failed to constant fold a bitcast. 6250 if (Opcode == ISD::BITCAST) 6251 return SDValue(); 6252 } 6253 6254 // Handle binops special cases. 6255 if (NumOps == 2) { 6256 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops)) 6257 return CFP; 6258 6259 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 6260 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 6261 if (C1->isOpaque() || C2->isOpaque()) 6262 return SDValue(); 6263 6264 std::optional<APInt> FoldAttempt = 6265 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 6266 if (!FoldAttempt) 6267 return SDValue(); 6268 6269 SDValue Folded = getConstant(*FoldAttempt, DL, VT); 6270 assert((!Folded || !VT.isVector()) && 6271 "Can't fold vectors ops with scalar operands"); 6272 return Folded; 6273 } 6274 } 6275 6276 // fold (add Sym, c) -> Sym+c 6277 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 6278 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 6279 if (TLI->isCommutativeBinOp(Opcode)) 6280 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 6281 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 6282 } 6283 6284 // This is for vector folding only from here on. 6285 if (!VT.isVector()) 6286 return SDValue(); 6287 6288 ElementCount NumElts = VT.getVectorElementCount(); 6289 6290 // See if we can fold through bitcasted integer ops. 6291 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 6292 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 6293 Ops[0].getOpcode() == ISD::BITCAST && 6294 Ops[1].getOpcode() == ISD::BITCAST) { 6295 SDValue N1 = peekThroughBitcasts(Ops[0]); 6296 SDValue N2 = peekThroughBitcasts(Ops[1]); 6297 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 6298 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 6299 EVT BVVT = N1.getValueType(); 6300 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 6301 bool IsLE = getDataLayout().isLittleEndian(); 6302 unsigned EltBits = VT.getScalarSizeInBits(); 6303 SmallVector<APInt> RawBits1, RawBits2; 6304 BitVector UndefElts1, UndefElts2; 6305 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 6306 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) { 6307 SmallVector<APInt> RawBits; 6308 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 6309 std::optional<APInt> Fold = FoldValueWithUndef( 6310 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]); 6311 if (!Fold) 6312 break; 6313 RawBits.push_back(*Fold); 6314 } 6315 if (RawBits.size() == NumElts.getFixedValue()) { 6316 // We have constant folded, but we need to cast this again back to 6317 // the original (possibly legalized) type. 6318 SmallVector<APInt> DstBits; 6319 BitVector DstUndefs; 6320 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 6321 DstBits, RawBits, DstUndefs, 6322 BitVector(RawBits.size(), false)); 6323 EVT BVEltVT = BV1->getOperand(0).getValueType(); 6324 unsigned BVEltBits = BVEltVT.getSizeInBits(); 6325 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 6326 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 6327 if (DstUndefs[I]) 6328 continue; 6329 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT); 6330 } 6331 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 6332 } 6333 } 6334 } 6335 } 6336 6337 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 6338 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 6339 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 6340 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 6341 APInt RHSVal; 6342 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 6343 APInt NewStep = Opcode == ISD::MUL 6344 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 6345 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 6346 return getStepVector(DL, VT, NewStep); 6347 } 6348 } 6349 6350 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 6351 return !Op.getValueType().isVector() || 6352 Op.getValueType().getVectorElementCount() == NumElts; 6353 }; 6354 6355 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 6356 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 6357 Op.getOpcode() == ISD::BUILD_VECTOR || 6358 Op.getOpcode() == ISD::SPLAT_VECTOR; 6359 }; 6360 6361 // All operands must be vector types with the same number of elements as 6362 // the result type and must be either UNDEF or a build/splat vector 6363 // or UNDEF scalars. 6364 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 6365 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 6366 return SDValue(); 6367 6368 // If we are comparing vectors, then the result needs to be a i1 boolean that 6369 // is then extended back to the legal result type depending on how booleans 6370 // are represented. 6371 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 6372 ISD::NodeType ExtendCode = 6373 (Opcode == ISD::SETCC && SVT != VT.getScalarType()) 6374 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT)) 6375 : ISD::SIGN_EXTEND; 6376 6377 // Find legal integer scalar type for constant promotion and 6378 // ensure that its scalar size is at least as large as source. 6379 EVT LegalSVT = VT.getScalarType(); 6380 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 6381 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 6382 if (LegalSVT.bitsLT(VT.getScalarType())) 6383 return SDValue(); 6384 } 6385 6386 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 6387 // only have one operand to check. For fixed-length vector types we may have 6388 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 6389 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 6390 6391 // Constant fold each scalar lane separately. 6392 SmallVector<SDValue, 4> ScalarResults; 6393 for (unsigned I = 0; I != NumVectorElts; I++) { 6394 SmallVector<SDValue, 4> ScalarOps; 6395 for (SDValue Op : Ops) { 6396 EVT InSVT = Op.getValueType().getScalarType(); 6397 if (Op.getOpcode() != ISD::BUILD_VECTOR && 6398 Op.getOpcode() != ISD::SPLAT_VECTOR) { 6399 if (Op.isUndef()) 6400 ScalarOps.push_back(getUNDEF(InSVT)); 6401 else 6402 ScalarOps.push_back(Op); 6403 continue; 6404 } 6405 6406 SDValue ScalarOp = 6407 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 6408 EVT ScalarVT = ScalarOp.getValueType(); 6409 6410 // Build vector (integer) scalar operands may need implicit 6411 // truncation - do this before constant folding. 6412 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 6413 // Don't create illegally-typed nodes unless they're constants or undef 6414 // - if we fail to constant fold we can't guarantee the (dead) nodes 6415 // we're creating will be cleaned up before being visited for 6416 // legalization. 6417 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 6418 !isa<ConstantSDNode>(ScalarOp) && 6419 TLI->getTypeAction(*getContext(), InSVT) != 6420 TargetLowering::TypeLegal) 6421 return SDValue(); 6422 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 6423 } 6424 6425 ScalarOps.push_back(ScalarOp); 6426 } 6427 6428 // Constant fold the scalar operands. 6429 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 6430 6431 // Legalize the (integer) scalar constant if necessary. 6432 if (LegalSVT != SVT) 6433 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult); 6434 6435 // Scalar folding only succeeded if the result is a constant or UNDEF. 6436 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 6437 ScalarResult.getOpcode() != ISD::ConstantFP) 6438 return SDValue(); 6439 ScalarResults.push_back(ScalarResult); 6440 } 6441 6442 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 6443 : getBuildVector(VT, DL, ScalarResults); 6444 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 6445 return V; 6446 } 6447 6448 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 6449 EVT VT, ArrayRef<SDValue> Ops) { 6450 // TODO: Add support for unary/ternary fp opcodes. 6451 if (Ops.size() != 2) 6452 return SDValue(); 6453 6454 // TODO: We don't do any constant folding for strict FP opcodes here, but we 6455 // should. That will require dealing with a potentially non-default 6456 // rounding mode, checking the "opStatus" return value from the APFloat 6457 // math calculations, and possibly other variations. 6458 SDValue N1 = Ops[0]; 6459 SDValue N2 = Ops[1]; 6460 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 6461 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 6462 if (N1CFP && N2CFP) { 6463 APFloat C1 = N1CFP->getValueAPF(); // make copy 6464 const APFloat &C2 = N2CFP->getValueAPF(); 6465 switch (Opcode) { 6466 case ISD::FADD: 6467 C1.add(C2, APFloat::rmNearestTiesToEven); 6468 return getConstantFP(C1, DL, VT); 6469 case ISD::FSUB: 6470 C1.subtract(C2, APFloat::rmNearestTiesToEven); 6471 return getConstantFP(C1, DL, VT); 6472 case ISD::FMUL: 6473 C1.multiply(C2, APFloat::rmNearestTiesToEven); 6474 return getConstantFP(C1, DL, VT); 6475 case ISD::FDIV: 6476 C1.divide(C2, APFloat::rmNearestTiesToEven); 6477 return getConstantFP(C1, DL, VT); 6478 case ISD::FREM: 6479 C1.mod(C2); 6480 return getConstantFP(C1, DL, VT); 6481 case ISD::FCOPYSIGN: 6482 C1.copySign(C2); 6483 return getConstantFP(C1, DL, VT); 6484 case ISD::FMINNUM: 6485 return getConstantFP(minnum(C1, C2), DL, VT); 6486 case ISD::FMAXNUM: 6487 return getConstantFP(maxnum(C1, C2), DL, VT); 6488 case ISD::FMINIMUM: 6489 return getConstantFP(minimum(C1, C2), DL, VT); 6490 case ISD::FMAXIMUM: 6491 return getConstantFP(maximum(C1, C2), DL, VT); 6492 default: break; 6493 } 6494 } 6495 if (N1CFP && Opcode == ISD::FP_ROUND) { 6496 APFloat C1 = N1CFP->getValueAPF(); // make copy 6497 bool Unused; 6498 // This can return overflow, underflow, or inexact; we don't care. 6499 // FIXME need to be more flexible about rounding mode. 6500 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 6501 &Unused); 6502 return getConstantFP(C1, DL, VT); 6503 } 6504 6505 switch (Opcode) { 6506 case ISD::FSUB: 6507 // -0.0 - undef --> undef (consistent with "fneg undef") 6508 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 6509 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 6510 return getUNDEF(VT); 6511 [[fallthrough]]; 6512 6513 case ISD::FADD: 6514 case ISD::FMUL: 6515 case ISD::FDIV: 6516 case ISD::FREM: 6517 // If both operands are undef, the result is undef. If 1 operand is undef, 6518 // the result is NaN. This should match the behavior of the IR optimizer. 6519 if (N1.isUndef() && N2.isUndef()) 6520 return getUNDEF(VT); 6521 if (N1.isUndef() || N2.isUndef()) 6522 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 6523 } 6524 return SDValue(); 6525 } 6526 6527 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 6528 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 6529 6530 // There's no need to assert on a byte-aligned pointer. All pointers are at 6531 // least byte aligned. 6532 if (A == Align(1)) 6533 return Val; 6534 6535 FoldingSetNodeID ID; 6536 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 6537 ID.AddInteger(A.value()); 6538 6539 void *IP = nullptr; 6540 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 6541 return SDValue(E, 0); 6542 6543 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 6544 Val.getValueType(), A); 6545 createOperands(N, {Val}); 6546 6547 CSEMap.InsertNode(N, IP); 6548 InsertNode(N); 6549 6550 SDValue V(N, 0); 6551 NewSDValueDbgMsg(V, "Creating new node: ", this); 6552 return V; 6553 } 6554 6555 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6556 SDValue N1, SDValue N2) { 6557 SDNodeFlags Flags; 6558 if (Inserter) 6559 Flags = Inserter->getFlags(); 6560 return getNode(Opcode, DL, VT, N1, N2, Flags); 6561 } 6562 6563 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 6564 SDValue &N2) const { 6565 if (!TLI->isCommutativeBinOp(Opcode)) 6566 return; 6567 6568 // Canonicalize: 6569 // binop(const, nonconst) -> binop(nonconst, const) 6570 SDNode *N1C = isConstantIntBuildVectorOrConstantInt(N1); 6571 SDNode *N2C = isConstantIntBuildVectorOrConstantInt(N2); 6572 SDNode *N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 6573 SDNode *N2CFP = isConstantFPBuildVectorOrConstantFP(N2); 6574 if ((N1C && !N2C) || (N1CFP && !N2CFP)) 6575 std::swap(N1, N2); 6576 6577 // Canonicalize: 6578 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 6579 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 6580 N2.getOpcode() == ISD::STEP_VECTOR) 6581 std::swap(N1, N2); 6582 } 6583 6584 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6585 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 6586 assert(N1.getOpcode() != ISD::DELETED_NODE && 6587 N2.getOpcode() != ISD::DELETED_NODE && 6588 "Operand is DELETED_NODE!"); 6589 6590 canonicalizeCommutativeBinop(Opcode, N1, N2); 6591 6592 auto *N1C = dyn_cast<ConstantSDNode>(N1); 6593 auto *N2C = dyn_cast<ConstantSDNode>(N2); 6594 6595 // Don't allow undefs in vector splats - we might be returning N2 when folding 6596 // to zero etc. 6597 ConstantSDNode *N2CV = 6598 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 6599 6600 switch (Opcode) { 6601 default: break; 6602 case ISD::TokenFactor: 6603 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 6604 N2.getValueType() == MVT::Other && "Invalid token factor!"); 6605 // Fold trivial token factors. 6606 if (N1.getOpcode() == ISD::EntryToken) return N2; 6607 if (N2.getOpcode() == ISD::EntryToken) return N1; 6608 if (N1 == N2) return N1; 6609 break; 6610 case ISD::BUILD_VECTOR: { 6611 // Attempt to simplify BUILD_VECTOR. 6612 SDValue Ops[] = {N1, N2}; 6613 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6614 return V; 6615 break; 6616 } 6617 case ISD::CONCAT_VECTORS: { 6618 SDValue Ops[] = {N1, N2}; 6619 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6620 return V; 6621 break; 6622 } 6623 case ISD::AND: 6624 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6625 assert(N1.getValueType() == N2.getValueType() && 6626 N1.getValueType() == VT && "Binary operator types must match!"); 6627 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 6628 // worth handling here. 6629 if (N2CV && N2CV->isZero()) 6630 return N2; 6631 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 6632 return N1; 6633 break; 6634 case ISD::OR: 6635 case ISD::XOR: 6636 case ISD::ADD: 6637 case ISD::SUB: 6638 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6639 assert(N1.getValueType() == N2.getValueType() && 6640 N1.getValueType() == VT && "Binary operator types must match!"); 6641 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 6642 // it's worth handling here. 6643 if (N2CV && N2CV->isZero()) 6644 return N1; 6645 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 6646 VT.getVectorElementType() == MVT::i1) 6647 return getNode(ISD::XOR, DL, VT, N1, N2); 6648 break; 6649 case ISD::MUL: 6650 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6651 assert(N1.getValueType() == N2.getValueType() && 6652 N1.getValueType() == VT && "Binary operator types must match!"); 6653 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6654 return getNode(ISD::AND, DL, VT, N1, N2); 6655 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 6656 const APInt &MulImm = N1->getConstantOperandAPInt(0); 6657 const APInt &N2CImm = N2C->getAPIntValue(); 6658 return getVScale(DL, VT, MulImm * N2CImm); 6659 } 6660 break; 6661 case ISD::UDIV: 6662 case ISD::UREM: 6663 case ISD::MULHU: 6664 case ISD::MULHS: 6665 case ISD::SDIV: 6666 case ISD::SREM: 6667 case ISD::SADDSAT: 6668 case ISD::SSUBSAT: 6669 case ISD::UADDSAT: 6670 case ISD::USUBSAT: 6671 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6672 assert(N1.getValueType() == N2.getValueType() && 6673 N1.getValueType() == VT && "Binary operator types must match!"); 6674 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 6675 // fold (add_sat x, y) -> (or x, y) for bool types. 6676 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 6677 return getNode(ISD::OR, DL, VT, N1, N2); 6678 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 6679 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 6680 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 6681 } 6682 break; 6683 case ISD::ABDS: 6684 case ISD::ABDU: 6685 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6686 assert(N1.getValueType() == N2.getValueType() && 6687 N1.getValueType() == VT && "Binary operator types must match!"); 6688 break; 6689 case ISD::SMIN: 6690 case ISD::UMAX: 6691 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6692 assert(N1.getValueType() == N2.getValueType() && 6693 N1.getValueType() == VT && "Binary operator types must match!"); 6694 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6695 return getNode(ISD::OR, DL, VT, N1, N2); 6696 break; 6697 case ISD::SMAX: 6698 case ISD::UMIN: 6699 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6700 assert(N1.getValueType() == N2.getValueType() && 6701 N1.getValueType() == VT && "Binary operator types must match!"); 6702 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6703 return getNode(ISD::AND, DL, VT, N1, N2); 6704 break; 6705 case ISD::FADD: 6706 case ISD::FSUB: 6707 case ISD::FMUL: 6708 case ISD::FDIV: 6709 case ISD::FREM: 6710 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6711 assert(N1.getValueType() == N2.getValueType() && 6712 N1.getValueType() == VT && "Binary operator types must match!"); 6713 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 6714 return V; 6715 break; 6716 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 6717 assert(N1.getValueType() == VT && 6718 N1.getValueType().isFloatingPoint() && 6719 N2.getValueType().isFloatingPoint() && 6720 "Invalid FCOPYSIGN!"); 6721 break; 6722 case ISD::SHL: 6723 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 6724 const APInt &MulImm = N1->getConstantOperandAPInt(0); 6725 const APInt &ShiftImm = N2C->getAPIntValue(); 6726 return getVScale(DL, VT, MulImm << ShiftImm); 6727 } 6728 [[fallthrough]]; 6729 case ISD::SRA: 6730 case ISD::SRL: 6731 if (SDValue V = simplifyShift(N1, N2)) 6732 return V; 6733 [[fallthrough]]; 6734 case ISD::ROTL: 6735 case ISD::ROTR: 6736 assert(VT == N1.getValueType() && 6737 "Shift operators return type must be the same as their first arg"); 6738 assert(VT.isInteger() && N2.getValueType().isInteger() && 6739 "Shifts only work on integers"); 6740 assert((!VT.isVector() || VT == N2.getValueType()) && 6741 "Vector shift amounts must be in the same as their first arg"); 6742 // Verify that the shift amount VT is big enough to hold valid shift 6743 // amounts. This catches things like trying to shift an i1024 value by an 6744 // i8, which is easy to fall into in generic code that uses 6745 // TLI.getShiftAmount(). 6746 assert(N2.getValueType().getScalarSizeInBits() >= 6747 Log2_32_Ceil(VT.getScalarSizeInBits()) && 6748 "Invalid use of small shift amount with oversized value!"); 6749 6750 // Always fold shifts of i1 values so the code generator doesn't need to 6751 // handle them. Since we know the size of the shift has to be less than the 6752 // size of the value, the shift/rotate count is guaranteed to be zero. 6753 if (VT == MVT::i1) 6754 return N1; 6755 if (N2CV && N2CV->isZero()) 6756 return N1; 6757 break; 6758 case ISD::FP_ROUND: 6759 assert(VT.isFloatingPoint() && 6760 N1.getValueType().isFloatingPoint() && 6761 VT.bitsLE(N1.getValueType()) && 6762 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 6763 "Invalid FP_ROUND!"); 6764 if (N1.getValueType() == VT) return N1; // noop conversion. 6765 break; 6766 case ISD::AssertSext: 6767 case ISD::AssertZext: { 6768 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6769 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6770 assert(VT.isInteger() && EVT.isInteger() && 6771 "Cannot *_EXTEND_INREG FP types"); 6772 assert(!EVT.isVector() && 6773 "AssertSExt/AssertZExt type should be the vector element type " 6774 "rather than the vector type!"); 6775 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 6776 if (VT.getScalarType() == EVT) return N1; // noop assertion. 6777 break; 6778 } 6779 case ISD::SIGN_EXTEND_INREG: { 6780 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6781 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6782 assert(VT.isInteger() && EVT.isInteger() && 6783 "Cannot *_EXTEND_INREG FP types"); 6784 assert(EVT.isVector() == VT.isVector() && 6785 "SIGN_EXTEND_INREG type should be vector iff the operand " 6786 "type is vector!"); 6787 assert((!EVT.isVector() || 6788 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 6789 "Vector element counts must match in SIGN_EXTEND_INREG"); 6790 assert(EVT.bitsLE(VT) && "Not extending!"); 6791 if (EVT == VT) return N1; // Not actually extending 6792 6793 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 6794 unsigned FromBits = EVT.getScalarSizeInBits(); 6795 Val <<= Val.getBitWidth() - FromBits; 6796 Val.ashrInPlace(Val.getBitWidth() - FromBits); 6797 return getConstant(Val, DL, ConstantVT); 6798 }; 6799 6800 if (N1C) { 6801 const APInt &Val = N1C->getAPIntValue(); 6802 return SignExtendInReg(Val, VT); 6803 } 6804 6805 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 6806 SmallVector<SDValue, 8> Ops; 6807 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 6808 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6809 SDValue Op = N1.getOperand(i); 6810 if (Op.isUndef()) { 6811 Ops.push_back(getUNDEF(OpVT)); 6812 continue; 6813 } 6814 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6815 APInt Val = C->getAPIntValue(); 6816 Ops.push_back(SignExtendInReg(Val, OpVT)); 6817 } 6818 return getBuildVector(VT, DL, Ops); 6819 } 6820 6821 if (N1.getOpcode() == ISD::SPLAT_VECTOR && 6822 isa<ConstantSDNode>(N1.getOperand(0))) 6823 return getNode( 6824 ISD::SPLAT_VECTOR, DL, VT, 6825 SignExtendInReg(N1.getConstantOperandAPInt(0), 6826 N1.getOperand(0).getValueType())); 6827 break; 6828 } 6829 case ISD::FP_TO_SINT_SAT: 6830 case ISD::FP_TO_UINT_SAT: { 6831 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6832 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6833 assert(N1.getValueType().isVector() == VT.isVector() && 6834 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6835 "vector!"); 6836 assert((!VT.isVector() || VT.getVectorElementCount() == 6837 N1.getValueType().getVectorElementCount()) && 6838 "Vector element counts must match in FP_TO_*INT_SAT"); 6839 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6840 "Type to saturate to must be a scalar."); 6841 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6842 "Not extending!"); 6843 break; 6844 } 6845 case ISD::EXTRACT_VECTOR_ELT: 6846 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6847 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6848 element type of the vector."); 6849 6850 // Extract from an undefined value or using an undefined index is undefined. 6851 if (N1.isUndef() || N2.isUndef()) 6852 return getUNDEF(VT); 6853 6854 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6855 // vectors. For scalable vectors we will provide appropriate support for 6856 // dealing with arbitrary indices. 6857 if (N2C && N1.getValueType().isFixedLengthVector() && 6858 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6859 return getUNDEF(VT); 6860 6861 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6862 // expanding copies of large vectors from registers. This only works for 6863 // fixed length vectors, since we need to know the exact number of 6864 // elements. 6865 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS && 6866 N1.getOperand(0).getValueType().isFixedLengthVector()) { 6867 unsigned Factor = 6868 N1.getOperand(0).getValueType().getVectorNumElements(); 6869 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6870 N1.getOperand(N2C->getZExtValue() / Factor), 6871 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6872 } 6873 6874 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6875 // lowering is expanding large vector constants. 6876 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6877 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6878 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6879 N1.getValueType().isFixedLengthVector()) && 6880 "BUILD_VECTOR used for scalable vectors"); 6881 unsigned Index = 6882 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6883 SDValue Elt = N1.getOperand(Index); 6884 6885 if (VT != Elt.getValueType()) 6886 // If the vector element type is not legal, the BUILD_VECTOR operands 6887 // are promoted and implicitly truncated, and the result implicitly 6888 // extended. Make that explicit here. 6889 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6890 6891 return Elt; 6892 } 6893 6894 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6895 // operations are lowered to scalars. 6896 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6897 // If the indices are the same, return the inserted element else 6898 // if the indices are known different, extract the element from 6899 // the original vector. 6900 SDValue N1Op2 = N1.getOperand(2); 6901 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6902 6903 if (N1Op2C && N2C) { 6904 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6905 if (VT == N1.getOperand(1).getValueType()) 6906 return N1.getOperand(1); 6907 if (VT.isFloatingPoint()) { 6908 assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits()); 6909 return getFPExtendOrRound(N1.getOperand(1), DL, VT); 6910 } 6911 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6912 } 6913 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6914 } 6915 } 6916 6917 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6918 // when vector types are scalarized and v1iX is legal. 6919 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6920 // Here we are completely ignoring the extract element index (N2), 6921 // which is fine for fixed width vectors, since any index other than 0 6922 // is undefined anyway. However, this cannot be ignored for scalable 6923 // vectors - in theory we could support this, but we don't want to do this 6924 // without a profitability check. 6925 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6926 N1.getValueType().isFixedLengthVector() && 6927 N1.getValueType().getVectorNumElements() == 1) { 6928 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6929 N1.getOperand(1)); 6930 } 6931 break; 6932 case ISD::EXTRACT_ELEMENT: 6933 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6934 assert(!N1.getValueType().isVector() && !VT.isVector() && 6935 (N1.getValueType().isInteger() == VT.isInteger()) && 6936 N1.getValueType() != VT && 6937 "Wrong types for EXTRACT_ELEMENT!"); 6938 6939 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6940 // 64-bit integers into 32-bit parts. Instead of building the extract of 6941 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6942 if (N1.getOpcode() == ISD::BUILD_PAIR) 6943 return N1.getOperand(N2C->getZExtValue()); 6944 6945 // EXTRACT_ELEMENT of a constant int is also very common. 6946 if (N1C) { 6947 unsigned ElementSize = VT.getSizeInBits(); 6948 unsigned Shift = ElementSize * N2C->getZExtValue(); 6949 const APInt &Val = N1C->getAPIntValue(); 6950 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6951 } 6952 break; 6953 case ISD::EXTRACT_SUBVECTOR: { 6954 EVT N1VT = N1.getValueType(); 6955 assert(VT.isVector() && N1VT.isVector() && 6956 "Extract subvector VTs must be vectors!"); 6957 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6958 "Extract subvector VTs must have the same element type!"); 6959 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6960 "Cannot extract a scalable vector from a fixed length vector!"); 6961 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6962 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6963 "Extract subvector must be from larger vector to smaller vector!"); 6964 assert(N2C && "Extract subvector index must be a constant"); 6965 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6966 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6967 N1VT.getVectorMinNumElements()) && 6968 "Extract subvector overflow!"); 6969 assert(N2C->getAPIntValue().getBitWidth() == 6970 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6971 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6972 6973 // Trivial extraction. 6974 if (VT == N1VT) 6975 return N1; 6976 6977 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6978 if (N1.isUndef()) 6979 return getUNDEF(VT); 6980 6981 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6982 // the concat have the same type as the extract. 6983 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 6984 VT == N1.getOperand(0).getValueType()) { 6985 unsigned Factor = VT.getVectorMinNumElements(); 6986 return N1.getOperand(N2C->getZExtValue() / Factor); 6987 } 6988 6989 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6990 // during shuffle legalization. 6991 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6992 VT == N1.getOperand(1).getValueType()) 6993 return N1.getOperand(1); 6994 break; 6995 } 6996 } 6997 6998 // Perform trivial constant folding. 6999 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 7000 return SV; 7001 7002 // Canonicalize an UNDEF to the RHS, even over a constant. 7003 if (N1.isUndef()) { 7004 if (TLI->isCommutativeBinOp(Opcode)) { 7005 std::swap(N1, N2); 7006 } else { 7007 switch (Opcode) { 7008 case ISD::SUB: 7009 return getUNDEF(VT); // fold op(undef, arg2) -> undef 7010 case ISD::SIGN_EXTEND_INREG: 7011 case ISD::UDIV: 7012 case ISD::SDIV: 7013 case ISD::UREM: 7014 case ISD::SREM: 7015 case ISD::SSUBSAT: 7016 case ISD::USUBSAT: 7017 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 7018 } 7019 } 7020 } 7021 7022 // Fold a bunch of operators when the RHS is undef. 7023 if (N2.isUndef()) { 7024 switch (Opcode) { 7025 case ISD::XOR: 7026 if (N1.isUndef()) 7027 // Handle undef ^ undef -> 0 special case. This is a common 7028 // idiom (misuse). 7029 return getConstant(0, DL, VT); 7030 [[fallthrough]]; 7031 case ISD::ADD: 7032 case ISD::SUB: 7033 case ISD::UDIV: 7034 case ISD::SDIV: 7035 case ISD::UREM: 7036 case ISD::SREM: 7037 return getUNDEF(VT); // fold op(arg1, undef) -> undef 7038 case ISD::MUL: 7039 case ISD::AND: 7040 case ISD::SSUBSAT: 7041 case ISD::USUBSAT: 7042 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 7043 case ISD::OR: 7044 case ISD::SADDSAT: 7045 case ISD::UADDSAT: 7046 return getAllOnesConstant(DL, VT); 7047 } 7048 } 7049 7050 // Memoize this node if possible. 7051 SDNode *N; 7052 SDVTList VTs = getVTList(VT); 7053 SDValue Ops[] = {N1, N2}; 7054 if (VT != MVT::Glue) { 7055 FoldingSetNodeID ID; 7056 AddNodeIDNode(ID, Opcode, VTs, Ops); 7057 void *IP = nullptr; 7058 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 7059 E->intersectFlagsWith(Flags); 7060 return SDValue(E, 0); 7061 } 7062 7063 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7064 N->setFlags(Flags); 7065 createOperands(N, Ops); 7066 CSEMap.InsertNode(N, IP); 7067 } else { 7068 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7069 createOperands(N, Ops); 7070 } 7071 7072 InsertNode(N); 7073 SDValue V = SDValue(N, 0); 7074 NewSDValueDbgMsg(V, "Creating new node: ", this); 7075 return V; 7076 } 7077 7078 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7079 SDValue N1, SDValue N2, SDValue N3) { 7080 SDNodeFlags Flags; 7081 if (Inserter) 7082 Flags = Inserter->getFlags(); 7083 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 7084 } 7085 7086 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7087 SDValue N1, SDValue N2, SDValue N3, 7088 const SDNodeFlags Flags) { 7089 assert(N1.getOpcode() != ISD::DELETED_NODE && 7090 N2.getOpcode() != ISD::DELETED_NODE && 7091 N3.getOpcode() != ISD::DELETED_NODE && 7092 "Operand is DELETED_NODE!"); 7093 // Perform various simplifications. 7094 switch (Opcode) { 7095 case ISD::FMA: 7096 case ISD::FMAD: { 7097 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 7098 assert(N1.getValueType() == VT && N2.getValueType() == VT && 7099 N3.getValueType() == VT && "FMA types must match!"); 7100 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7101 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 7102 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 7103 if (N1CFP && N2CFP && N3CFP) { 7104 APFloat V1 = N1CFP->getValueAPF(); 7105 const APFloat &V2 = N2CFP->getValueAPF(); 7106 const APFloat &V3 = N3CFP->getValueAPF(); 7107 if (Opcode == ISD::FMAD) { 7108 V1.multiply(V2, APFloat::rmNearestTiesToEven); 7109 V1.add(V3, APFloat::rmNearestTiesToEven); 7110 } else 7111 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 7112 return getConstantFP(V1, DL, VT); 7113 } 7114 break; 7115 } 7116 case ISD::BUILD_VECTOR: { 7117 // Attempt to simplify BUILD_VECTOR. 7118 SDValue Ops[] = {N1, N2, N3}; 7119 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 7120 return V; 7121 break; 7122 } 7123 case ISD::CONCAT_VECTORS: { 7124 SDValue Ops[] = {N1, N2, N3}; 7125 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 7126 return V; 7127 break; 7128 } 7129 case ISD::SETCC: { 7130 assert(VT.isInteger() && "SETCC result type must be an integer!"); 7131 assert(N1.getValueType() == N2.getValueType() && 7132 "SETCC operands must have the same type!"); 7133 assert(VT.isVector() == N1.getValueType().isVector() && 7134 "SETCC type should be vector iff the operand type is vector!"); 7135 assert((!VT.isVector() || VT.getVectorElementCount() == 7136 N1.getValueType().getVectorElementCount()) && 7137 "SETCC vector element counts must match!"); 7138 // Use FoldSetCC to simplify SETCC's. 7139 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 7140 return V; 7141 // Vector constant folding. 7142 SDValue Ops[] = {N1, N2, N3}; 7143 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 7144 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 7145 return V; 7146 } 7147 break; 7148 } 7149 case ISD::SELECT: 7150 case ISD::VSELECT: 7151 if (SDValue V = simplifySelect(N1, N2, N3)) 7152 return V; 7153 break; 7154 case ISD::VECTOR_SHUFFLE: 7155 llvm_unreachable("should use getVectorShuffle constructor!"); 7156 case ISD::VECTOR_SPLICE: { 7157 if (cast<ConstantSDNode>(N3)->isZero()) 7158 return N1; 7159 break; 7160 } 7161 case ISD::INSERT_VECTOR_ELT: { 7162 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 7163 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 7164 // for scalable vectors where we will generate appropriate code to 7165 // deal with out-of-bounds cases correctly. 7166 if (N3C && N1.getValueType().isFixedLengthVector() && 7167 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 7168 return getUNDEF(VT); 7169 7170 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 7171 if (N3.isUndef()) 7172 return getUNDEF(VT); 7173 7174 // If the inserted element is an UNDEF, just use the input vector. 7175 if (N2.isUndef()) 7176 return N1; 7177 7178 break; 7179 } 7180 case ISD::INSERT_SUBVECTOR: { 7181 // Inserting undef into undef is still undef. 7182 if (N1.isUndef() && N2.isUndef()) 7183 return getUNDEF(VT); 7184 7185 EVT N2VT = N2.getValueType(); 7186 assert(VT == N1.getValueType() && 7187 "Dest and insert subvector source types must match!"); 7188 assert(VT.isVector() && N2VT.isVector() && 7189 "Insert subvector VTs must be vectors!"); 7190 assert(VT.getVectorElementType() == N2VT.getVectorElementType() && 7191 "Insert subvector VTs must have the same element type!"); 7192 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 7193 "Cannot insert a scalable vector into a fixed length vector!"); 7194 assert((VT.isScalableVector() != N2VT.isScalableVector() || 7195 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 7196 "Insert subvector must be from smaller vector to larger vector!"); 7197 assert(isa<ConstantSDNode>(N3) && 7198 "Insert subvector index must be constant"); 7199 assert((VT.isScalableVector() != N2VT.isScalableVector() || 7200 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <= 7201 VT.getVectorMinNumElements()) && 7202 "Insert subvector overflow!"); 7203 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 7204 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 7205 "Constant index for INSERT_SUBVECTOR has an invalid size"); 7206 7207 // Trivial insertion. 7208 if (VT == N2VT) 7209 return N2; 7210 7211 // If this is an insert of an extracted vector into an undef vector, we 7212 // can just use the input to the extract. 7213 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 7214 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 7215 return N2.getOperand(0); 7216 break; 7217 } 7218 case ISD::BITCAST: 7219 // Fold bit_convert nodes from a type to themselves. 7220 if (N1.getValueType() == VT) 7221 return N1; 7222 break; 7223 case ISD::VP_TRUNCATE: 7224 case ISD::VP_SIGN_EXTEND: 7225 case ISD::VP_ZERO_EXTEND: 7226 // Don't create noop casts. 7227 if (N1.getValueType() == VT) 7228 return N1; 7229 break; 7230 } 7231 7232 // Memoize node if it doesn't produce a glue result. 7233 SDNode *N; 7234 SDVTList VTs = getVTList(VT); 7235 SDValue Ops[] = {N1, N2, N3}; 7236 if (VT != MVT::Glue) { 7237 FoldingSetNodeID ID; 7238 AddNodeIDNode(ID, Opcode, VTs, Ops); 7239 void *IP = nullptr; 7240 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 7241 E->intersectFlagsWith(Flags); 7242 return SDValue(E, 0); 7243 } 7244 7245 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7246 N->setFlags(Flags); 7247 createOperands(N, Ops); 7248 CSEMap.InsertNode(N, IP); 7249 } else { 7250 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7251 createOperands(N, Ops); 7252 } 7253 7254 InsertNode(N); 7255 SDValue V = SDValue(N, 0); 7256 NewSDValueDbgMsg(V, "Creating new node: ", this); 7257 return V; 7258 } 7259 7260 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7261 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 7262 SDValue Ops[] = { N1, N2, N3, N4 }; 7263 return getNode(Opcode, DL, VT, Ops); 7264 } 7265 7266 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7267 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 7268 SDValue N5) { 7269 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 7270 return getNode(Opcode, DL, VT, Ops); 7271 } 7272 7273 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 7274 /// the incoming stack arguments to be loaded from the stack. 7275 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 7276 SmallVector<SDValue, 8> ArgChains; 7277 7278 // Include the original chain at the beginning of the list. When this is 7279 // used by target LowerCall hooks, this helps legalize find the 7280 // CALLSEQ_BEGIN node. 7281 ArgChains.push_back(Chain); 7282 7283 // Add a chain value for each stack argument. 7284 for (SDNode *U : getEntryNode().getNode()->uses()) 7285 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 7286 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 7287 if (FI->getIndex() < 0) 7288 ArgChains.push_back(SDValue(L, 1)); 7289 7290 // Build a tokenfactor for all the chains. 7291 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 7292 } 7293 7294 /// getMemsetValue - Vectorized representation of the memset value 7295 /// operand. 7296 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 7297 const SDLoc &dl) { 7298 assert(!Value.isUndef()); 7299 7300 unsigned NumBits = VT.getScalarSizeInBits(); 7301 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 7302 assert(C->getAPIntValue().getBitWidth() == 8); 7303 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 7304 if (VT.isInteger()) { 7305 bool IsOpaque = VT.getSizeInBits() > 64 || 7306 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 7307 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 7308 } 7309 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 7310 VT); 7311 } 7312 7313 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 7314 EVT IntVT = VT.getScalarType(); 7315 if (!IntVT.isInteger()) 7316 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 7317 7318 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 7319 if (NumBits > 8) { 7320 // Use a multiplication with 0x010101... to extend the input to the 7321 // required length. 7322 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 7323 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 7324 DAG.getConstant(Magic, dl, IntVT)); 7325 } 7326 7327 if (VT != Value.getValueType() && !VT.isInteger()) 7328 Value = DAG.getBitcast(VT.getScalarType(), Value); 7329 if (VT != Value.getValueType()) 7330 Value = DAG.getSplatBuildVector(VT, dl, Value); 7331 7332 return Value; 7333 } 7334 7335 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 7336 /// used when a memcpy is turned into a memset when the source is a constant 7337 /// string ptr. 7338 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 7339 const TargetLowering &TLI, 7340 const ConstantDataArraySlice &Slice) { 7341 // Handle vector with all elements zero. 7342 if (Slice.Array == nullptr) { 7343 if (VT.isInteger()) 7344 return DAG.getConstant(0, dl, VT); 7345 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 7346 return DAG.getConstantFP(0.0, dl, VT); 7347 if (VT.isVector()) { 7348 unsigned NumElts = VT.getVectorNumElements(); 7349 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 7350 return DAG.getNode(ISD::BITCAST, dl, VT, 7351 DAG.getConstant(0, dl, 7352 EVT::getVectorVT(*DAG.getContext(), 7353 EltVT, NumElts))); 7354 } 7355 llvm_unreachable("Expected type!"); 7356 } 7357 7358 assert(!VT.isVector() && "Can't handle vector type here!"); 7359 unsigned NumVTBits = VT.getSizeInBits(); 7360 unsigned NumVTBytes = NumVTBits / 8; 7361 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 7362 7363 APInt Val(NumVTBits, 0); 7364 if (DAG.getDataLayout().isLittleEndian()) { 7365 for (unsigned i = 0; i != NumBytes; ++i) 7366 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 7367 } else { 7368 for (unsigned i = 0; i != NumBytes; ++i) 7369 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 7370 } 7371 7372 // If the "cost" of materializing the integer immediate is less than the cost 7373 // of a load, then it is cost effective to turn the load into the immediate. 7374 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 7375 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 7376 return DAG.getConstant(Val, dl, VT); 7377 return SDValue(); 7378 } 7379 7380 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 7381 const SDLoc &DL, 7382 const SDNodeFlags Flags) { 7383 EVT VT = Base.getValueType(); 7384 SDValue Index; 7385 7386 if (Offset.isScalable()) 7387 Index = getVScale(DL, Base.getValueType(), 7388 APInt(Base.getValueSizeInBits().getFixedValue(), 7389 Offset.getKnownMinValue())); 7390 else 7391 Index = getConstant(Offset.getFixedValue(), DL, VT); 7392 7393 return getMemBasePlusOffset(Base, Index, DL, Flags); 7394 } 7395 7396 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 7397 const SDLoc &DL, 7398 const SDNodeFlags Flags) { 7399 assert(Offset.getValueType().isInteger()); 7400 EVT BasePtrVT = Ptr.getValueType(); 7401 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 7402 } 7403 7404 /// Returns true if memcpy source is constant data. 7405 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 7406 uint64_t SrcDelta = 0; 7407 GlobalAddressSDNode *G = nullptr; 7408 if (Src.getOpcode() == ISD::GlobalAddress) 7409 G = cast<GlobalAddressSDNode>(Src); 7410 else if (Src.getOpcode() == ISD::ADD && 7411 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 7412 Src.getOperand(1).getOpcode() == ISD::Constant) { 7413 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 7414 SrcDelta = Src.getConstantOperandVal(1); 7415 } 7416 if (!G) 7417 return false; 7418 7419 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 7420 SrcDelta + G->getOffset()); 7421 } 7422 7423 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 7424 SelectionDAG &DAG) { 7425 // On Darwin, -Os means optimize for size without hurting performance, so 7426 // only really optimize for size when -Oz (MinSize) is used. 7427 if (MF.getTarget().getTargetTriple().isOSDarwin()) 7428 return MF.getFunction().hasMinSize(); 7429 return DAG.shouldOptForSize(); 7430 } 7431 7432 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 7433 SmallVector<SDValue, 32> &OutChains, unsigned From, 7434 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 7435 SmallVector<SDValue, 16> &OutStoreChains) { 7436 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 7437 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 7438 SmallVector<SDValue, 16> GluedLoadChains; 7439 for (unsigned i = From; i < To; ++i) { 7440 OutChains.push_back(OutLoadChains[i]); 7441 GluedLoadChains.push_back(OutLoadChains[i]); 7442 } 7443 7444 // Chain for all loads. 7445 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7446 GluedLoadChains); 7447 7448 for (unsigned i = From; i < To; ++i) { 7449 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 7450 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 7451 ST->getBasePtr(), ST->getMemoryVT(), 7452 ST->getMemOperand()); 7453 OutChains.push_back(NewStore); 7454 } 7455 } 7456 7457 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 7458 SDValue Chain, SDValue Dst, SDValue Src, 7459 uint64_t Size, Align Alignment, 7460 bool isVol, bool AlwaysInline, 7461 MachinePointerInfo DstPtrInfo, 7462 MachinePointerInfo SrcPtrInfo, 7463 const AAMDNodes &AAInfo, AAResults *AA) { 7464 // Turn a memcpy of undef to nop. 7465 // FIXME: We need to honor volatile even is Src is undef. 7466 if (Src.isUndef()) 7467 return Chain; 7468 7469 // Expand memcpy to a series of load and store ops if the size operand falls 7470 // below a certain threshold. 7471 // TODO: In the AlwaysInline case, if the size is big then generate a loop 7472 // rather than maybe a humongous number of loads and stores. 7473 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7474 const DataLayout &DL = DAG.getDataLayout(); 7475 LLVMContext &C = *DAG.getContext(); 7476 std::vector<EVT> MemOps; 7477 bool DstAlignCanChange = false; 7478 MachineFunction &MF = DAG.getMachineFunction(); 7479 MachineFrameInfo &MFI = MF.getFrameInfo(); 7480 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7481 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7482 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7483 DstAlignCanChange = true; 7484 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 7485 if (!SrcAlign || Alignment > *SrcAlign) 7486 SrcAlign = Alignment; 7487 assert(SrcAlign && "SrcAlign must be set"); 7488 ConstantDataArraySlice Slice; 7489 // If marked as volatile, perform a copy even when marked as constant. 7490 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 7491 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 7492 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 7493 const MemOp Op = isZeroConstant 7494 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 7495 /*IsZeroMemset*/ true, isVol) 7496 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 7497 *SrcAlign, isVol, CopyFromConstant); 7498 if (!TLI.findOptimalMemOpLowering( 7499 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 7500 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 7501 return SDValue(); 7502 7503 if (DstAlignCanChange) { 7504 Type *Ty = MemOps[0].getTypeForEVT(C); 7505 Align NewAlign = DL.getABITypeAlign(Ty); 7506 7507 // Don't promote to an alignment that would require dynamic stack 7508 // realignment which may conflict with optimizations such as tail call 7509 // optimization. 7510 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 7511 if (!TRI->hasStackRealignment(MF)) 7512 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 7513 NewAlign = NewAlign.previous(); 7514 7515 if (NewAlign > Alignment) { 7516 // Give the stack frame object a larger alignment if needed. 7517 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7518 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7519 Alignment = NewAlign; 7520 } 7521 } 7522 7523 // Prepare AAInfo for loads/stores after lowering this memcpy. 7524 AAMDNodes NewAAInfo = AAInfo; 7525 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7526 7527 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V); 7528 bool isConstant = 7529 AA && SrcVal && 7530 AA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo)); 7531 7532 MachineMemOperand::Flags MMOFlags = 7533 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 7534 SmallVector<SDValue, 16> OutLoadChains; 7535 SmallVector<SDValue, 16> OutStoreChains; 7536 SmallVector<SDValue, 32> OutChains; 7537 unsigned NumMemOps = MemOps.size(); 7538 uint64_t SrcOff = 0, DstOff = 0; 7539 for (unsigned i = 0; i != NumMemOps; ++i) { 7540 EVT VT = MemOps[i]; 7541 unsigned VTSize = VT.getSizeInBits() / 8; 7542 SDValue Value, Store; 7543 7544 if (VTSize > Size) { 7545 // Issuing an unaligned load / store pair that overlaps with the previous 7546 // pair. Adjust the offset accordingly. 7547 assert(i == NumMemOps-1 && i != 0); 7548 SrcOff -= VTSize - Size; 7549 DstOff -= VTSize - Size; 7550 } 7551 7552 if (CopyFromConstant && 7553 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 7554 // It's unlikely a store of a vector immediate can be done in a single 7555 // instruction. It would require a load from a constantpool first. 7556 // We only handle zero vectors here. 7557 // FIXME: Handle other cases where store of vector immediate is done in 7558 // a single instruction. 7559 ConstantDataArraySlice SubSlice; 7560 if (SrcOff < Slice.Length) { 7561 SubSlice = Slice; 7562 SubSlice.move(SrcOff); 7563 } else { 7564 // This is an out-of-bounds access and hence UB. Pretend we read zero. 7565 SubSlice.Array = nullptr; 7566 SubSlice.Offset = 0; 7567 SubSlice.Length = VTSize; 7568 } 7569 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 7570 if (Value.getNode()) { 7571 Store = DAG.getStore( 7572 Chain, dl, Value, 7573 DAG.getMemBasePlusOffset(Dst, TypeSize::getFixed(DstOff), dl), 7574 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 7575 OutChains.push_back(Store); 7576 } 7577 } 7578 7579 if (!Store.getNode()) { 7580 // The type might not be legal for the target. This should only happen 7581 // if the type is smaller than a legal type, as on PPC, so the right 7582 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 7583 // to Load/Store if NVT==VT. 7584 // FIXME does the case above also need this? 7585 EVT NVT = TLI.getTypeToTransformTo(C, VT); 7586 assert(NVT.bitsGE(VT)); 7587 7588 bool isDereferenceable = 7589 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 7590 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 7591 if (isDereferenceable) 7592 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 7593 if (isConstant) 7594 SrcMMOFlags |= MachineMemOperand::MOInvariant; 7595 7596 Value = DAG.getExtLoad( 7597 ISD::EXTLOAD, dl, NVT, Chain, 7598 DAG.getMemBasePlusOffset(Src, TypeSize::getFixed(SrcOff), dl), 7599 SrcPtrInfo.getWithOffset(SrcOff), VT, 7600 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 7601 OutLoadChains.push_back(Value.getValue(1)); 7602 7603 Store = DAG.getTruncStore( 7604 Chain, dl, Value, 7605 DAG.getMemBasePlusOffset(Dst, TypeSize::getFixed(DstOff), dl), 7606 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 7607 OutStoreChains.push_back(Store); 7608 } 7609 SrcOff += VTSize; 7610 DstOff += VTSize; 7611 Size -= VTSize; 7612 } 7613 7614 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 7615 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 7616 unsigned NumLdStInMemcpy = OutStoreChains.size(); 7617 7618 if (NumLdStInMemcpy) { 7619 // It may be that memcpy might be converted to memset if it's memcpy 7620 // of constants. In such a case, we won't have loads and stores, but 7621 // just stores. In the absence of loads, there is nothing to gang up. 7622 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 7623 // If target does not care, just leave as it. 7624 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 7625 OutChains.push_back(OutLoadChains[i]); 7626 OutChains.push_back(OutStoreChains[i]); 7627 } 7628 } else { 7629 // Ld/St less than/equal limit set by target. 7630 if (NumLdStInMemcpy <= GluedLdStLimit) { 7631 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 7632 NumLdStInMemcpy, OutLoadChains, 7633 OutStoreChains); 7634 } else { 7635 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 7636 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 7637 unsigned GlueIter = 0; 7638 7639 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 7640 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 7641 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 7642 7643 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 7644 OutLoadChains, OutStoreChains); 7645 GlueIter += GluedLdStLimit; 7646 } 7647 7648 // Residual ld/st. 7649 if (RemainingLdStInMemcpy) { 7650 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 7651 RemainingLdStInMemcpy, OutLoadChains, 7652 OutStoreChains); 7653 } 7654 } 7655 } 7656 } 7657 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7658 } 7659 7660 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 7661 SDValue Chain, SDValue Dst, SDValue Src, 7662 uint64_t Size, Align Alignment, 7663 bool isVol, bool AlwaysInline, 7664 MachinePointerInfo DstPtrInfo, 7665 MachinePointerInfo SrcPtrInfo, 7666 const AAMDNodes &AAInfo) { 7667 // Turn a memmove of undef to nop. 7668 // FIXME: We need to honor volatile even is Src is undef. 7669 if (Src.isUndef()) 7670 return Chain; 7671 7672 // Expand memmove to a series of load and store ops if the size operand falls 7673 // below a certain threshold. 7674 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7675 const DataLayout &DL = DAG.getDataLayout(); 7676 LLVMContext &C = *DAG.getContext(); 7677 std::vector<EVT> MemOps; 7678 bool DstAlignCanChange = false; 7679 MachineFunction &MF = DAG.getMachineFunction(); 7680 MachineFrameInfo &MFI = MF.getFrameInfo(); 7681 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7682 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7683 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7684 DstAlignCanChange = true; 7685 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 7686 if (!SrcAlign || Alignment > *SrcAlign) 7687 SrcAlign = Alignment; 7688 assert(SrcAlign && "SrcAlign must be set"); 7689 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 7690 if (!TLI.findOptimalMemOpLowering( 7691 MemOps, Limit, 7692 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 7693 /*IsVolatile*/ true), 7694 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 7695 MF.getFunction().getAttributes())) 7696 return SDValue(); 7697 7698 if (DstAlignCanChange) { 7699 Type *Ty = MemOps[0].getTypeForEVT(C); 7700 Align NewAlign = DL.getABITypeAlign(Ty); 7701 7702 // Don't promote to an alignment that would require dynamic stack 7703 // realignment which may conflict with optimizations such as tail call 7704 // optimization. 7705 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 7706 if (!TRI->hasStackRealignment(MF)) 7707 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 7708 NewAlign = NewAlign.previous(); 7709 7710 if (NewAlign > Alignment) { 7711 // Give the stack frame object a larger alignment if needed. 7712 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7713 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7714 Alignment = NewAlign; 7715 } 7716 } 7717 7718 // Prepare AAInfo for loads/stores after lowering this memmove. 7719 AAMDNodes NewAAInfo = AAInfo; 7720 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7721 7722 MachineMemOperand::Flags MMOFlags = 7723 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 7724 uint64_t SrcOff = 0, DstOff = 0; 7725 SmallVector<SDValue, 8> LoadValues; 7726 SmallVector<SDValue, 8> LoadChains; 7727 SmallVector<SDValue, 8> OutChains; 7728 unsigned NumMemOps = MemOps.size(); 7729 for (unsigned i = 0; i < NumMemOps; i++) { 7730 EVT VT = MemOps[i]; 7731 unsigned VTSize = VT.getSizeInBits() / 8; 7732 SDValue Value; 7733 7734 bool isDereferenceable = 7735 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 7736 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 7737 if (isDereferenceable) 7738 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 7739 7740 Value = DAG.getLoad( 7741 VT, dl, Chain, 7742 DAG.getMemBasePlusOffset(Src, TypeSize::getFixed(SrcOff), dl), 7743 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 7744 LoadValues.push_back(Value); 7745 LoadChains.push_back(Value.getValue(1)); 7746 SrcOff += VTSize; 7747 } 7748 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 7749 OutChains.clear(); 7750 for (unsigned i = 0; i < NumMemOps; i++) { 7751 EVT VT = MemOps[i]; 7752 unsigned VTSize = VT.getSizeInBits() / 8; 7753 SDValue Store; 7754 7755 Store = DAG.getStore( 7756 Chain, dl, LoadValues[i], 7757 DAG.getMemBasePlusOffset(Dst, TypeSize::getFixed(DstOff), dl), 7758 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 7759 OutChains.push_back(Store); 7760 DstOff += VTSize; 7761 } 7762 7763 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7764 } 7765 7766 /// Lower the call to 'memset' intrinsic function into a series of store 7767 /// operations. 7768 /// 7769 /// \param DAG Selection DAG where lowered code is placed. 7770 /// \param dl Link to corresponding IR location. 7771 /// \param Chain Control flow dependency. 7772 /// \param Dst Pointer to destination memory location. 7773 /// \param Src Value of byte to write into the memory. 7774 /// \param Size Number of bytes to write. 7775 /// \param Alignment Alignment of the destination in bytes. 7776 /// \param isVol True if destination is volatile. 7777 /// \param AlwaysInline Makes sure no function call is generated. 7778 /// \param DstPtrInfo IR information on the memory pointer. 7779 /// \returns New head in the control flow, if lowering was successful, empty 7780 /// SDValue otherwise. 7781 /// 7782 /// The function tries to replace 'llvm.memset' intrinsic with several store 7783 /// operations and value calculation code. This is usually profitable for small 7784 /// memory size or when the semantic requires inlining. 7785 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 7786 SDValue Chain, SDValue Dst, SDValue Src, 7787 uint64_t Size, Align Alignment, bool isVol, 7788 bool AlwaysInline, MachinePointerInfo DstPtrInfo, 7789 const AAMDNodes &AAInfo) { 7790 // Turn a memset of undef to nop. 7791 // FIXME: We need to honor volatile even is Src is undef. 7792 if (Src.isUndef()) 7793 return Chain; 7794 7795 // Expand memset to a series of load/store ops if the size operand 7796 // falls below a certain threshold. 7797 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7798 std::vector<EVT> MemOps; 7799 bool DstAlignCanChange = false; 7800 MachineFunction &MF = DAG.getMachineFunction(); 7801 MachineFrameInfo &MFI = MF.getFrameInfo(); 7802 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7803 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7804 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7805 DstAlignCanChange = true; 7806 bool IsZeroVal = isNullConstant(Src); 7807 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize); 7808 7809 if (!TLI.findOptimalMemOpLowering( 7810 MemOps, Limit, 7811 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 7812 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 7813 return SDValue(); 7814 7815 if (DstAlignCanChange) { 7816 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 7817 const DataLayout &DL = DAG.getDataLayout(); 7818 Align NewAlign = DL.getABITypeAlign(Ty); 7819 7820 // Don't promote to an alignment that would require dynamic stack 7821 // realignment which may conflict with optimizations such as tail call 7822 // optimization. 7823 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 7824 if (!TRI->hasStackRealignment(MF)) 7825 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 7826 NewAlign = NewAlign.previous(); 7827 7828 if (NewAlign > Alignment) { 7829 // Give the stack frame object a larger alignment if needed. 7830 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7831 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7832 Alignment = NewAlign; 7833 } 7834 } 7835 7836 SmallVector<SDValue, 8> OutChains; 7837 uint64_t DstOff = 0; 7838 unsigned NumMemOps = MemOps.size(); 7839 7840 // Find the largest store and generate the bit pattern for it. 7841 EVT LargestVT = MemOps[0]; 7842 for (unsigned i = 1; i < NumMemOps; i++) 7843 if (MemOps[i].bitsGT(LargestVT)) 7844 LargestVT = MemOps[i]; 7845 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 7846 7847 // Prepare AAInfo for loads/stores after lowering this memset. 7848 AAMDNodes NewAAInfo = AAInfo; 7849 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7850 7851 for (unsigned i = 0; i < NumMemOps; i++) { 7852 EVT VT = MemOps[i]; 7853 unsigned VTSize = VT.getSizeInBits() / 8; 7854 if (VTSize > Size) { 7855 // Issuing an unaligned load / store pair that overlaps with the previous 7856 // pair. Adjust the offset accordingly. 7857 assert(i == NumMemOps-1 && i != 0); 7858 DstOff -= VTSize - Size; 7859 } 7860 7861 // If this store is smaller than the largest store see whether we can get 7862 // the smaller value for free with a truncate or extract vector element and 7863 // then store. 7864 SDValue Value = MemSetValue; 7865 if (VT.bitsLT(LargestVT)) { 7866 unsigned Index; 7867 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits(); 7868 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts); 7869 if (!LargestVT.isVector() && !VT.isVector() && 7870 TLI.isTruncateFree(LargestVT, VT)) 7871 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7872 else if (LargestVT.isVector() && !VT.isVector() && 7873 TLI.shallExtractConstSplatVectorElementToStore( 7874 LargestVT.getTypeForEVT(*DAG.getContext()), 7875 VT.getSizeInBits(), Index) && 7876 TLI.isTypeLegal(SVT) && 7877 LargestVT.getSizeInBits() == SVT.getSizeInBits()) { 7878 // Target which can combine store(extractelement VectorTy, Idx) can get 7879 // the smaller value for free. 7880 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue); 7881 Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, TailValue, 7882 DAG.getVectorIdxConstant(Index, dl)); 7883 } else 7884 Value = getMemsetValue(Src, VT, DAG, dl); 7885 } 7886 assert(Value.getValueType() == VT && "Value with wrong type."); 7887 SDValue Store = DAG.getStore( 7888 Chain, dl, Value, 7889 DAG.getMemBasePlusOffset(Dst, TypeSize::getFixed(DstOff), dl), 7890 DstPtrInfo.getWithOffset(DstOff), Alignment, 7891 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7892 NewAAInfo); 7893 OutChains.push_back(Store); 7894 DstOff += VT.getSizeInBits() / 8; 7895 Size -= VTSize; 7896 } 7897 7898 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7899 } 7900 7901 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7902 unsigned AS) { 7903 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7904 // pointer operands can be losslessly bitcasted to pointers of address space 0 7905 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7906 report_fatal_error("cannot lower memory intrinsic in address space " + 7907 Twine(AS)); 7908 } 7909 } 7910 7911 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7912 SDValue Src, SDValue Size, Align Alignment, 7913 bool isVol, bool AlwaysInline, bool isTailCall, 7914 MachinePointerInfo DstPtrInfo, 7915 MachinePointerInfo SrcPtrInfo, 7916 const AAMDNodes &AAInfo, AAResults *AA) { 7917 // Check to see if we should lower the memcpy to loads and stores first. 7918 // For cases within the target-specified limits, this is the best choice. 7919 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7920 if (ConstantSize) { 7921 // Memcpy with size zero? Just return the original chain. 7922 if (ConstantSize->isZero()) 7923 return Chain; 7924 7925 SDValue Result = getMemcpyLoadsAndStores( 7926 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7927 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, AA); 7928 if (Result.getNode()) 7929 return Result; 7930 } 7931 7932 // Then check to see if we should lower the memcpy with target-specific 7933 // code. If the target chooses to do this, this is the next best. 7934 if (TSI) { 7935 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7936 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7937 DstPtrInfo, SrcPtrInfo); 7938 if (Result.getNode()) 7939 return Result; 7940 } 7941 7942 // If we really need inline code and the target declined to provide it, 7943 // use a (potentially long) sequence of loads and stores. 7944 if (AlwaysInline) { 7945 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7946 return getMemcpyLoadsAndStores( 7947 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7948 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, AA); 7949 } 7950 7951 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7952 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7953 7954 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7955 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7956 // respect volatile, so they may do things like read or write memory 7957 // beyond the given memory regions. But fixing this isn't easy, and most 7958 // people don't care. 7959 7960 // Emit a library call. 7961 TargetLowering::ArgListTy Args; 7962 TargetLowering::ArgListEntry Entry; 7963 Entry.Ty = PointerType::getUnqual(*getContext()); 7964 Entry.Node = Dst; Args.push_back(Entry); 7965 Entry.Node = Src; Args.push_back(Entry); 7966 7967 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7968 Entry.Node = Size; Args.push_back(Entry); 7969 // FIXME: pass in SDLoc 7970 TargetLowering::CallLoweringInfo CLI(*this); 7971 CLI.setDebugLoc(dl) 7972 .setChain(Chain) 7973 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7974 Dst.getValueType().getTypeForEVT(*getContext()), 7975 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7976 TLI->getPointerTy(getDataLayout())), 7977 std::move(Args)) 7978 .setDiscardResult() 7979 .setTailCall(isTailCall); 7980 7981 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7982 return CallResult.second; 7983 } 7984 7985 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7986 SDValue Dst, SDValue Src, SDValue Size, 7987 Type *SizeTy, unsigned ElemSz, 7988 bool isTailCall, 7989 MachinePointerInfo DstPtrInfo, 7990 MachinePointerInfo SrcPtrInfo) { 7991 // Emit a library call. 7992 TargetLowering::ArgListTy Args; 7993 TargetLowering::ArgListEntry Entry; 7994 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7995 Entry.Node = Dst; 7996 Args.push_back(Entry); 7997 7998 Entry.Node = Src; 7999 Args.push_back(Entry); 8000 8001 Entry.Ty = SizeTy; 8002 Entry.Node = Size; 8003 Args.push_back(Entry); 8004 8005 RTLIB::Libcall LibraryCall = 8006 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 8007 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 8008 report_fatal_error("Unsupported element size"); 8009 8010 TargetLowering::CallLoweringInfo CLI(*this); 8011 CLI.setDebugLoc(dl) 8012 .setChain(Chain) 8013 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 8014 Type::getVoidTy(*getContext()), 8015 getExternalSymbol(TLI->getLibcallName(LibraryCall), 8016 TLI->getPointerTy(getDataLayout())), 8017 std::move(Args)) 8018 .setDiscardResult() 8019 .setTailCall(isTailCall); 8020 8021 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 8022 return CallResult.second; 8023 } 8024 8025 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 8026 SDValue Src, SDValue Size, Align Alignment, 8027 bool isVol, bool isTailCall, 8028 MachinePointerInfo DstPtrInfo, 8029 MachinePointerInfo SrcPtrInfo, 8030 const AAMDNodes &AAInfo, AAResults *AA) { 8031 // Check to see if we should lower the memmove to loads and stores first. 8032 // For cases within the target-specified limits, this is the best choice. 8033 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 8034 if (ConstantSize) { 8035 // Memmove with size zero? Just return the original chain. 8036 if (ConstantSize->isZero()) 8037 return Chain; 8038 8039 SDValue Result = getMemmoveLoadsAndStores( 8040 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 8041 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 8042 if (Result.getNode()) 8043 return Result; 8044 } 8045 8046 // Then check to see if we should lower the memmove with target-specific 8047 // code. If the target chooses to do this, this is the next best. 8048 if (TSI) { 8049 SDValue Result = 8050 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 8051 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 8052 if (Result.getNode()) 8053 return Result; 8054 } 8055 8056 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 8057 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 8058 8059 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 8060 // not be safe. See memcpy above for more details. 8061 8062 // Emit a library call. 8063 TargetLowering::ArgListTy Args; 8064 TargetLowering::ArgListEntry Entry; 8065 Entry.Ty = PointerType::getUnqual(*getContext()); 8066 Entry.Node = Dst; Args.push_back(Entry); 8067 Entry.Node = Src; Args.push_back(Entry); 8068 8069 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 8070 Entry.Node = Size; Args.push_back(Entry); 8071 // FIXME: pass in SDLoc 8072 TargetLowering::CallLoweringInfo CLI(*this); 8073 CLI.setDebugLoc(dl) 8074 .setChain(Chain) 8075 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 8076 Dst.getValueType().getTypeForEVT(*getContext()), 8077 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 8078 TLI->getPointerTy(getDataLayout())), 8079 std::move(Args)) 8080 .setDiscardResult() 8081 .setTailCall(isTailCall); 8082 8083 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 8084 return CallResult.second; 8085 } 8086 8087 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 8088 SDValue Dst, SDValue Src, SDValue Size, 8089 Type *SizeTy, unsigned ElemSz, 8090 bool isTailCall, 8091 MachinePointerInfo DstPtrInfo, 8092 MachinePointerInfo SrcPtrInfo) { 8093 // Emit a library call. 8094 TargetLowering::ArgListTy Args; 8095 TargetLowering::ArgListEntry Entry; 8096 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 8097 Entry.Node = Dst; 8098 Args.push_back(Entry); 8099 8100 Entry.Node = Src; 8101 Args.push_back(Entry); 8102 8103 Entry.Ty = SizeTy; 8104 Entry.Node = Size; 8105 Args.push_back(Entry); 8106 8107 RTLIB::Libcall LibraryCall = 8108 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 8109 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 8110 report_fatal_error("Unsupported element size"); 8111 8112 TargetLowering::CallLoweringInfo CLI(*this); 8113 CLI.setDebugLoc(dl) 8114 .setChain(Chain) 8115 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 8116 Type::getVoidTy(*getContext()), 8117 getExternalSymbol(TLI->getLibcallName(LibraryCall), 8118 TLI->getPointerTy(getDataLayout())), 8119 std::move(Args)) 8120 .setDiscardResult() 8121 .setTailCall(isTailCall); 8122 8123 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 8124 return CallResult.second; 8125 } 8126 8127 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 8128 SDValue Src, SDValue Size, Align Alignment, 8129 bool isVol, bool AlwaysInline, bool isTailCall, 8130 MachinePointerInfo DstPtrInfo, 8131 const AAMDNodes &AAInfo) { 8132 // Check to see if we should lower the memset to stores first. 8133 // For cases within the target-specified limits, this is the best choice. 8134 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 8135 if (ConstantSize) { 8136 // Memset with size zero? Just return the original chain. 8137 if (ConstantSize->isZero()) 8138 return Chain; 8139 8140 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 8141 ConstantSize->getZExtValue(), Alignment, 8142 isVol, false, DstPtrInfo, AAInfo); 8143 8144 if (Result.getNode()) 8145 return Result; 8146 } 8147 8148 // Then check to see if we should lower the memset with target-specific 8149 // code. If the target chooses to do this, this is the next best. 8150 if (TSI) { 8151 SDValue Result = TSI->EmitTargetCodeForMemset( 8152 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo); 8153 if (Result.getNode()) 8154 return Result; 8155 } 8156 8157 // If we really need inline code and the target declined to provide it, 8158 // use a (potentially long) sequence of loads and stores. 8159 if (AlwaysInline) { 8160 assert(ConstantSize && "AlwaysInline requires a constant size!"); 8161 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 8162 ConstantSize->getZExtValue(), Alignment, 8163 isVol, true, DstPtrInfo, AAInfo); 8164 assert(Result && 8165 "getMemsetStores must return a valid sequence when AlwaysInline"); 8166 return Result; 8167 } 8168 8169 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 8170 8171 // Emit a library call. 8172 auto &Ctx = *getContext(); 8173 const auto& DL = getDataLayout(); 8174 8175 TargetLowering::CallLoweringInfo CLI(*this); 8176 // FIXME: pass in SDLoc 8177 CLI.setDebugLoc(dl).setChain(Chain); 8178 8179 const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO); 8180 8181 // Helper function to create an Entry from Node and Type. 8182 const auto CreateEntry = [](SDValue Node, Type *Ty) { 8183 TargetLowering::ArgListEntry Entry; 8184 Entry.Node = Node; 8185 Entry.Ty = Ty; 8186 return Entry; 8187 }; 8188 8189 // If zeroing out and bzero is present, use it. 8190 if (isNullConstant(Src) && BzeroName) { 8191 TargetLowering::ArgListTy Args; 8192 Args.push_back(CreateEntry(Dst, PointerType::getUnqual(Ctx))); 8193 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 8194 CLI.setLibCallee( 8195 TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx), 8196 getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args)); 8197 } else { 8198 TargetLowering::ArgListTy Args; 8199 Args.push_back(CreateEntry(Dst, PointerType::getUnqual(Ctx))); 8200 Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx))); 8201 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 8202 CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 8203 Dst.getValueType().getTypeForEVT(Ctx), 8204 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 8205 TLI->getPointerTy(DL)), 8206 std::move(Args)); 8207 } 8208 8209 CLI.setDiscardResult().setTailCall(isTailCall); 8210 8211 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 8212 return CallResult.second; 8213 } 8214 8215 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 8216 SDValue Dst, SDValue Value, SDValue Size, 8217 Type *SizeTy, unsigned ElemSz, 8218 bool isTailCall, 8219 MachinePointerInfo DstPtrInfo) { 8220 // Emit a library call. 8221 TargetLowering::ArgListTy Args; 8222 TargetLowering::ArgListEntry Entry; 8223 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 8224 Entry.Node = Dst; 8225 Args.push_back(Entry); 8226 8227 Entry.Ty = Type::getInt8Ty(*getContext()); 8228 Entry.Node = Value; 8229 Args.push_back(Entry); 8230 8231 Entry.Ty = SizeTy; 8232 Entry.Node = Size; 8233 Args.push_back(Entry); 8234 8235 RTLIB::Libcall LibraryCall = 8236 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 8237 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 8238 report_fatal_error("Unsupported element size"); 8239 8240 TargetLowering::CallLoweringInfo CLI(*this); 8241 CLI.setDebugLoc(dl) 8242 .setChain(Chain) 8243 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 8244 Type::getVoidTy(*getContext()), 8245 getExternalSymbol(TLI->getLibcallName(LibraryCall), 8246 TLI->getPointerTy(getDataLayout())), 8247 std::move(Args)) 8248 .setDiscardResult() 8249 .setTailCall(isTailCall); 8250 8251 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 8252 return CallResult.second; 8253 } 8254 8255 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 8256 SDVTList VTList, ArrayRef<SDValue> Ops, 8257 MachineMemOperand *MMO) { 8258 FoldingSetNodeID ID; 8259 ID.AddInteger(MemVT.getRawBits()); 8260 AddNodeIDNode(ID, Opcode, VTList, Ops); 8261 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8262 ID.AddInteger(MMO->getFlags()); 8263 void* IP = nullptr; 8264 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8265 cast<AtomicSDNode>(E)->refineAlignment(MMO); 8266 return SDValue(E, 0); 8267 } 8268 8269 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 8270 VTList, MemVT, MMO); 8271 createOperands(N, Ops); 8272 8273 CSEMap.InsertNode(N, IP); 8274 InsertNode(N); 8275 return SDValue(N, 0); 8276 } 8277 8278 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 8279 EVT MemVT, SDVTList VTs, SDValue Chain, 8280 SDValue Ptr, SDValue Cmp, SDValue Swp, 8281 MachineMemOperand *MMO) { 8282 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 8283 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 8284 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 8285 8286 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 8287 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 8288 } 8289 8290 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 8291 SDValue Chain, SDValue Ptr, SDValue Val, 8292 MachineMemOperand *MMO) { 8293 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 8294 Opcode == ISD::ATOMIC_LOAD_SUB || 8295 Opcode == ISD::ATOMIC_LOAD_AND || 8296 Opcode == ISD::ATOMIC_LOAD_CLR || 8297 Opcode == ISD::ATOMIC_LOAD_OR || 8298 Opcode == ISD::ATOMIC_LOAD_XOR || 8299 Opcode == ISD::ATOMIC_LOAD_NAND || 8300 Opcode == ISD::ATOMIC_LOAD_MIN || 8301 Opcode == ISD::ATOMIC_LOAD_MAX || 8302 Opcode == ISD::ATOMIC_LOAD_UMIN || 8303 Opcode == ISD::ATOMIC_LOAD_UMAX || 8304 Opcode == ISD::ATOMIC_LOAD_FADD || 8305 Opcode == ISD::ATOMIC_LOAD_FSUB || 8306 Opcode == ISD::ATOMIC_LOAD_FMAX || 8307 Opcode == ISD::ATOMIC_LOAD_FMIN || 8308 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP || 8309 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP || 8310 Opcode == ISD::ATOMIC_SWAP || 8311 Opcode == ISD::ATOMIC_STORE) && 8312 "Invalid Atomic Op"); 8313 8314 EVT VT = Val.getValueType(); 8315 8316 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 8317 getVTList(VT, MVT::Other); 8318 SDValue Ops[] = {Chain, Ptr, Val}; 8319 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 8320 } 8321 8322 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 8323 EVT VT, SDValue Chain, SDValue Ptr, 8324 MachineMemOperand *MMO) { 8325 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 8326 8327 SDVTList VTs = getVTList(VT, MVT::Other); 8328 SDValue Ops[] = {Chain, Ptr}; 8329 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 8330 } 8331 8332 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 8333 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 8334 if (Ops.size() == 1) 8335 return Ops[0]; 8336 8337 SmallVector<EVT, 4> VTs; 8338 VTs.reserve(Ops.size()); 8339 for (const SDValue &Op : Ops) 8340 VTs.push_back(Op.getValueType()); 8341 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 8342 } 8343 8344 SDValue SelectionDAG::getMemIntrinsicNode( 8345 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 8346 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 8347 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 8348 if (!Size && MemVT.isScalableVector()) 8349 Size = MemoryLocation::UnknownSize; 8350 else if (!Size) 8351 Size = MemVT.getStoreSize(); 8352 8353 MachineFunction &MF = getMachineFunction(); 8354 MachineMemOperand *MMO = 8355 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 8356 8357 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 8358 } 8359 8360 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 8361 SDVTList VTList, 8362 ArrayRef<SDValue> Ops, EVT MemVT, 8363 MachineMemOperand *MMO) { 8364 assert((Opcode == ISD::INTRINSIC_VOID || 8365 Opcode == ISD::INTRINSIC_W_CHAIN || 8366 Opcode == ISD::PREFETCH || 8367 (Opcode <= (unsigned)std::numeric_limits<int>::max() && 8368 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 8369 "Opcode is not a memory-accessing opcode!"); 8370 8371 // Memoize the node unless it returns a glue result. 8372 MemIntrinsicSDNode *N; 8373 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8374 FoldingSetNodeID ID; 8375 AddNodeIDNode(ID, Opcode, VTList, Ops); 8376 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 8377 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 8378 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8379 ID.AddInteger(MMO->getFlags()); 8380 ID.AddInteger(MemVT.getRawBits()); 8381 void *IP = nullptr; 8382 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8383 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 8384 return SDValue(E, 0); 8385 } 8386 8387 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 8388 VTList, MemVT, MMO); 8389 createOperands(N, Ops); 8390 8391 CSEMap.InsertNode(N, IP); 8392 } else { 8393 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 8394 VTList, MemVT, MMO); 8395 createOperands(N, Ops); 8396 } 8397 InsertNode(N); 8398 SDValue V(N, 0); 8399 NewSDValueDbgMsg(V, "Creating new node: ", this); 8400 return V; 8401 } 8402 8403 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 8404 SDValue Chain, int FrameIndex, 8405 int64_t Size, int64_t Offset) { 8406 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 8407 const auto VTs = getVTList(MVT::Other); 8408 SDValue Ops[2] = { 8409 Chain, 8410 getFrameIndex(FrameIndex, 8411 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 8412 true)}; 8413 8414 FoldingSetNodeID ID; 8415 AddNodeIDNode(ID, Opcode, VTs, Ops); 8416 ID.AddInteger(FrameIndex); 8417 ID.AddInteger(Size); 8418 ID.AddInteger(Offset); 8419 void *IP = nullptr; 8420 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8421 return SDValue(E, 0); 8422 8423 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 8424 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 8425 createOperands(N, Ops); 8426 CSEMap.InsertNode(N, IP); 8427 InsertNode(N); 8428 SDValue V(N, 0); 8429 NewSDValueDbgMsg(V, "Creating new node: ", this); 8430 return V; 8431 } 8432 8433 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 8434 uint64_t Guid, uint64_t Index, 8435 uint32_t Attr) { 8436 const unsigned Opcode = ISD::PSEUDO_PROBE; 8437 const auto VTs = getVTList(MVT::Other); 8438 SDValue Ops[] = {Chain}; 8439 FoldingSetNodeID ID; 8440 AddNodeIDNode(ID, Opcode, VTs, Ops); 8441 ID.AddInteger(Guid); 8442 ID.AddInteger(Index); 8443 void *IP = nullptr; 8444 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 8445 return SDValue(E, 0); 8446 8447 auto *N = newSDNode<PseudoProbeSDNode>( 8448 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 8449 createOperands(N, Ops); 8450 CSEMap.InsertNode(N, IP); 8451 InsertNode(N); 8452 SDValue V(N, 0); 8453 NewSDValueDbgMsg(V, "Creating new node: ", this); 8454 return V; 8455 } 8456 8457 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 8458 /// MachinePointerInfo record from it. This is particularly useful because the 8459 /// code generator has many cases where it doesn't bother passing in a 8460 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 8461 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 8462 SelectionDAG &DAG, SDValue Ptr, 8463 int64_t Offset = 0) { 8464 // If this is FI+Offset, we can model it. 8465 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 8466 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 8467 FI->getIndex(), Offset); 8468 8469 // If this is (FI+Offset1)+Offset2, we can model it. 8470 if (Ptr.getOpcode() != ISD::ADD || 8471 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 8472 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 8473 return Info; 8474 8475 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 8476 return MachinePointerInfo::getFixedStack( 8477 DAG.getMachineFunction(), FI, 8478 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 8479 } 8480 8481 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 8482 /// MachinePointerInfo record from it. This is particularly useful because the 8483 /// code generator has many cases where it doesn't bother passing in a 8484 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 8485 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 8486 SelectionDAG &DAG, SDValue Ptr, 8487 SDValue OffsetOp) { 8488 // If the 'Offset' value isn't a constant, we can't handle this. 8489 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 8490 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 8491 if (OffsetOp.isUndef()) 8492 return InferPointerInfo(Info, DAG, Ptr); 8493 return Info; 8494 } 8495 8496 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 8497 EVT VT, const SDLoc &dl, SDValue Chain, 8498 SDValue Ptr, SDValue Offset, 8499 MachinePointerInfo PtrInfo, EVT MemVT, 8500 Align Alignment, 8501 MachineMemOperand::Flags MMOFlags, 8502 const AAMDNodes &AAInfo, const MDNode *Ranges) { 8503 assert(Chain.getValueType() == MVT::Other && 8504 "Invalid chain type"); 8505 8506 MMOFlags |= MachineMemOperand::MOLoad; 8507 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8508 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8509 // clients. 8510 if (PtrInfo.V.isNull()) 8511 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8512 8513 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 8514 MachineFunction &MF = getMachineFunction(); 8515 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8516 Alignment, AAInfo, Ranges); 8517 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 8518 } 8519 8520 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 8521 EVT VT, const SDLoc &dl, SDValue Chain, 8522 SDValue Ptr, SDValue Offset, EVT MemVT, 8523 MachineMemOperand *MMO) { 8524 if (VT == MemVT) { 8525 ExtType = ISD::NON_EXTLOAD; 8526 } else if (ExtType == ISD::NON_EXTLOAD) { 8527 assert(VT == MemVT && "Non-extending load from different memory type!"); 8528 } else { 8529 // Extending load. 8530 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 8531 "Should only be an extending load, not truncating!"); 8532 assert(VT.isInteger() == MemVT.isInteger() && 8533 "Cannot convert from FP to Int or Int -> FP!"); 8534 assert(VT.isVector() == MemVT.isVector() && 8535 "Cannot use an ext load to convert to or from a vector!"); 8536 assert((!VT.isVector() || 8537 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 8538 "Cannot use an ext load to change the number of vector elements!"); 8539 } 8540 8541 bool Indexed = AM != ISD::UNINDEXED; 8542 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8543 8544 SDVTList VTs = Indexed ? 8545 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 8546 SDValue Ops[] = { Chain, Ptr, Offset }; 8547 FoldingSetNodeID ID; 8548 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 8549 ID.AddInteger(MemVT.getRawBits()); 8550 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 8551 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 8552 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8553 ID.AddInteger(MMO->getFlags()); 8554 void *IP = nullptr; 8555 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8556 cast<LoadSDNode>(E)->refineAlignment(MMO); 8557 return SDValue(E, 0); 8558 } 8559 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8560 ExtType, MemVT, MMO); 8561 createOperands(N, Ops); 8562 8563 CSEMap.InsertNode(N, IP); 8564 InsertNode(N); 8565 SDValue V(N, 0); 8566 NewSDValueDbgMsg(V, "Creating new node: ", this); 8567 return V; 8568 } 8569 8570 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8571 SDValue Ptr, MachinePointerInfo PtrInfo, 8572 MaybeAlign Alignment, 8573 MachineMemOperand::Flags MMOFlags, 8574 const AAMDNodes &AAInfo, const MDNode *Ranges) { 8575 SDValue Undef = getUNDEF(Ptr.getValueType()); 8576 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8577 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 8578 } 8579 8580 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8581 SDValue Ptr, MachineMemOperand *MMO) { 8582 SDValue Undef = getUNDEF(Ptr.getValueType()); 8583 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8584 VT, MMO); 8585 } 8586 8587 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 8588 EVT VT, SDValue Chain, SDValue Ptr, 8589 MachinePointerInfo PtrInfo, EVT MemVT, 8590 MaybeAlign Alignment, 8591 MachineMemOperand::Flags MMOFlags, 8592 const AAMDNodes &AAInfo) { 8593 SDValue Undef = getUNDEF(Ptr.getValueType()); 8594 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 8595 MemVT, Alignment, MMOFlags, AAInfo); 8596 } 8597 8598 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 8599 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 8600 MachineMemOperand *MMO) { 8601 SDValue Undef = getUNDEF(Ptr.getValueType()); 8602 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 8603 MemVT, MMO); 8604 } 8605 8606 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 8607 SDValue Base, SDValue Offset, 8608 ISD::MemIndexedMode AM) { 8609 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 8610 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8611 // Don't propagate the invariant or dereferenceable flags. 8612 auto MMOFlags = 8613 LD->getMemOperand()->getFlags() & 8614 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8615 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8616 LD->getChain(), Base, Offset, LD->getPointerInfo(), 8617 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 8618 } 8619 8620 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8621 SDValue Ptr, MachinePointerInfo PtrInfo, 8622 Align Alignment, 8623 MachineMemOperand::Flags MMOFlags, 8624 const AAMDNodes &AAInfo) { 8625 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8626 8627 MMOFlags |= MachineMemOperand::MOStore; 8628 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8629 8630 if (PtrInfo.V.isNull()) 8631 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8632 8633 MachineFunction &MF = getMachineFunction(); 8634 uint64_t Size = 8635 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 8636 MachineMemOperand *MMO = 8637 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 8638 return getStore(Chain, dl, Val, Ptr, MMO); 8639 } 8640 8641 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8642 SDValue Ptr, MachineMemOperand *MMO) { 8643 assert(Chain.getValueType() == MVT::Other && 8644 "Invalid chain type"); 8645 EVT VT = Val.getValueType(); 8646 SDVTList VTs = getVTList(MVT::Other); 8647 SDValue Undef = getUNDEF(Ptr.getValueType()); 8648 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 8649 FoldingSetNodeID ID; 8650 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 8651 ID.AddInteger(VT.getRawBits()); 8652 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 8653 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 8654 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8655 ID.AddInteger(MMO->getFlags()); 8656 void *IP = nullptr; 8657 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8658 cast<StoreSDNode>(E)->refineAlignment(MMO); 8659 return SDValue(E, 0); 8660 } 8661 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8662 ISD::UNINDEXED, false, VT, MMO); 8663 createOperands(N, Ops); 8664 8665 CSEMap.InsertNode(N, IP); 8666 InsertNode(N); 8667 SDValue V(N, 0); 8668 NewSDValueDbgMsg(V, "Creating new node: ", this); 8669 return V; 8670 } 8671 8672 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8673 SDValue Ptr, MachinePointerInfo PtrInfo, 8674 EVT SVT, Align Alignment, 8675 MachineMemOperand::Flags MMOFlags, 8676 const AAMDNodes &AAInfo) { 8677 assert(Chain.getValueType() == MVT::Other && 8678 "Invalid chain type"); 8679 8680 MMOFlags |= MachineMemOperand::MOStore; 8681 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8682 8683 if (PtrInfo.V.isNull()) 8684 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8685 8686 MachineFunction &MF = getMachineFunction(); 8687 MachineMemOperand *MMO = MF.getMachineMemOperand( 8688 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8689 Alignment, AAInfo); 8690 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 8691 } 8692 8693 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8694 SDValue Ptr, EVT SVT, 8695 MachineMemOperand *MMO) { 8696 EVT VT = Val.getValueType(); 8697 8698 assert(Chain.getValueType() == MVT::Other && 8699 "Invalid chain type"); 8700 if (VT == SVT) 8701 return getStore(Chain, dl, Val, Ptr, MMO); 8702 8703 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8704 "Should only be a truncating store, not extending!"); 8705 assert(VT.isInteger() == SVT.isInteger() && 8706 "Can't do FP-INT conversion!"); 8707 assert(VT.isVector() == SVT.isVector() && 8708 "Cannot use trunc store to convert to or from a vector!"); 8709 assert((!VT.isVector() || 8710 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8711 "Cannot use trunc store to change the number of vector elements!"); 8712 8713 SDVTList VTs = getVTList(MVT::Other); 8714 SDValue Undef = getUNDEF(Ptr.getValueType()); 8715 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 8716 FoldingSetNodeID ID; 8717 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 8718 ID.AddInteger(SVT.getRawBits()); 8719 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 8720 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 8721 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8722 ID.AddInteger(MMO->getFlags()); 8723 void *IP = nullptr; 8724 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8725 cast<StoreSDNode>(E)->refineAlignment(MMO); 8726 return SDValue(E, 0); 8727 } 8728 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8729 ISD::UNINDEXED, true, SVT, MMO); 8730 createOperands(N, Ops); 8731 8732 CSEMap.InsertNode(N, IP); 8733 InsertNode(N); 8734 SDValue V(N, 0); 8735 NewSDValueDbgMsg(V, "Creating new node: ", this); 8736 return V; 8737 } 8738 8739 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 8740 SDValue Base, SDValue Offset, 8741 ISD::MemIndexedMode AM) { 8742 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 8743 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 8744 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8745 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 8746 FoldingSetNodeID ID; 8747 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 8748 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8749 ID.AddInteger(ST->getRawSubclassData()); 8750 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8751 ID.AddInteger(ST->getMemOperand()->getFlags()); 8752 void *IP = nullptr; 8753 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8754 return SDValue(E, 0); 8755 8756 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8757 ST->isTruncatingStore(), ST->getMemoryVT(), 8758 ST->getMemOperand()); 8759 createOperands(N, Ops); 8760 8761 CSEMap.InsertNode(N, IP); 8762 InsertNode(N); 8763 SDValue V(N, 0); 8764 NewSDValueDbgMsg(V, "Creating new node: ", this); 8765 return V; 8766 } 8767 8768 SDValue SelectionDAG::getLoadVP( 8769 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 8770 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 8771 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8772 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8773 const MDNode *Ranges, bool IsExpanding) { 8774 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8775 8776 MMOFlags |= MachineMemOperand::MOLoad; 8777 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8778 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8779 // clients. 8780 if (PtrInfo.V.isNull()) 8781 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8782 8783 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 8784 MachineFunction &MF = getMachineFunction(); 8785 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8786 Alignment, AAInfo, Ranges); 8787 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 8788 MMO, IsExpanding); 8789 } 8790 8791 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 8792 ISD::LoadExtType ExtType, EVT VT, 8793 const SDLoc &dl, SDValue Chain, SDValue Ptr, 8794 SDValue Offset, SDValue Mask, SDValue EVL, 8795 EVT MemVT, MachineMemOperand *MMO, 8796 bool IsExpanding) { 8797 bool Indexed = AM != ISD::UNINDEXED; 8798 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8799 8800 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8801 : getVTList(VT, MVT::Other); 8802 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 8803 FoldingSetNodeID ID; 8804 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 8805 ID.AddInteger(MemVT.getRawBits()); 8806 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 8807 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8808 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8809 ID.AddInteger(MMO->getFlags()); 8810 void *IP = nullptr; 8811 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8812 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 8813 return SDValue(E, 0); 8814 } 8815 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8816 ExtType, IsExpanding, MemVT, MMO); 8817 createOperands(N, Ops); 8818 8819 CSEMap.InsertNode(N, IP); 8820 InsertNode(N); 8821 SDValue V(N, 0); 8822 NewSDValueDbgMsg(V, "Creating new node: ", this); 8823 return V; 8824 } 8825 8826 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8827 SDValue Ptr, SDValue Mask, SDValue EVL, 8828 MachinePointerInfo PtrInfo, 8829 MaybeAlign Alignment, 8830 MachineMemOperand::Flags MMOFlags, 8831 const AAMDNodes &AAInfo, const MDNode *Ranges, 8832 bool IsExpanding) { 8833 SDValue Undef = getUNDEF(Ptr.getValueType()); 8834 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8835 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 8836 IsExpanding); 8837 } 8838 8839 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8840 SDValue Ptr, SDValue Mask, SDValue EVL, 8841 MachineMemOperand *MMO, bool IsExpanding) { 8842 SDValue Undef = getUNDEF(Ptr.getValueType()); 8843 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8844 Mask, EVL, VT, MMO, IsExpanding); 8845 } 8846 8847 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8848 EVT VT, SDValue Chain, SDValue Ptr, 8849 SDValue Mask, SDValue EVL, 8850 MachinePointerInfo PtrInfo, EVT MemVT, 8851 MaybeAlign Alignment, 8852 MachineMemOperand::Flags MMOFlags, 8853 const AAMDNodes &AAInfo, bool IsExpanding) { 8854 SDValue Undef = getUNDEF(Ptr.getValueType()); 8855 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8856 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 8857 IsExpanding); 8858 } 8859 8860 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8861 EVT VT, SDValue Chain, SDValue Ptr, 8862 SDValue Mask, SDValue EVL, EVT MemVT, 8863 MachineMemOperand *MMO, bool IsExpanding) { 8864 SDValue Undef = getUNDEF(Ptr.getValueType()); 8865 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8866 EVL, MemVT, MMO, IsExpanding); 8867 } 8868 8869 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 8870 SDValue Base, SDValue Offset, 8871 ISD::MemIndexedMode AM) { 8872 auto *LD = cast<VPLoadSDNode>(OrigLoad); 8873 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8874 // Don't propagate the invariant or dereferenceable flags. 8875 auto MMOFlags = 8876 LD->getMemOperand()->getFlags() & 8877 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8878 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8879 LD->getChain(), Base, Offset, LD->getMask(), 8880 LD->getVectorLength(), LD->getPointerInfo(), 8881 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 8882 nullptr, LD->isExpandingLoad()); 8883 } 8884 8885 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 8886 SDValue Ptr, SDValue Offset, SDValue Mask, 8887 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 8888 ISD::MemIndexedMode AM, bool IsTruncating, 8889 bool IsCompressing) { 8890 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8891 bool Indexed = AM != ISD::UNINDEXED; 8892 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8893 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8894 : getVTList(MVT::Other); 8895 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 8896 FoldingSetNodeID ID; 8897 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8898 ID.AddInteger(MemVT.getRawBits()); 8899 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8900 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8901 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8902 ID.AddInteger(MMO->getFlags()); 8903 void *IP = nullptr; 8904 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8905 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8906 return SDValue(E, 0); 8907 } 8908 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8909 IsTruncating, IsCompressing, MemVT, MMO); 8910 createOperands(N, Ops); 8911 8912 CSEMap.InsertNode(N, IP); 8913 InsertNode(N); 8914 SDValue V(N, 0); 8915 NewSDValueDbgMsg(V, "Creating new node: ", this); 8916 return V; 8917 } 8918 8919 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8920 SDValue Val, SDValue Ptr, SDValue Mask, 8921 SDValue EVL, MachinePointerInfo PtrInfo, 8922 EVT SVT, Align Alignment, 8923 MachineMemOperand::Flags MMOFlags, 8924 const AAMDNodes &AAInfo, 8925 bool IsCompressing) { 8926 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8927 8928 MMOFlags |= MachineMemOperand::MOStore; 8929 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8930 8931 if (PtrInfo.V.isNull()) 8932 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8933 8934 MachineFunction &MF = getMachineFunction(); 8935 MachineMemOperand *MMO = MF.getMachineMemOperand( 8936 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8937 Alignment, AAInfo); 8938 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8939 IsCompressing); 8940 } 8941 8942 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8943 SDValue Val, SDValue Ptr, SDValue Mask, 8944 SDValue EVL, EVT SVT, 8945 MachineMemOperand *MMO, 8946 bool IsCompressing) { 8947 EVT VT = Val.getValueType(); 8948 8949 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8950 if (VT == SVT) 8951 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8952 EVL, VT, MMO, ISD::UNINDEXED, 8953 /*IsTruncating*/ false, IsCompressing); 8954 8955 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8956 "Should only be a truncating store, not extending!"); 8957 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8958 assert(VT.isVector() == SVT.isVector() && 8959 "Cannot use trunc store to convert to or from a vector!"); 8960 assert((!VT.isVector() || 8961 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8962 "Cannot use trunc store to change the number of vector elements!"); 8963 8964 SDVTList VTs = getVTList(MVT::Other); 8965 SDValue Undef = getUNDEF(Ptr.getValueType()); 8966 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8967 FoldingSetNodeID ID; 8968 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8969 ID.AddInteger(SVT.getRawBits()); 8970 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8971 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8972 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8973 ID.AddInteger(MMO->getFlags()); 8974 void *IP = nullptr; 8975 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8976 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8977 return SDValue(E, 0); 8978 } 8979 auto *N = 8980 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8981 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8982 createOperands(N, Ops); 8983 8984 CSEMap.InsertNode(N, IP); 8985 InsertNode(N); 8986 SDValue V(N, 0); 8987 NewSDValueDbgMsg(V, "Creating new node: ", this); 8988 return V; 8989 } 8990 8991 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8992 SDValue Base, SDValue Offset, 8993 ISD::MemIndexedMode AM) { 8994 auto *ST = cast<VPStoreSDNode>(OrigStore); 8995 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8996 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8997 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8998 Offset, ST->getMask(), ST->getVectorLength()}; 8999 FoldingSetNodeID ID; 9000 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 9001 ID.AddInteger(ST->getMemoryVT().getRawBits()); 9002 ID.AddInteger(ST->getRawSubclassData()); 9003 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 9004 ID.AddInteger(ST->getMemOperand()->getFlags()); 9005 void *IP = nullptr; 9006 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 9007 return SDValue(E, 0); 9008 9009 auto *N = newSDNode<VPStoreSDNode>( 9010 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 9011 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 9012 createOperands(N, Ops); 9013 9014 CSEMap.InsertNode(N, IP); 9015 InsertNode(N); 9016 SDValue V(N, 0); 9017 NewSDValueDbgMsg(V, "Creating new node: ", this); 9018 return V; 9019 } 9020 9021 SDValue SelectionDAG::getStridedLoadVP( 9022 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 9023 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 9024 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 9025 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 9026 const MDNode *Ranges, bool IsExpanding) { 9027 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9028 9029 MMOFlags |= MachineMemOperand::MOLoad; 9030 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 9031 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 9032 // clients. 9033 if (PtrInfo.V.isNull()) 9034 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 9035 9036 uint64_t Size = MemoryLocation::UnknownSize; 9037 MachineFunction &MF = getMachineFunction(); 9038 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 9039 Alignment, AAInfo, Ranges); 9040 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 9041 EVL, MemVT, MMO, IsExpanding); 9042 } 9043 9044 SDValue SelectionDAG::getStridedLoadVP( 9045 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 9046 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 9047 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 9048 bool Indexed = AM != ISD::UNINDEXED; 9049 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 9050 9051 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 9052 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 9053 : getVTList(VT, MVT::Other); 9054 FoldingSetNodeID ID; 9055 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 9056 ID.AddInteger(VT.getRawBits()); 9057 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 9058 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 9059 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9060 9061 void *IP = nullptr; 9062 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9063 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 9064 return SDValue(E, 0); 9065 } 9066 9067 auto *N = 9068 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 9069 ExtType, IsExpanding, MemVT, MMO); 9070 createOperands(N, Ops); 9071 CSEMap.InsertNode(N, IP); 9072 InsertNode(N); 9073 SDValue V(N, 0); 9074 NewSDValueDbgMsg(V, "Creating new node: ", this); 9075 return V; 9076 } 9077 9078 SDValue SelectionDAG::getStridedLoadVP( 9079 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 9080 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 9081 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 9082 const MDNode *Ranges, bool IsExpanding) { 9083 SDValue Undef = getUNDEF(Ptr.getValueType()); 9084 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 9085 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 9086 MMOFlags, AAInfo, Ranges, IsExpanding); 9087 } 9088 9089 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 9090 SDValue Ptr, SDValue Stride, 9091 SDValue Mask, SDValue EVL, 9092 MachineMemOperand *MMO, 9093 bool IsExpanding) { 9094 SDValue Undef = getUNDEF(Ptr.getValueType()); 9095 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 9096 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 9097 } 9098 9099 SDValue SelectionDAG::getExtStridedLoadVP( 9100 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 9101 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 9102 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 9103 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 9104 bool IsExpanding) { 9105 SDValue Undef = getUNDEF(Ptr.getValueType()); 9106 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 9107 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 9108 MMOFlags, AAInfo, nullptr, IsExpanding); 9109 } 9110 9111 SDValue SelectionDAG::getExtStridedLoadVP( 9112 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 9113 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 9114 MachineMemOperand *MMO, bool IsExpanding) { 9115 SDValue Undef = getUNDEF(Ptr.getValueType()); 9116 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 9117 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 9118 } 9119 9120 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 9121 SDValue Base, SDValue Offset, 9122 ISD::MemIndexedMode AM) { 9123 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 9124 assert(SLD->getOffset().isUndef() && 9125 "Strided load is already a indexed load!"); 9126 // Don't propagate the invariant or dereferenceable flags. 9127 auto MMOFlags = 9128 SLD->getMemOperand()->getFlags() & 9129 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 9130 return getStridedLoadVP( 9131 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 9132 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 9133 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 9134 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 9135 } 9136 9137 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 9138 SDValue Val, SDValue Ptr, 9139 SDValue Offset, SDValue Stride, 9140 SDValue Mask, SDValue EVL, EVT MemVT, 9141 MachineMemOperand *MMO, 9142 ISD::MemIndexedMode AM, 9143 bool IsTruncating, bool IsCompressing) { 9144 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9145 bool Indexed = AM != ISD::UNINDEXED; 9146 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 9147 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 9148 : getVTList(MVT::Other); 9149 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 9150 FoldingSetNodeID ID; 9151 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 9152 ID.AddInteger(MemVT.getRawBits()); 9153 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 9154 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 9155 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9156 void *IP = nullptr; 9157 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9158 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 9159 return SDValue(E, 0); 9160 } 9161 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 9162 VTs, AM, IsTruncating, 9163 IsCompressing, MemVT, MMO); 9164 createOperands(N, Ops); 9165 9166 CSEMap.InsertNode(N, IP); 9167 InsertNode(N); 9168 SDValue V(N, 0); 9169 NewSDValueDbgMsg(V, "Creating new node: ", this); 9170 return V; 9171 } 9172 9173 SDValue SelectionDAG::getTruncStridedStoreVP( 9174 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 9175 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 9176 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 9177 bool IsCompressing) { 9178 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9179 9180 MMOFlags |= MachineMemOperand::MOStore; 9181 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 9182 9183 if (PtrInfo.V.isNull()) 9184 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 9185 9186 MachineFunction &MF = getMachineFunction(); 9187 MachineMemOperand *MMO = MF.getMachineMemOperand( 9188 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 9189 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 9190 MMO, IsCompressing); 9191 } 9192 9193 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 9194 SDValue Val, SDValue Ptr, 9195 SDValue Stride, SDValue Mask, 9196 SDValue EVL, EVT SVT, 9197 MachineMemOperand *MMO, 9198 bool IsCompressing) { 9199 EVT VT = Val.getValueType(); 9200 9201 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9202 if (VT == SVT) 9203 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 9204 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 9205 /*IsTruncating*/ false, IsCompressing); 9206 9207 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 9208 "Should only be a truncating store, not extending!"); 9209 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 9210 assert(VT.isVector() == SVT.isVector() && 9211 "Cannot use trunc store to convert to or from a vector!"); 9212 assert((!VT.isVector() || 9213 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 9214 "Cannot use trunc store to change the number of vector elements!"); 9215 9216 SDVTList VTs = getVTList(MVT::Other); 9217 SDValue Undef = getUNDEF(Ptr.getValueType()); 9218 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 9219 FoldingSetNodeID ID; 9220 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 9221 ID.AddInteger(SVT.getRawBits()); 9222 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 9223 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 9224 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9225 void *IP = nullptr; 9226 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9227 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 9228 return SDValue(E, 0); 9229 } 9230 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 9231 VTs, ISD::UNINDEXED, true, 9232 IsCompressing, SVT, MMO); 9233 createOperands(N, Ops); 9234 9235 CSEMap.InsertNode(N, IP); 9236 InsertNode(N); 9237 SDValue V(N, 0); 9238 NewSDValueDbgMsg(V, "Creating new node: ", this); 9239 return V; 9240 } 9241 9242 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 9243 const SDLoc &DL, SDValue Base, 9244 SDValue Offset, 9245 ISD::MemIndexedMode AM) { 9246 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 9247 assert(SST->getOffset().isUndef() && 9248 "Strided store is already an indexed store!"); 9249 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 9250 SDValue Ops[] = { 9251 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 9252 SST->getMask(), SST->getVectorLength()}; 9253 FoldingSetNodeID ID; 9254 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 9255 ID.AddInteger(SST->getMemoryVT().getRawBits()); 9256 ID.AddInteger(SST->getRawSubclassData()); 9257 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 9258 void *IP = nullptr; 9259 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9260 return SDValue(E, 0); 9261 9262 auto *N = newSDNode<VPStridedStoreSDNode>( 9263 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 9264 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 9265 createOperands(N, Ops); 9266 9267 CSEMap.InsertNode(N, IP); 9268 InsertNode(N); 9269 SDValue V(N, 0); 9270 NewSDValueDbgMsg(V, "Creating new node: ", this); 9271 return V; 9272 } 9273 9274 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 9275 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 9276 ISD::MemIndexType IndexType) { 9277 assert(Ops.size() == 6 && "Incompatible number of operands"); 9278 9279 FoldingSetNodeID ID; 9280 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 9281 ID.AddInteger(VT.getRawBits()); 9282 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 9283 dl.getIROrder(), VTs, VT, MMO, IndexType)); 9284 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9285 ID.AddInteger(MMO->getFlags()); 9286 void *IP = nullptr; 9287 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9288 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 9289 return SDValue(E, 0); 9290 } 9291 9292 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 9293 VT, MMO, IndexType); 9294 createOperands(N, Ops); 9295 9296 assert(N->getMask().getValueType().getVectorElementCount() == 9297 N->getValueType(0).getVectorElementCount() && 9298 "Vector width mismatch between mask and data"); 9299 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 9300 N->getValueType(0).getVectorElementCount().isScalable() && 9301 "Scalable flags of index and data do not match"); 9302 assert(ElementCount::isKnownGE( 9303 N->getIndex().getValueType().getVectorElementCount(), 9304 N->getValueType(0).getVectorElementCount()) && 9305 "Vector width mismatch between index and data"); 9306 assert(isa<ConstantSDNode>(N->getScale()) && 9307 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9308 "Scale should be a constant power of 2"); 9309 9310 CSEMap.InsertNode(N, IP); 9311 InsertNode(N); 9312 SDValue V(N, 0); 9313 NewSDValueDbgMsg(V, "Creating new node: ", this); 9314 return V; 9315 } 9316 9317 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 9318 ArrayRef<SDValue> Ops, 9319 MachineMemOperand *MMO, 9320 ISD::MemIndexType IndexType) { 9321 assert(Ops.size() == 7 && "Incompatible number of operands"); 9322 9323 FoldingSetNodeID ID; 9324 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 9325 ID.AddInteger(VT.getRawBits()); 9326 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 9327 dl.getIROrder(), VTs, VT, MMO, IndexType)); 9328 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9329 ID.AddInteger(MMO->getFlags()); 9330 void *IP = nullptr; 9331 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9332 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 9333 return SDValue(E, 0); 9334 } 9335 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 9336 VT, MMO, IndexType); 9337 createOperands(N, Ops); 9338 9339 assert(N->getMask().getValueType().getVectorElementCount() == 9340 N->getValue().getValueType().getVectorElementCount() && 9341 "Vector width mismatch between mask and data"); 9342 assert( 9343 N->getIndex().getValueType().getVectorElementCount().isScalable() == 9344 N->getValue().getValueType().getVectorElementCount().isScalable() && 9345 "Scalable flags of index and data do not match"); 9346 assert(ElementCount::isKnownGE( 9347 N->getIndex().getValueType().getVectorElementCount(), 9348 N->getValue().getValueType().getVectorElementCount()) && 9349 "Vector width mismatch between index and data"); 9350 assert(isa<ConstantSDNode>(N->getScale()) && 9351 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9352 "Scale should be a constant power of 2"); 9353 9354 CSEMap.InsertNode(N, IP); 9355 InsertNode(N); 9356 SDValue V(N, 0); 9357 NewSDValueDbgMsg(V, "Creating new node: ", this); 9358 return V; 9359 } 9360 9361 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 9362 SDValue Base, SDValue Offset, SDValue Mask, 9363 SDValue PassThru, EVT MemVT, 9364 MachineMemOperand *MMO, 9365 ISD::MemIndexedMode AM, 9366 ISD::LoadExtType ExtTy, bool isExpanding) { 9367 bool Indexed = AM != ISD::UNINDEXED; 9368 assert((Indexed || Offset.isUndef()) && 9369 "Unindexed masked load with an offset!"); 9370 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 9371 : getVTList(VT, MVT::Other); 9372 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 9373 FoldingSetNodeID ID; 9374 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 9375 ID.AddInteger(MemVT.getRawBits()); 9376 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 9377 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 9378 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9379 ID.AddInteger(MMO->getFlags()); 9380 void *IP = nullptr; 9381 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9382 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 9383 return SDValue(E, 0); 9384 } 9385 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 9386 AM, ExtTy, isExpanding, MemVT, MMO); 9387 createOperands(N, Ops); 9388 9389 CSEMap.InsertNode(N, IP); 9390 InsertNode(N); 9391 SDValue V(N, 0); 9392 NewSDValueDbgMsg(V, "Creating new node: ", this); 9393 return V; 9394 } 9395 9396 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 9397 SDValue Base, SDValue Offset, 9398 ISD::MemIndexedMode AM) { 9399 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 9400 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 9401 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 9402 Offset, LD->getMask(), LD->getPassThru(), 9403 LD->getMemoryVT(), LD->getMemOperand(), AM, 9404 LD->getExtensionType(), LD->isExpandingLoad()); 9405 } 9406 9407 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 9408 SDValue Val, SDValue Base, SDValue Offset, 9409 SDValue Mask, EVT MemVT, 9410 MachineMemOperand *MMO, 9411 ISD::MemIndexedMode AM, bool IsTruncating, 9412 bool IsCompressing) { 9413 assert(Chain.getValueType() == MVT::Other && 9414 "Invalid chain type"); 9415 bool Indexed = AM != ISD::UNINDEXED; 9416 assert((Indexed || Offset.isUndef()) && 9417 "Unindexed masked store with an offset!"); 9418 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 9419 : getVTList(MVT::Other); 9420 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 9421 FoldingSetNodeID ID; 9422 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 9423 ID.AddInteger(MemVT.getRawBits()); 9424 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 9425 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 9426 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9427 ID.AddInteger(MMO->getFlags()); 9428 void *IP = nullptr; 9429 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9430 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 9431 return SDValue(E, 0); 9432 } 9433 auto *N = 9434 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 9435 IsTruncating, IsCompressing, MemVT, MMO); 9436 createOperands(N, Ops); 9437 9438 CSEMap.InsertNode(N, IP); 9439 InsertNode(N); 9440 SDValue V(N, 0); 9441 NewSDValueDbgMsg(V, "Creating new node: ", this); 9442 return V; 9443 } 9444 9445 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 9446 SDValue Base, SDValue Offset, 9447 ISD::MemIndexedMode AM) { 9448 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 9449 assert(ST->getOffset().isUndef() && 9450 "Masked store is already a indexed store!"); 9451 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 9452 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 9453 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 9454 } 9455 9456 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 9457 ArrayRef<SDValue> Ops, 9458 MachineMemOperand *MMO, 9459 ISD::MemIndexType IndexType, 9460 ISD::LoadExtType ExtTy) { 9461 assert(Ops.size() == 6 && "Incompatible number of operands"); 9462 9463 FoldingSetNodeID ID; 9464 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 9465 ID.AddInteger(MemVT.getRawBits()); 9466 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 9467 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 9468 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9469 ID.AddInteger(MMO->getFlags()); 9470 void *IP = nullptr; 9471 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9472 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 9473 return SDValue(E, 0); 9474 } 9475 9476 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 9477 VTs, MemVT, MMO, IndexType, ExtTy); 9478 createOperands(N, Ops); 9479 9480 assert(N->getPassThru().getValueType() == N->getValueType(0) && 9481 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 9482 assert(N->getMask().getValueType().getVectorElementCount() == 9483 N->getValueType(0).getVectorElementCount() && 9484 "Vector width mismatch between mask and data"); 9485 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 9486 N->getValueType(0).getVectorElementCount().isScalable() && 9487 "Scalable flags of index and data do not match"); 9488 assert(ElementCount::isKnownGE( 9489 N->getIndex().getValueType().getVectorElementCount(), 9490 N->getValueType(0).getVectorElementCount()) && 9491 "Vector width mismatch between index and data"); 9492 assert(isa<ConstantSDNode>(N->getScale()) && 9493 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9494 "Scale should be a constant power of 2"); 9495 9496 CSEMap.InsertNode(N, IP); 9497 InsertNode(N); 9498 SDValue V(N, 0); 9499 NewSDValueDbgMsg(V, "Creating new node: ", this); 9500 return V; 9501 } 9502 9503 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 9504 ArrayRef<SDValue> Ops, 9505 MachineMemOperand *MMO, 9506 ISD::MemIndexType IndexType, 9507 bool IsTrunc) { 9508 assert(Ops.size() == 6 && "Incompatible number of operands"); 9509 9510 FoldingSetNodeID ID; 9511 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 9512 ID.AddInteger(MemVT.getRawBits()); 9513 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 9514 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 9515 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9516 ID.AddInteger(MMO->getFlags()); 9517 void *IP = nullptr; 9518 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9519 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 9520 return SDValue(E, 0); 9521 } 9522 9523 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 9524 VTs, MemVT, MMO, IndexType, IsTrunc); 9525 createOperands(N, Ops); 9526 9527 assert(N->getMask().getValueType().getVectorElementCount() == 9528 N->getValue().getValueType().getVectorElementCount() && 9529 "Vector width mismatch between mask and data"); 9530 assert( 9531 N->getIndex().getValueType().getVectorElementCount().isScalable() == 9532 N->getValue().getValueType().getVectorElementCount().isScalable() && 9533 "Scalable flags of index and data do not match"); 9534 assert(ElementCount::isKnownGE( 9535 N->getIndex().getValueType().getVectorElementCount(), 9536 N->getValue().getValueType().getVectorElementCount()) && 9537 "Vector width mismatch between index and data"); 9538 assert(isa<ConstantSDNode>(N->getScale()) && 9539 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9540 "Scale should be a constant power of 2"); 9541 9542 CSEMap.InsertNode(N, IP); 9543 InsertNode(N); 9544 SDValue V(N, 0); 9545 NewSDValueDbgMsg(V, "Creating new node: ", this); 9546 return V; 9547 } 9548 9549 SDValue SelectionDAG::getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, 9550 EVT MemVT, MachineMemOperand *MMO) { 9551 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9552 SDVTList VTs = getVTList(MVT::Other); 9553 SDValue Ops[] = {Chain, Ptr}; 9554 FoldingSetNodeID ID; 9555 AddNodeIDNode(ID, ISD::GET_FPENV_MEM, VTs, Ops); 9556 ID.AddInteger(MemVT.getRawBits()); 9557 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>( 9558 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO)); 9559 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9560 ID.AddInteger(MMO->getFlags()); 9561 void *IP = nullptr; 9562 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 9563 return SDValue(E, 0); 9564 9565 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(), 9566 dl.getDebugLoc(), VTs, MemVT, MMO); 9567 createOperands(N, Ops); 9568 9569 CSEMap.InsertNode(N, IP); 9570 InsertNode(N); 9571 SDValue V(N, 0); 9572 NewSDValueDbgMsg(V, "Creating new node: ", this); 9573 return V; 9574 } 9575 9576 SDValue SelectionDAG::getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, 9577 EVT MemVT, MachineMemOperand *MMO) { 9578 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9579 SDVTList VTs = getVTList(MVT::Other); 9580 SDValue Ops[] = {Chain, Ptr}; 9581 FoldingSetNodeID ID; 9582 AddNodeIDNode(ID, ISD::SET_FPENV_MEM, VTs, Ops); 9583 ID.AddInteger(MemVT.getRawBits()); 9584 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>( 9585 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO)); 9586 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9587 ID.AddInteger(MMO->getFlags()); 9588 void *IP = nullptr; 9589 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 9590 return SDValue(E, 0); 9591 9592 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(), 9593 dl.getDebugLoc(), VTs, MemVT, MMO); 9594 createOperands(N, Ops); 9595 9596 CSEMap.InsertNode(N, IP); 9597 InsertNode(N); 9598 SDValue V(N, 0); 9599 NewSDValueDbgMsg(V, "Creating new node: ", this); 9600 return V; 9601 } 9602 9603 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 9604 // select undef, T, F --> T (if T is a constant), otherwise F 9605 // select, ?, undef, F --> F 9606 // select, ?, T, undef --> T 9607 if (Cond.isUndef()) 9608 return isConstantValueOfAnyType(T) ? T : F; 9609 if (T.isUndef()) 9610 return F; 9611 if (F.isUndef()) 9612 return T; 9613 9614 // select true, T, F --> T 9615 // select false, T, F --> F 9616 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 9617 return CondC->isZero() ? F : T; 9618 9619 // TODO: This should simplify VSELECT with non-zero constant condition using 9620 // something like this (but check boolean contents to be complete?): 9621 if (ConstantSDNode *CondC = isConstOrConstSplat(Cond, /*AllowUndefs*/ false, 9622 /*AllowTruncation*/ true)) 9623 if (CondC->isZero()) 9624 return F; 9625 9626 // select ?, T, T --> T 9627 if (T == F) 9628 return T; 9629 9630 return SDValue(); 9631 } 9632 9633 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 9634 // shift undef, Y --> 0 (can always assume that the undef value is 0) 9635 if (X.isUndef()) 9636 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 9637 // shift X, undef --> undef (because it may shift by the bitwidth) 9638 if (Y.isUndef()) 9639 return getUNDEF(X.getValueType()); 9640 9641 // shift 0, Y --> 0 9642 // shift X, 0 --> X 9643 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 9644 return X; 9645 9646 // shift X, C >= bitwidth(X) --> undef 9647 // All vector elements must be too big (or undef) to avoid partial undefs. 9648 auto isShiftTooBig = [X](ConstantSDNode *Val) { 9649 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 9650 }; 9651 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 9652 return getUNDEF(X.getValueType()); 9653 9654 return SDValue(); 9655 } 9656 9657 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 9658 SDNodeFlags Flags) { 9659 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 9660 // (an undef operand can be chosen to be Nan/Inf), then the result of this 9661 // operation is poison. That result can be relaxed to undef. 9662 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 9663 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 9664 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 9665 (YC && YC->getValueAPF().isNaN()); 9666 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 9667 (YC && YC->getValueAPF().isInfinity()); 9668 9669 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 9670 return getUNDEF(X.getValueType()); 9671 9672 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 9673 return getUNDEF(X.getValueType()); 9674 9675 if (!YC) 9676 return SDValue(); 9677 9678 // X + -0.0 --> X 9679 if (Opcode == ISD::FADD) 9680 if (YC->getValueAPF().isNegZero()) 9681 return X; 9682 9683 // X - +0.0 --> X 9684 if (Opcode == ISD::FSUB) 9685 if (YC->getValueAPF().isPosZero()) 9686 return X; 9687 9688 // X * 1.0 --> X 9689 // X / 1.0 --> X 9690 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 9691 if (YC->getValueAPF().isExactlyValue(1.0)) 9692 return X; 9693 9694 // X * 0.0 --> 0.0 9695 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 9696 if (YC->getValueAPF().isZero()) 9697 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 9698 9699 return SDValue(); 9700 } 9701 9702 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 9703 SDValue Ptr, SDValue SV, unsigned Align) { 9704 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 9705 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 9706 } 9707 9708 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 9709 ArrayRef<SDUse> Ops) { 9710 switch (Ops.size()) { 9711 case 0: return getNode(Opcode, DL, VT); 9712 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 9713 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 9714 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 9715 default: break; 9716 } 9717 9718 // Copy from an SDUse array into an SDValue array for use with 9719 // the regular getNode logic. 9720 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 9721 return getNode(Opcode, DL, VT, NewOps); 9722 } 9723 9724 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 9725 ArrayRef<SDValue> Ops) { 9726 SDNodeFlags Flags; 9727 if (Inserter) 9728 Flags = Inserter->getFlags(); 9729 return getNode(Opcode, DL, VT, Ops, Flags); 9730 } 9731 9732 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 9733 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 9734 unsigned NumOps = Ops.size(); 9735 switch (NumOps) { 9736 case 0: return getNode(Opcode, DL, VT); 9737 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 9738 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 9739 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 9740 default: break; 9741 } 9742 9743 #ifndef NDEBUG 9744 for (const auto &Op : Ops) 9745 assert(Op.getOpcode() != ISD::DELETED_NODE && 9746 "Operand is DELETED_NODE!"); 9747 #endif 9748 9749 switch (Opcode) { 9750 default: break; 9751 case ISD::BUILD_VECTOR: 9752 // Attempt to simplify BUILD_VECTOR. 9753 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 9754 return V; 9755 break; 9756 case ISD::CONCAT_VECTORS: 9757 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 9758 return V; 9759 break; 9760 case ISD::SELECT_CC: 9761 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 9762 assert(Ops[0].getValueType() == Ops[1].getValueType() && 9763 "LHS and RHS of condition must have same type!"); 9764 assert(Ops[2].getValueType() == Ops[3].getValueType() && 9765 "True and False arms of SelectCC must have same type!"); 9766 assert(Ops[2].getValueType() == VT && 9767 "select_cc node must be of same type as true and false value!"); 9768 assert((!Ops[0].getValueType().isVector() || 9769 Ops[0].getValueType().getVectorElementCount() == 9770 VT.getVectorElementCount()) && 9771 "Expected select_cc with vector result to have the same sized " 9772 "comparison type!"); 9773 break; 9774 case ISD::BR_CC: 9775 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 9776 assert(Ops[2].getValueType() == Ops[3].getValueType() && 9777 "LHS/RHS of comparison should match types!"); 9778 break; 9779 case ISD::VP_ADD: 9780 case ISD::VP_SUB: 9781 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR 9782 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 9783 Opcode = ISD::VP_XOR; 9784 break; 9785 case ISD::VP_MUL: 9786 // If it is VP_MUL mask operation then turn it to VP_AND 9787 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 9788 Opcode = ISD::VP_AND; 9789 break; 9790 case ISD::VP_REDUCE_MUL: 9791 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND 9792 if (VT == MVT::i1) 9793 Opcode = ISD::VP_REDUCE_AND; 9794 break; 9795 case ISD::VP_REDUCE_ADD: 9796 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR 9797 if (VT == MVT::i1) 9798 Opcode = ISD::VP_REDUCE_XOR; 9799 break; 9800 case ISD::VP_REDUCE_SMAX: 9801 case ISD::VP_REDUCE_UMIN: 9802 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to 9803 // VP_REDUCE_AND. 9804 if (VT == MVT::i1) 9805 Opcode = ISD::VP_REDUCE_AND; 9806 break; 9807 case ISD::VP_REDUCE_SMIN: 9808 case ISD::VP_REDUCE_UMAX: 9809 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to 9810 // VP_REDUCE_OR. 9811 if (VT == MVT::i1) 9812 Opcode = ISD::VP_REDUCE_OR; 9813 break; 9814 } 9815 9816 // Memoize nodes. 9817 SDNode *N; 9818 SDVTList VTs = getVTList(VT); 9819 9820 if (VT != MVT::Glue) { 9821 FoldingSetNodeID ID; 9822 AddNodeIDNode(ID, Opcode, VTs, Ops); 9823 void *IP = nullptr; 9824 9825 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9826 return SDValue(E, 0); 9827 9828 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9829 createOperands(N, Ops); 9830 9831 CSEMap.InsertNode(N, IP); 9832 } else { 9833 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9834 createOperands(N, Ops); 9835 } 9836 9837 N->setFlags(Flags); 9838 InsertNode(N); 9839 SDValue V(N, 0); 9840 NewSDValueDbgMsg(V, "Creating new node: ", this); 9841 return V; 9842 } 9843 9844 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 9845 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 9846 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 9847 } 9848 9849 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9850 ArrayRef<SDValue> Ops) { 9851 SDNodeFlags Flags; 9852 if (Inserter) 9853 Flags = Inserter->getFlags(); 9854 return getNode(Opcode, DL, VTList, Ops, Flags); 9855 } 9856 9857 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9858 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 9859 if (VTList.NumVTs == 1) 9860 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags); 9861 9862 #ifndef NDEBUG 9863 for (const auto &Op : Ops) 9864 assert(Op.getOpcode() != ISD::DELETED_NODE && 9865 "Operand is DELETED_NODE!"); 9866 #endif 9867 9868 switch (Opcode) { 9869 case ISD::SADDO: 9870 case ISD::UADDO: 9871 case ISD::SSUBO: 9872 case ISD::USUBO: { 9873 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 9874 "Invalid add/sub overflow op!"); 9875 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() && 9876 Ops[0].getValueType() == Ops[1].getValueType() && 9877 Ops[0].getValueType() == VTList.VTs[0] && 9878 "Binary operator types must match!"); 9879 SDValue N1 = Ops[0], N2 = Ops[1]; 9880 canonicalizeCommutativeBinop(Opcode, N1, N2); 9881 9882 // (X +- 0) -> X with zero-overflow. 9883 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false, 9884 /*AllowTruncation*/ true); 9885 if (N2CV && N2CV->isZero()) { 9886 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]); 9887 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags); 9888 } 9889 9890 if (VTList.VTs[0].isVector() && 9891 VTList.VTs[0].getVectorElementType() == MVT::i1 && 9892 VTList.VTs[1].getVectorElementType() == MVT::i1) { 9893 SDValue F1 = getFreeze(N1); 9894 SDValue F2 = getFreeze(N2); 9895 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)} 9896 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO) 9897 return getNode(ISD::MERGE_VALUES, DL, VTList, 9898 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2), 9899 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)}, 9900 Flags); 9901 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)} 9902 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) { 9903 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]); 9904 return getNode(ISD::MERGE_VALUES, DL, VTList, 9905 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2), 9906 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)}, 9907 Flags); 9908 } 9909 } 9910 break; 9911 } 9912 case ISD::SMUL_LOHI: 9913 case ISD::UMUL_LOHI: { 9914 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!"); 9915 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] && 9916 VTList.VTs[0] == Ops[0].getValueType() && 9917 VTList.VTs[0] == Ops[1].getValueType() && 9918 "Binary operator types must match!"); 9919 // Constant fold. 9920 ConstantSDNode *LHS = dyn_cast<ConstantSDNode>(Ops[0]); 9921 ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ops[1]); 9922 if (LHS && RHS) { 9923 unsigned Width = VTList.VTs[0].getScalarSizeInBits(); 9924 unsigned OutWidth = Width * 2; 9925 APInt Val = LHS->getAPIntValue(); 9926 APInt Mul = RHS->getAPIntValue(); 9927 if (Opcode == ISD::SMUL_LOHI) { 9928 Val = Val.sext(OutWidth); 9929 Mul = Mul.sext(OutWidth); 9930 } else { 9931 Val = Val.zext(OutWidth); 9932 Mul = Mul.zext(OutWidth); 9933 } 9934 Val *= Mul; 9935 9936 SDValue Hi = 9937 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]); 9938 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]); 9939 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags); 9940 } 9941 break; 9942 } 9943 case ISD::FFREXP: { 9944 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!"); 9945 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() && 9946 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch"); 9947 9948 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Ops[0])) { 9949 int FrexpExp; 9950 APFloat FrexpMant = 9951 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven); 9952 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]); 9953 SDValue Result1 = 9954 getConstant(FrexpMant.isFinite() ? FrexpExp : 0, DL, VTList.VTs[1]); 9955 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags); 9956 } 9957 9958 break; 9959 } 9960 case ISD::STRICT_FP_EXTEND: 9961 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 9962 "Invalid STRICT_FP_EXTEND!"); 9963 assert(VTList.VTs[0].isFloatingPoint() && 9964 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 9965 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9966 "STRICT_FP_EXTEND result type should be vector iff the operand " 9967 "type is vector!"); 9968 assert((!VTList.VTs[0].isVector() || 9969 VTList.VTs[0].getVectorElementCount() == 9970 Ops[1].getValueType().getVectorElementCount()) && 9971 "Vector element count mismatch!"); 9972 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 9973 "Invalid fpext node, dst <= src!"); 9974 break; 9975 case ISD::STRICT_FP_ROUND: 9976 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 9977 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9978 "STRICT_FP_ROUND result type should be vector iff the operand " 9979 "type is vector!"); 9980 assert((!VTList.VTs[0].isVector() || 9981 VTList.VTs[0].getVectorElementCount() == 9982 Ops[1].getValueType().getVectorElementCount()) && 9983 "Vector element count mismatch!"); 9984 assert(VTList.VTs[0].isFloatingPoint() && 9985 Ops[1].getValueType().isFloatingPoint() && 9986 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 9987 isa<ConstantSDNode>(Ops[2]) && 9988 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) && 9989 "Invalid STRICT_FP_ROUND!"); 9990 break; 9991 #if 0 9992 // FIXME: figure out how to safely handle things like 9993 // int foo(int x) { return 1 << (x & 255); } 9994 // int bar() { return foo(256); } 9995 case ISD::SRA_PARTS: 9996 case ISD::SRL_PARTS: 9997 case ISD::SHL_PARTS: 9998 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 9999 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 10000 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 10001 else if (N3.getOpcode() == ISD::AND) 10002 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 10003 // If the and is only masking out bits that cannot effect the shift, 10004 // eliminate the and. 10005 unsigned NumBits = VT.getScalarSizeInBits()*2; 10006 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 10007 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 10008 } 10009 break; 10010 #endif 10011 } 10012 10013 // Memoize the node unless it returns a glue result. 10014 SDNode *N; 10015 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 10016 FoldingSetNodeID ID; 10017 AddNodeIDNode(ID, Opcode, VTList, Ops); 10018 void *IP = nullptr; 10019 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 10020 return SDValue(E, 0); 10021 10022 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 10023 createOperands(N, Ops); 10024 CSEMap.InsertNode(N, IP); 10025 } else { 10026 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 10027 createOperands(N, Ops); 10028 } 10029 10030 N->setFlags(Flags); 10031 InsertNode(N); 10032 SDValue V(N, 0); 10033 NewSDValueDbgMsg(V, "Creating new node: ", this); 10034 return V; 10035 } 10036 10037 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 10038 SDVTList VTList) { 10039 return getNode(Opcode, DL, VTList, std::nullopt); 10040 } 10041 10042 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 10043 SDValue N1) { 10044 SDValue Ops[] = { N1 }; 10045 return getNode(Opcode, DL, VTList, Ops); 10046 } 10047 10048 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 10049 SDValue N1, SDValue N2) { 10050 SDValue Ops[] = { N1, N2 }; 10051 return getNode(Opcode, DL, VTList, Ops); 10052 } 10053 10054 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 10055 SDValue N1, SDValue N2, SDValue N3) { 10056 SDValue Ops[] = { N1, N2, N3 }; 10057 return getNode(Opcode, DL, VTList, Ops); 10058 } 10059 10060 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 10061 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 10062 SDValue Ops[] = { N1, N2, N3, N4 }; 10063 return getNode(Opcode, DL, VTList, Ops); 10064 } 10065 10066 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 10067 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 10068 SDValue N5) { 10069 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 10070 return getNode(Opcode, DL, VTList, Ops); 10071 } 10072 10073 SDVTList SelectionDAG::getVTList(EVT VT) { 10074 return makeVTList(SDNode::getValueTypeList(VT), 1); 10075 } 10076 10077 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 10078 FoldingSetNodeID ID; 10079 ID.AddInteger(2U); 10080 ID.AddInteger(VT1.getRawBits()); 10081 ID.AddInteger(VT2.getRawBits()); 10082 10083 void *IP = nullptr; 10084 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 10085 if (!Result) { 10086 EVT *Array = Allocator.Allocate<EVT>(2); 10087 Array[0] = VT1; 10088 Array[1] = VT2; 10089 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 10090 VTListMap.InsertNode(Result, IP); 10091 } 10092 return Result->getSDVTList(); 10093 } 10094 10095 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 10096 FoldingSetNodeID ID; 10097 ID.AddInteger(3U); 10098 ID.AddInteger(VT1.getRawBits()); 10099 ID.AddInteger(VT2.getRawBits()); 10100 ID.AddInteger(VT3.getRawBits()); 10101 10102 void *IP = nullptr; 10103 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 10104 if (!Result) { 10105 EVT *Array = Allocator.Allocate<EVT>(3); 10106 Array[0] = VT1; 10107 Array[1] = VT2; 10108 Array[2] = VT3; 10109 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 10110 VTListMap.InsertNode(Result, IP); 10111 } 10112 return Result->getSDVTList(); 10113 } 10114 10115 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 10116 FoldingSetNodeID ID; 10117 ID.AddInteger(4U); 10118 ID.AddInteger(VT1.getRawBits()); 10119 ID.AddInteger(VT2.getRawBits()); 10120 ID.AddInteger(VT3.getRawBits()); 10121 ID.AddInteger(VT4.getRawBits()); 10122 10123 void *IP = nullptr; 10124 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 10125 if (!Result) { 10126 EVT *Array = Allocator.Allocate<EVT>(4); 10127 Array[0] = VT1; 10128 Array[1] = VT2; 10129 Array[2] = VT3; 10130 Array[3] = VT4; 10131 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 10132 VTListMap.InsertNode(Result, IP); 10133 } 10134 return Result->getSDVTList(); 10135 } 10136 10137 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 10138 unsigned NumVTs = VTs.size(); 10139 FoldingSetNodeID ID; 10140 ID.AddInteger(NumVTs); 10141 for (unsigned index = 0; index < NumVTs; index++) { 10142 ID.AddInteger(VTs[index].getRawBits()); 10143 } 10144 10145 void *IP = nullptr; 10146 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 10147 if (!Result) { 10148 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 10149 llvm::copy(VTs, Array); 10150 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 10151 VTListMap.InsertNode(Result, IP); 10152 } 10153 return Result->getSDVTList(); 10154 } 10155 10156 10157 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 10158 /// specified operands. If the resultant node already exists in the DAG, 10159 /// this does not modify the specified node, instead it returns the node that 10160 /// already exists. If the resultant node does not exist in the DAG, the 10161 /// input node is returned. As a degenerate case, if you specify the same 10162 /// input operands as the node already has, the input node is returned. 10163 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 10164 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 10165 10166 // Check to see if there is no change. 10167 if (Op == N->getOperand(0)) return N; 10168 10169 // See if the modified node already exists. 10170 void *InsertPos = nullptr; 10171 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 10172 return Existing; 10173 10174 // Nope it doesn't. Remove the node from its current place in the maps. 10175 if (InsertPos) 10176 if (!RemoveNodeFromCSEMaps(N)) 10177 InsertPos = nullptr; 10178 10179 // Now we update the operands. 10180 N->OperandList[0].set(Op); 10181 10182 updateDivergence(N); 10183 // If this gets put into a CSE map, add it. 10184 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 10185 return N; 10186 } 10187 10188 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 10189 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 10190 10191 // Check to see if there is no change. 10192 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 10193 return N; // No operands changed, just return the input node. 10194 10195 // See if the modified node already exists. 10196 void *InsertPos = nullptr; 10197 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 10198 return Existing; 10199 10200 // Nope it doesn't. Remove the node from its current place in the maps. 10201 if (InsertPos) 10202 if (!RemoveNodeFromCSEMaps(N)) 10203 InsertPos = nullptr; 10204 10205 // Now we update the operands. 10206 if (N->OperandList[0] != Op1) 10207 N->OperandList[0].set(Op1); 10208 if (N->OperandList[1] != Op2) 10209 N->OperandList[1].set(Op2); 10210 10211 updateDivergence(N); 10212 // If this gets put into a CSE map, add it. 10213 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 10214 return N; 10215 } 10216 10217 SDNode *SelectionDAG:: 10218 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 10219 SDValue Ops[] = { Op1, Op2, Op3 }; 10220 return UpdateNodeOperands(N, Ops); 10221 } 10222 10223 SDNode *SelectionDAG:: 10224 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 10225 SDValue Op3, SDValue Op4) { 10226 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 10227 return UpdateNodeOperands(N, Ops); 10228 } 10229 10230 SDNode *SelectionDAG:: 10231 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 10232 SDValue Op3, SDValue Op4, SDValue Op5) { 10233 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 10234 return UpdateNodeOperands(N, Ops); 10235 } 10236 10237 SDNode *SelectionDAG:: 10238 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 10239 unsigned NumOps = Ops.size(); 10240 assert(N->getNumOperands() == NumOps && 10241 "Update with wrong number of operands"); 10242 10243 // If no operands changed just return the input node. 10244 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 10245 return N; 10246 10247 // See if the modified node already exists. 10248 void *InsertPos = nullptr; 10249 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 10250 return Existing; 10251 10252 // Nope it doesn't. Remove the node from its current place in the maps. 10253 if (InsertPos) 10254 if (!RemoveNodeFromCSEMaps(N)) 10255 InsertPos = nullptr; 10256 10257 // Now we update the operands. 10258 for (unsigned i = 0; i != NumOps; ++i) 10259 if (N->OperandList[i] != Ops[i]) 10260 N->OperandList[i].set(Ops[i]); 10261 10262 updateDivergence(N); 10263 // If this gets put into a CSE map, add it. 10264 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 10265 return N; 10266 } 10267 10268 /// DropOperands - Release the operands and set this node to have 10269 /// zero operands. 10270 void SDNode::DropOperands() { 10271 // Unlike the code in MorphNodeTo that does this, we don't need to 10272 // watch for dead nodes here. 10273 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 10274 SDUse &Use = *I++; 10275 Use.set(SDValue()); 10276 } 10277 } 10278 10279 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 10280 ArrayRef<MachineMemOperand *> NewMemRefs) { 10281 if (NewMemRefs.empty()) { 10282 N->clearMemRefs(); 10283 return; 10284 } 10285 10286 // Check if we can avoid allocating by storing a single reference directly. 10287 if (NewMemRefs.size() == 1) { 10288 N->MemRefs = NewMemRefs[0]; 10289 N->NumMemRefs = 1; 10290 return; 10291 } 10292 10293 MachineMemOperand **MemRefsBuffer = 10294 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 10295 llvm::copy(NewMemRefs, MemRefsBuffer); 10296 N->MemRefs = MemRefsBuffer; 10297 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 10298 } 10299 10300 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 10301 /// machine opcode. 10302 /// 10303 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10304 EVT VT) { 10305 SDVTList VTs = getVTList(VT); 10306 return SelectNodeTo(N, MachineOpc, VTs, std::nullopt); 10307 } 10308 10309 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10310 EVT VT, SDValue Op1) { 10311 SDVTList VTs = getVTList(VT); 10312 SDValue Ops[] = { Op1 }; 10313 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10314 } 10315 10316 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10317 EVT VT, SDValue Op1, 10318 SDValue Op2) { 10319 SDVTList VTs = getVTList(VT); 10320 SDValue Ops[] = { Op1, Op2 }; 10321 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10322 } 10323 10324 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10325 EVT VT, SDValue Op1, 10326 SDValue Op2, SDValue Op3) { 10327 SDVTList VTs = getVTList(VT); 10328 SDValue Ops[] = { Op1, Op2, Op3 }; 10329 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10330 } 10331 10332 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10333 EVT VT, ArrayRef<SDValue> Ops) { 10334 SDVTList VTs = getVTList(VT); 10335 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10336 } 10337 10338 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10339 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 10340 SDVTList VTs = getVTList(VT1, VT2); 10341 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10342 } 10343 10344 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10345 EVT VT1, EVT VT2) { 10346 SDVTList VTs = getVTList(VT1, VT2); 10347 return SelectNodeTo(N, MachineOpc, VTs, std::nullopt); 10348 } 10349 10350 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10351 EVT VT1, EVT VT2, EVT VT3, 10352 ArrayRef<SDValue> Ops) { 10353 SDVTList VTs = getVTList(VT1, VT2, VT3); 10354 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10355 } 10356 10357 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10358 EVT VT1, EVT VT2, 10359 SDValue Op1, SDValue Op2) { 10360 SDVTList VTs = getVTList(VT1, VT2); 10361 SDValue Ops[] = { Op1, Op2 }; 10362 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10363 } 10364 10365 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10366 SDVTList VTs,ArrayRef<SDValue> Ops) { 10367 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 10368 // Reset the NodeID to -1. 10369 New->setNodeId(-1); 10370 if (New != N) { 10371 ReplaceAllUsesWith(N, New); 10372 RemoveDeadNode(N); 10373 } 10374 return New; 10375 } 10376 10377 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 10378 /// the line number information on the merged node since it is not possible to 10379 /// preserve the information that operation is associated with multiple lines. 10380 /// This will make the debugger working better at -O0, were there is a higher 10381 /// probability having other instructions associated with that line. 10382 /// 10383 /// For IROrder, we keep the smaller of the two 10384 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 10385 DebugLoc NLoc = N->getDebugLoc(); 10386 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) { 10387 N->setDebugLoc(DebugLoc()); 10388 } 10389 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 10390 N->setIROrder(Order); 10391 return N; 10392 } 10393 10394 /// MorphNodeTo - This *mutates* the specified node to have the specified 10395 /// return type, opcode, and operands. 10396 /// 10397 /// Note that MorphNodeTo returns the resultant node. If there is already a 10398 /// node of the specified opcode and operands, it returns that node instead of 10399 /// the current one. Note that the SDLoc need not be the same. 10400 /// 10401 /// Using MorphNodeTo is faster than creating a new node and swapping it in 10402 /// with ReplaceAllUsesWith both because it often avoids allocating a new 10403 /// node, and because it doesn't require CSE recalculation for any of 10404 /// the node's users. 10405 /// 10406 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 10407 /// As a consequence it isn't appropriate to use from within the DAG combiner or 10408 /// the legalizer which maintain worklists that would need to be updated when 10409 /// deleting things. 10410 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 10411 SDVTList VTs, ArrayRef<SDValue> Ops) { 10412 // If an identical node already exists, use it. 10413 void *IP = nullptr; 10414 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 10415 FoldingSetNodeID ID; 10416 AddNodeIDNode(ID, Opc, VTs, Ops); 10417 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 10418 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 10419 } 10420 10421 if (!RemoveNodeFromCSEMaps(N)) 10422 IP = nullptr; 10423 10424 // Start the morphing. 10425 N->NodeType = Opc; 10426 N->ValueList = VTs.VTs; 10427 N->NumValues = VTs.NumVTs; 10428 10429 // Clear the operands list, updating used nodes to remove this from their 10430 // use list. Keep track of any operands that become dead as a result. 10431 SmallPtrSet<SDNode*, 16> DeadNodeSet; 10432 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 10433 SDUse &Use = *I++; 10434 SDNode *Used = Use.getNode(); 10435 Use.set(SDValue()); 10436 if (Used->use_empty()) 10437 DeadNodeSet.insert(Used); 10438 } 10439 10440 // For MachineNode, initialize the memory references information. 10441 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 10442 MN->clearMemRefs(); 10443 10444 // Swap for an appropriately sized array from the recycler. 10445 removeOperands(N); 10446 createOperands(N, Ops); 10447 10448 // Delete any nodes that are still dead after adding the uses for the 10449 // new operands. 10450 if (!DeadNodeSet.empty()) { 10451 SmallVector<SDNode *, 16> DeadNodes; 10452 for (SDNode *N : DeadNodeSet) 10453 if (N->use_empty()) 10454 DeadNodes.push_back(N); 10455 RemoveDeadNodes(DeadNodes); 10456 } 10457 10458 if (IP) 10459 CSEMap.InsertNode(N, IP); // Memoize the new node. 10460 return N; 10461 } 10462 10463 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 10464 unsigned OrigOpc = Node->getOpcode(); 10465 unsigned NewOpc; 10466 switch (OrigOpc) { 10467 default: 10468 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 10469 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 10470 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 10471 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 10472 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 10473 #include "llvm/IR/ConstrainedOps.def" 10474 } 10475 10476 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 10477 10478 // We're taking this node out of the chain, so we need to re-link things. 10479 SDValue InputChain = Node->getOperand(0); 10480 SDValue OutputChain = SDValue(Node, 1); 10481 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 10482 10483 SmallVector<SDValue, 3> Ops; 10484 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 10485 Ops.push_back(Node->getOperand(i)); 10486 10487 SDVTList VTs = getVTList(Node->getValueType(0)); 10488 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 10489 10490 // MorphNodeTo can operate in two ways: if an existing node with the 10491 // specified operands exists, it can just return it. Otherwise, it 10492 // updates the node in place to have the requested operands. 10493 if (Res == Node) { 10494 // If we updated the node in place, reset the node ID. To the isel, 10495 // this should be just like a newly allocated machine node. 10496 Res->setNodeId(-1); 10497 } else { 10498 ReplaceAllUsesWith(Node, Res); 10499 RemoveDeadNode(Node); 10500 } 10501 10502 return Res; 10503 } 10504 10505 /// getMachineNode - These are used for target selectors to create a new node 10506 /// with specified return type(s), MachineInstr opcode, and operands. 10507 /// 10508 /// Note that getMachineNode returns the resultant node. If there is already a 10509 /// node of the specified opcode and operands, it returns that node instead of 10510 /// the current one. 10511 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10512 EVT VT) { 10513 SDVTList VTs = getVTList(VT); 10514 return getMachineNode(Opcode, dl, VTs, std::nullopt); 10515 } 10516 10517 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10518 EVT VT, SDValue Op1) { 10519 SDVTList VTs = getVTList(VT); 10520 SDValue Ops[] = { Op1 }; 10521 return getMachineNode(Opcode, dl, VTs, Ops); 10522 } 10523 10524 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10525 EVT VT, SDValue Op1, SDValue Op2) { 10526 SDVTList VTs = getVTList(VT); 10527 SDValue Ops[] = { Op1, Op2 }; 10528 return getMachineNode(Opcode, dl, VTs, Ops); 10529 } 10530 10531 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10532 EVT VT, SDValue Op1, SDValue Op2, 10533 SDValue Op3) { 10534 SDVTList VTs = getVTList(VT); 10535 SDValue Ops[] = { Op1, Op2, Op3 }; 10536 return getMachineNode(Opcode, dl, VTs, Ops); 10537 } 10538 10539 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10540 EVT VT, ArrayRef<SDValue> Ops) { 10541 SDVTList VTs = getVTList(VT); 10542 return getMachineNode(Opcode, dl, VTs, Ops); 10543 } 10544 10545 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10546 EVT VT1, EVT VT2, SDValue Op1, 10547 SDValue Op2) { 10548 SDVTList VTs = getVTList(VT1, VT2); 10549 SDValue Ops[] = { Op1, Op2 }; 10550 return getMachineNode(Opcode, dl, VTs, Ops); 10551 } 10552 10553 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10554 EVT VT1, EVT VT2, SDValue Op1, 10555 SDValue Op2, SDValue Op3) { 10556 SDVTList VTs = getVTList(VT1, VT2); 10557 SDValue Ops[] = { Op1, Op2, Op3 }; 10558 return getMachineNode(Opcode, dl, VTs, Ops); 10559 } 10560 10561 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10562 EVT VT1, EVT VT2, 10563 ArrayRef<SDValue> Ops) { 10564 SDVTList VTs = getVTList(VT1, VT2); 10565 return getMachineNode(Opcode, dl, VTs, Ops); 10566 } 10567 10568 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10569 EVT VT1, EVT VT2, EVT VT3, 10570 SDValue Op1, SDValue Op2) { 10571 SDVTList VTs = getVTList(VT1, VT2, VT3); 10572 SDValue Ops[] = { Op1, Op2 }; 10573 return getMachineNode(Opcode, dl, VTs, Ops); 10574 } 10575 10576 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10577 EVT VT1, EVT VT2, EVT VT3, 10578 SDValue Op1, SDValue Op2, 10579 SDValue Op3) { 10580 SDVTList VTs = getVTList(VT1, VT2, VT3); 10581 SDValue Ops[] = { Op1, Op2, Op3 }; 10582 return getMachineNode(Opcode, dl, VTs, Ops); 10583 } 10584 10585 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10586 EVT VT1, EVT VT2, EVT VT3, 10587 ArrayRef<SDValue> Ops) { 10588 SDVTList VTs = getVTList(VT1, VT2, VT3); 10589 return getMachineNode(Opcode, dl, VTs, Ops); 10590 } 10591 10592 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10593 ArrayRef<EVT> ResultTys, 10594 ArrayRef<SDValue> Ops) { 10595 SDVTList VTs = getVTList(ResultTys); 10596 return getMachineNode(Opcode, dl, VTs, Ops); 10597 } 10598 10599 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 10600 SDVTList VTs, 10601 ArrayRef<SDValue> Ops) { 10602 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 10603 MachineSDNode *N; 10604 void *IP = nullptr; 10605 10606 if (DoCSE) { 10607 FoldingSetNodeID ID; 10608 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 10609 IP = nullptr; 10610 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 10611 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 10612 } 10613 } 10614 10615 // Allocate a new MachineSDNode. 10616 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 10617 createOperands(N, Ops); 10618 10619 if (DoCSE) 10620 CSEMap.InsertNode(N, IP); 10621 10622 InsertNode(N); 10623 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 10624 return N; 10625 } 10626 10627 /// getTargetExtractSubreg - A convenience function for creating 10628 /// TargetOpcode::EXTRACT_SUBREG nodes. 10629 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 10630 SDValue Operand) { 10631 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 10632 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 10633 VT, Operand, SRIdxVal); 10634 return SDValue(Subreg, 0); 10635 } 10636 10637 /// getTargetInsertSubreg - A convenience function for creating 10638 /// TargetOpcode::INSERT_SUBREG nodes. 10639 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 10640 SDValue Operand, SDValue Subreg) { 10641 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 10642 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 10643 VT, Operand, Subreg, SRIdxVal); 10644 return SDValue(Result, 0); 10645 } 10646 10647 /// getNodeIfExists - Get the specified node if it's already available, or 10648 /// else return NULL. 10649 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 10650 ArrayRef<SDValue> Ops) { 10651 SDNodeFlags Flags; 10652 if (Inserter) 10653 Flags = Inserter->getFlags(); 10654 return getNodeIfExists(Opcode, VTList, Ops, Flags); 10655 } 10656 10657 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 10658 ArrayRef<SDValue> Ops, 10659 const SDNodeFlags Flags) { 10660 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 10661 FoldingSetNodeID ID; 10662 AddNodeIDNode(ID, Opcode, VTList, Ops); 10663 void *IP = nullptr; 10664 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 10665 E->intersectFlagsWith(Flags); 10666 return E; 10667 } 10668 } 10669 return nullptr; 10670 } 10671 10672 /// doesNodeExist - Check if a node exists without modifying its flags. 10673 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 10674 ArrayRef<SDValue> Ops) { 10675 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 10676 FoldingSetNodeID ID; 10677 AddNodeIDNode(ID, Opcode, VTList, Ops); 10678 void *IP = nullptr; 10679 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 10680 return true; 10681 } 10682 return false; 10683 } 10684 10685 /// getDbgValue - Creates a SDDbgValue node. 10686 /// 10687 /// SDNode 10688 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 10689 SDNode *N, unsigned R, bool IsIndirect, 10690 const DebugLoc &DL, unsigned O) { 10691 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10692 "Expected inlined-at fields to agree"); 10693 return new (DbgInfo->getAlloc()) 10694 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 10695 {}, IsIndirect, DL, O, 10696 /*IsVariadic=*/false); 10697 } 10698 10699 /// Constant 10700 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 10701 DIExpression *Expr, 10702 const Value *C, 10703 const DebugLoc &DL, unsigned O) { 10704 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10705 "Expected inlined-at fields to agree"); 10706 return new (DbgInfo->getAlloc()) 10707 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 10708 /*IsIndirect=*/false, DL, O, 10709 /*IsVariadic=*/false); 10710 } 10711 10712 /// FrameIndex 10713 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 10714 DIExpression *Expr, unsigned FI, 10715 bool IsIndirect, 10716 const DebugLoc &DL, 10717 unsigned O) { 10718 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10719 "Expected inlined-at fields to agree"); 10720 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 10721 } 10722 10723 /// FrameIndex with dependencies 10724 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 10725 DIExpression *Expr, unsigned FI, 10726 ArrayRef<SDNode *> Dependencies, 10727 bool IsIndirect, 10728 const DebugLoc &DL, 10729 unsigned O) { 10730 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10731 "Expected inlined-at fields to agree"); 10732 return new (DbgInfo->getAlloc()) 10733 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 10734 Dependencies, IsIndirect, DL, O, 10735 /*IsVariadic=*/false); 10736 } 10737 10738 /// VReg 10739 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 10740 unsigned VReg, bool IsIndirect, 10741 const DebugLoc &DL, unsigned O) { 10742 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10743 "Expected inlined-at fields to agree"); 10744 return new (DbgInfo->getAlloc()) 10745 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 10746 {}, IsIndirect, DL, O, 10747 /*IsVariadic=*/false); 10748 } 10749 10750 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 10751 ArrayRef<SDDbgOperand> Locs, 10752 ArrayRef<SDNode *> Dependencies, 10753 bool IsIndirect, const DebugLoc &DL, 10754 unsigned O, bool IsVariadic) { 10755 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10756 "Expected inlined-at fields to agree"); 10757 return new (DbgInfo->getAlloc()) 10758 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 10759 DL, O, IsVariadic); 10760 } 10761 10762 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 10763 unsigned OffsetInBits, unsigned SizeInBits, 10764 bool InvalidateDbg) { 10765 SDNode *FromNode = From.getNode(); 10766 SDNode *ToNode = To.getNode(); 10767 assert(FromNode && ToNode && "Can't modify dbg values"); 10768 10769 // PR35338 10770 // TODO: assert(From != To && "Redundant dbg value transfer"); 10771 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 10772 if (From == To || FromNode == ToNode) 10773 return; 10774 10775 if (!FromNode->getHasDebugValue()) 10776 return; 10777 10778 SDDbgOperand FromLocOp = 10779 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 10780 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 10781 10782 SmallVector<SDDbgValue *, 2> ClonedDVs; 10783 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 10784 if (Dbg->isInvalidated()) 10785 continue; 10786 10787 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 10788 10789 // Create a new location ops vector that is equal to the old vector, but 10790 // with each instance of FromLocOp replaced with ToLocOp. 10791 bool Changed = false; 10792 auto NewLocOps = Dbg->copyLocationOps(); 10793 std::replace_if( 10794 NewLocOps.begin(), NewLocOps.end(), 10795 [&Changed, FromLocOp](const SDDbgOperand &Op) { 10796 bool Match = Op == FromLocOp; 10797 Changed |= Match; 10798 return Match; 10799 }, 10800 ToLocOp); 10801 // Ignore this SDDbgValue if we didn't find a matching location. 10802 if (!Changed) 10803 continue; 10804 10805 DIVariable *Var = Dbg->getVariable(); 10806 auto *Expr = Dbg->getExpression(); 10807 // If a fragment is requested, update the expression. 10808 if (SizeInBits) { 10809 // When splitting a larger (e.g., sign-extended) value whose 10810 // lower bits are described with an SDDbgValue, do not attempt 10811 // to transfer the SDDbgValue to the upper bits. 10812 if (auto FI = Expr->getFragmentInfo()) 10813 if (OffsetInBits + SizeInBits > FI->SizeInBits) 10814 continue; 10815 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 10816 SizeInBits); 10817 if (!Fragment) 10818 continue; 10819 Expr = *Fragment; 10820 } 10821 10822 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 10823 // Clone the SDDbgValue and move it to To. 10824 SDDbgValue *Clone = getDbgValueList( 10825 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 10826 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 10827 Dbg->isVariadic()); 10828 ClonedDVs.push_back(Clone); 10829 10830 if (InvalidateDbg) { 10831 // Invalidate value and indicate the SDDbgValue should not be emitted. 10832 Dbg->setIsInvalidated(); 10833 Dbg->setIsEmitted(); 10834 } 10835 } 10836 10837 for (SDDbgValue *Dbg : ClonedDVs) { 10838 assert(is_contained(Dbg->getSDNodes(), ToNode) && 10839 "Transferred DbgValues should depend on the new SDNode"); 10840 AddDbgValue(Dbg, false); 10841 } 10842 } 10843 10844 void SelectionDAG::salvageDebugInfo(SDNode &N) { 10845 if (!N.getHasDebugValue()) 10846 return; 10847 10848 SmallVector<SDDbgValue *, 2> ClonedDVs; 10849 for (auto *DV : GetDbgValues(&N)) { 10850 if (DV->isInvalidated()) 10851 continue; 10852 switch (N.getOpcode()) { 10853 default: 10854 break; 10855 case ISD::ADD: { 10856 SDValue N0 = N.getOperand(0); 10857 SDValue N1 = N.getOperand(1); 10858 if (!isa<ConstantSDNode>(N0)) { 10859 bool RHSConstant = isa<ConstantSDNode>(N1); 10860 uint64_t Offset; 10861 if (RHSConstant) 10862 Offset = N.getConstantOperandVal(1); 10863 // We are not allowed to turn indirect debug values variadic, so 10864 // don't salvage those. 10865 if (!RHSConstant && DV->isIndirect()) 10866 continue; 10867 10868 // Rewrite an ADD constant node into a DIExpression. Since we are 10869 // performing arithmetic to compute the variable's *value* in the 10870 // DIExpression, we need to mark the expression with a 10871 // DW_OP_stack_value. 10872 auto *DIExpr = DV->getExpression(); 10873 auto NewLocOps = DV->copyLocationOps(); 10874 bool Changed = false; 10875 size_t OrigLocOpsSize = NewLocOps.size(); 10876 for (size_t i = 0; i < OrigLocOpsSize; ++i) { 10877 // We're not given a ResNo to compare against because the whole 10878 // node is going away. We know that any ISD::ADD only has one 10879 // result, so we can assume any node match is using the result. 10880 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 10881 NewLocOps[i].getSDNode() != &N) 10882 continue; 10883 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 10884 if (RHSConstant) { 10885 SmallVector<uint64_t, 3> ExprOps; 10886 DIExpression::appendOffset(ExprOps, Offset); 10887 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 10888 } else { 10889 // Convert to a variadic expression (if not already). 10890 // convertToVariadicExpression() returns a const pointer, so we use 10891 // a temporary const variable here. 10892 const auto *TmpDIExpr = 10893 DIExpression::convertToVariadicExpression(DIExpr); 10894 SmallVector<uint64_t, 3> ExprOps; 10895 ExprOps.push_back(dwarf::DW_OP_LLVM_arg); 10896 ExprOps.push_back(NewLocOps.size()); 10897 ExprOps.push_back(dwarf::DW_OP_plus); 10898 SDDbgOperand RHS = 10899 SDDbgOperand::fromNode(N1.getNode(), N1.getResNo()); 10900 NewLocOps.push_back(RHS); 10901 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true); 10902 } 10903 Changed = true; 10904 } 10905 (void)Changed; 10906 assert(Changed && "Salvage target doesn't use N"); 10907 10908 bool IsVariadic = 10909 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size(); 10910 10911 auto AdditionalDependencies = DV->getAdditionalDependencies(); 10912 SDDbgValue *Clone = getDbgValueList( 10913 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies, 10914 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic); 10915 ClonedDVs.push_back(Clone); 10916 DV->setIsInvalidated(); 10917 DV->setIsEmitted(); 10918 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 10919 N0.getNode()->dumprFull(this); 10920 dbgs() << " into " << *DIExpr << '\n'); 10921 } 10922 break; 10923 } 10924 case ISD::TRUNCATE: { 10925 SDValue N0 = N.getOperand(0); 10926 TypeSize FromSize = N0.getValueSizeInBits(); 10927 TypeSize ToSize = N.getValueSizeInBits(0); 10928 10929 DIExpression *DbgExpression = DV->getExpression(); 10930 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false); 10931 auto NewLocOps = DV->copyLocationOps(); 10932 bool Changed = false; 10933 for (size_t i = 0; i < NewLocOps.size(); ++i) { 10934 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 10935 NewLocOps[i].getSDNode() != &N) 10936 continue; 10937 10938 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 10939 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i); 10940 Changed = true; 10941 } 10942 assert(Changed && "Salvage target doesn't use N"); 10943 (void)Changed; 10944 10945 SDDbgValue *Clone = 10946 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps, 10947 DV->getAdditionalDependencies(), DV->isIndirect(), 10948 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic()); 10949 10950 ClonedDVs.push_back(Clone); 10951 DV->setIsInvalidated(); 10952 DV->setIsEmitted(); 10953 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this); 10954 dbgs() << " into " << *DbgExpression << '\n'); 10955 break; 10956 } 10957 } 10958 } 10959 10960 for (SDDbgValue *Dbg : ClonedDVs) { 10961 assert(!Dbg->getSDNodes().empty() && 10962 "Salvaged DbgValue should depend on a new SDNode"); 10963 AddDbgValue(Dbg, false); 10964 } 10965 } 10966 10967 /// Creates a SDDbgLabel node. 10968 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 10969 const DebugLoc &DL, unsigned O) { 10970 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 10971 "Expected inlined-at fields to agree"); 10972 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 10973 } 10974 10975 namespace { 10976 10977 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 10978 /// pointed to by a use iterator is deleted, increment the use iterator 10979 /// so that it doesn't dangle. 10980 /// 10981 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 10982 SDNode::use_iterator &UI; 10983 SDNode::use_iterator &UE; 10984 10985 void NodeDeleted(SDNode *N, SDNode *E) override { 10986 // Increment the iterator as needed. 10987 while (UI != UE && N == *UI) 10988 ++UI; 10989 } 10990 10991 public: 10992 RAUWUpdateListener(SelectionDAG &d, 10993 SDNode::use_iterator &ui, 10994 SDNode::use_iterator &ue) 10995 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 10996 }; 10997 10998 } // end anonymous namespace 10999 11000 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 11001 /// This can cause recursive merging of nodes in the DAG. 11002 /// 11003 /// This version assumes From has a single result value. 11004 /// 11005 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 11006 SDNode *From = FromN.getNode(); 11007 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 11008 "Cannot replace with this method!"); 11009 assert(From != To.getNode() && "Cannot replace uses of with self"); 11010 11011 // Preserve Debug Values 11012 transferDbgValues(FromN, To); 11013 // Preserve extra info. 11014 copyExtraInfo(From, To.getNode()); 11015 11016 // Iterate over all the existing uses of From. New uses will be added 11017 // to the beginning of the use list, which we avoid visiting. 11018 // This specifically avoids visiting uses of From that arise while the 11019 // replacement is happening, because any such uses would be the result 11020 // of CSE: If an existing node looks like From after one of its operands 11021 // is replaced by To, we don't want to replace of all its users with To 11022 // too. See PR3018 for more info. 11023 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 11024 RAUWUpdateListener Listener(*this, UI, UE); 11025 while (UI != UE) { 11026 SDNode *User = *UI; 11027 11028 // This node is about to morph, remove its old self from the CSE maps. 11029 RemoveNodeFromCSEMaps(User); 11030 11031 // A user can appear in a use list multiple times, and when this 11032 // happens the uses are usually next to each other in the list. 11033 // To help reduce the number of CSE recomputations, process all 11034 // the uses of this user that we can find this way. 11035 do { 11036 SDUse &Use = UI.getUse(); 11037 ++UI; 11038 Use.set(To); 11039 if (To->isDivergent() != From->isDivergent()) 11040 updateDivergence(User); 11041 } while (UI != UE && *UI == User); 11042 // Now that we have modified User, add it back to the CSE maps. If it 11043 // already exists there, recursively merge the results together. 11044 AddModifiedNodeToCSEMaps(User); 11045 } 11046 11047 // If we just RAUW'd the root, take note. 11048 if (FromN == getRoot()) 11049 setRoot(To); 11050 } 11051 11052 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 11053 /// This can cause recursive merging of nodes in the DAG. 11054 /// 11055 /// This version assumes that for each value of From, there is a 11056 /// corresponding value in To in the same position with the same type. 11057 /// 11058 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 11059 #ifndef NDEBUG 11060 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 11061 assert((!From->hasAnyUseOfValue(i) || 11062 From->getValueType(i) == To->getValueType(i)) && 11063 "Cannot use this version of ReplaceAllUsesWith!"); 11064 #endif 11065 11066 // Handle the trivial case. 11067 if (From == To) 11068 return; 11069 11070 // Preserve Debug Info. Only do this if there's a use. 11071 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 11072 if (From->hasAnyUseOfValue(i)) { 11073 assert((i < To->getNumValues()) && "Invalid To location"); 11074 transferDbgValues(SDValue(From, i), SDValue(To, i)); 11075 } 11076 // Preserve extra info. 11077 copyExtraInfo(From, To); 11078 11079 // Iterate over just the existing users of From. See the comments in 11080 // the ReplaceAllUsesWith above. 11081 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 11082 RAUWUpdateListener Listener(*this, UI, UE); 11083 while (UI != UE) { 11084 SDNode *User = *UI; 11085 11086 // This node is about to morph, remove its old self from the CSE maps. 11087 RemoveNodeFromCSEMaps(User); 11088 11089 // A user can appear in a use list multiple times, and when this 11090 // happens the uses are usually next to each other in the list. 11091 // To help reduce the number of CSE recomputations, process all 11092 // the uses of this user that we can find this way. 11093 do { 11094 SDUse &Use = UI.getUse(); 11095 ++UI; 11096 Use.setNode(To); 11097 if (To->isDivergent() != From->isDivergent()) 11098 updateDivergence(User); 11099 } while (UI != UE && *UI == User); 11100 11101 // Now that we have modified User, add it back to the CSE maps. If it 11102 // already exists there, recursively merge the results together. 11103 AddModifiedNodeToCSEMaps(User); 11104 } 11105 11106 // If we just RAUW'd the root, take note. 11107 if (From == getRoot().getNode()) 11108 setRoot(SDValue(To, getRoot().getResNo())); 11109 } 11110 11111 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 11112 /// This can cause recursive merging of nodes in the DAG. 11113 /// 11114 /// This version can replace From with any result values. To must match the 11115 /// number and types of values returned by From. 11116 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 11117 if (From->getNumValues() == 1) // Handle the simple case efficiently. 11118 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 11119 11120 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) { 11121 // Preserve Debug Info. 11122 transferDbgValues(SDValue(From, i), To[i]); 11123 // Preserve extra info. 11124 copyExtraInfo(From, To[i].getNode()); 11125 } 11126 11127 // Iterate over just the existing users of From. See the comments in 11128 // the ReplaceAllUsesWith above. 11129 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 11130 RAUWUpdateListener Listener(*this, UI, UE); 11131 while (UI != UE) { 11132 SDNode *User = *UI; 11133 11134 // This node is about to morph, remove its old self from the CSE maps. 11135 RemoveNodeFromCSEMaps(User); 11136 11137 // A user can appear in a use list multiple times, and when this happens the 11138 // uses are usually next to each other in the list. To help reduce the 11139 // number of CSE and divergence recomputations, process all the uses of this 11140 // user that we can find this way. 11141 bool To_IsDivergent = false; 11142 do { 11143 SDUse &Use = UI.getUse(); 11144 const SDValue &ToOp = To[Use.getResNo()]; 11145 ++UI; 11146 Use.set(ToOp); 11147 To_IsDivergent |= ToOp->isDivergent(); 11148 } while (UI != UE && *UI == User); 11149 11150 if (To_IsDivergent != From->isDivergent()) 11151 updateDivergence(User); 11152 11153 // Now that we have modified User, add it back to the CSE maps. If it 11154 // already exists there, recursively merge the results together. 11155 AddModifiedNodeToCSEMaps(User); 11156 } 11157 11158 // If we just RAUW'd the root, take note. 11159 if (From == getRoot().getNode()) 11160 setRoot(SDValue(To[getRoot().getResNo()])); 11161 } 11162 11163 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 11164 /// uses of other values produced by From.getNode() alone. The Deleted 11165 /// vector is handled the same way as for ReplaceAllUsesWith. 11166 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 11167 // Handle the really simple, really trivial case efficiently. 11168 if (From == To) return; 11169 11170 // Handle the simple, trivial, case efficiently. 11171 if (From.getNode()->getNumValues() == 1) { 11172 ReplaceAllUsesWith(From, To); 11173 return; 11174 } 11175 11176 // Preserve Debug Info. 11177 transferDbgValues(From, To); 11178 copyExtraInfo(From.getNode(), To.getNode()); 11179 11180 // Iterate over just the existing users of From. See the comments in 11181 // the ReplaceAllUsesWith above. 11182 SDNode::use_iterator UI = From.getNode()->use_begin(), 11183 UE = From.getNode()->use_end(); 11184 RAUWUpdateListener Listener(*this, UI, UE); 11185 while (UI != UE) { 11186 SDNode *User = *UI; 11187 bool UserRemovedFromCSEMaps = false; 11188 11189 // A user can appear in a use list multiple times, and when this 11190 // happens the uses are usually next to each other in the list. 11191 // To help reduce the number of CSE recomputations, process all 11192 // the uses of this user that we can find this way. 11193 do { 11194 SDUse &Use = UI.getUse(); 11195 11196 // Skip uses of different values from the same node. 11197 if (Use.getResNo() != From.getResNo()) { 11198 ++UI; 11199 continue; 11200 } 11201 11202 // If this node hasn't been modified yet, it's still in the CSE maps, 11203 // so remove its old self from the CSE maps. 11204 if (!UserRemovedFromCSEMaps) { 11205 RemoveNodeFromCSEMaps(User); 11206 UserRemovedFromCSEMaps = true; 11207 } 11208 11209 ++UI; 11210 Use.set(To); 11211 if (To->isDivergent() != From->isDivergent()) 11212 updateDivergence(User); 11213 } while (UI != UE && *UI == User); 11214 // We are iterating over all uses of the From node, so if a use 11215 // doesn't use the specific value, no changes are made. 11216 if (!UserRemovedFromCSEMaps) 11217 continue; 11218 11219 // Now that we have modified User, add it back to the CSE maps. If it 11220 // already exists there, recursively merge the results together. 11221 AddModifiedNodeToCSEMaps(User); 11222 } 11223 11224 // If we just RAUW'd the root, take note. 11225 if (From == getRoot()) 11226 setRoot(To); 11227 } 11228 11229 namespace { 11230 11231 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 11232 /// to record information about a use. 11233 struct UseMemo { 11234 SDNode *User; 11235 unsigned Index; 11236 SDUse *Use; 11237 }; 11238 11239 /// operator< - Sort Memos by User. 11240 bool operator<(const UseMemo &L, const UseMemo &R) { 11241 return (intptr_t)L.User < (intptr_t)R.User; 11242 } 11243 11244 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 11245 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 11246 /// the node already has been taken care of recursively. 11247 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 11248 SmallVector<UseMemo, 4> &Uses; 11249 11250 void NodeDeleted(SDNode *N, SDNode *E) override { 11251 for (UseMemo &Memo : Uses) 11252 if (Memo.User == N) 11253 Memo.User = nullptr; 11254 } 11255 11256 public: 11257 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 11258 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 11259 }; 11260 11261 } // end anonymous namespace 11262 11263 bool SelectionDAG::calculateDivergence(SDNode *N) { 11264 if (TLI->isSDNodeAlwaysUniform(N)) { 11265 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) && 11266 "Conflicting divergence information!"); 11267 return false; 11268 } 11269 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA)) 11270 return true; 11271 for (const auto &Op : N->ops()) { 11272 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 11273 return true; 11274 } 11275 return false; 11276 } 11277 11278 void SelectionDAG::updateDivergence(SDNode *N) { 11279 SmallVector<SDNode *, 16> Worklist(1, N); 11280 do { 11281 N = Worklist.pop_back_val(); 11282 bool IsDivergent = calculateDivergence(N); 11283 if (N->SDNodeBits.IsDivergent != IsDivergent) { 11284 N->SDNodeBits.IsDivergent = IsDivergent; 11285 llvm::append_range(Worklist, N->uses()); 11286 } 11287 } while (!Worklist.empty()); 11288 } 11289 11290 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 11291 DenseMap<SDNode *, unsigned> Degree; 11292 Order.reserve(AllNodes.size()); 11293 for (auto &N : allnodes()) { 11294 unsigned NOps = N.getNumOperands(); 11295 Degree[&N] = NOps; 11296 if (0 == NOps) 11297 Order.push_back(&N); 11298 } 11299 for (size_t I = 0; I != Order.size(); ++I) { 11300 SDNode *N = Order[I]; 11301 for (auto *U : N->uses()) { 11302 unsigned &UnsortedOps = Degree[U]; 11303 if (0 == --UnsortedOps) 11304 Order.push_back(U); 11305 } 11306 } 11307 } 11308 11309 #ifndef NDEBUG 11310 void SelectionDAG::VerifyDAGDivergence() { 11311 std::vector<SDNode *> TopoOrder; 11312 CreateTopologicalOrder(TopoOrder); 11313 for (auto *N : TopoOrder) { 11314 assert(calculateDivergence(N) == N->isDivergent() && 11315 "Divergence bit inconsistency detected"); 11316 } 11317 } 11318 #endif 11319 11320 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 11321 /// uses of other values produced by From.getNode() alone. The same value 11322 /// may appear in both the From and To list. The Deleted vector is 11323 /// handled the same way as for ReplaceAllUsesWith. 11324 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 11325 const SDValue *To, 11326 unsigned Num){ 11327 // Handle the simple, trivial case efficiently. 11328 if (Num == 1) 11329 return ReplaceAllUsesOfValueWith(*From, *To); 11330 11331 transferDbgValues(*From, *To); 11332 copyExtraInfo(From->getNode(), To->getNode()); 11333 11334 // Read up all the uses and make records of them. This helps 11335 // processing new uses that are introduced during the 11336 // replacement process. 11337 SmallVector<UseMemo, 4> Uses; 11338 for (unsigned i = 0; i != Num; ++i) { 11339 unsigned FromResNo = From[i].getResNo(); 11340 SDNode *FromNode = From[i].getNode(); 11341 for (SDNode::use_iterator UI = FromNode->use_begin(), 11342 E = FromNode->use_end(); UI != E; ++UI) { 11343 SDUse &Use = UI.getUse(); 11344 if (Use.getResNo() == FromResNo) { 11345 UseMemo Memo = { *UI, i, &Use }; 11346 Uses.push_back(Memo); 11347 } 11348 } 11349 } 11350 11351 // Sort the uses, so that all the uses from a given User are together. 11352 llvm::sort(Uses); 11353 RAUOVWUpdateListener Listener(*this, Uses); 11354 11355 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 11356 UseIndex != UseIndexEnd; ) { 11357 // We know that this user uses some value of From. If it is the right 11358 // value, update it. 11359 SDNode *User = Uses[UseIndex].User; 11360 // If the node has been deleted by recursive CSE updates when updating 11361 // another node, then just skip this entry. 11362 if (User == nullptr) { 11363 ++UseIndex; 11364 continue; 11365 } 11366 11367 // This node is about to morph, remove its old self from the CSE maps. 11368 RemoveNodeFromCSEMaps(User); 11369 11370 // The Uses array is sorted, so all the uses for a given User 11371 // are next to each other in the list. 11372 // To help reduce the number of CSE recomputations, process all 11373 // the uses of this user that we can find this way. 11374 do { 11375 unsigned i = Uses[UseIndex].Index; 11376 SDUse &Use = *Uses[UseIndex].Use; 11377 ++UseIndex; 11378 11379 Use.set(To[i]); 11380 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 11381 11382 // Now that we have modified User, add it back to the CSE maps. If it 11383 // already exists there, recursively merge the results together. 11384 AddModifiedNodeToCSEMaps(User); 11385 } 11386 } 11387 11388 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 11389 /// based on their topological order. It returns the maximum id and a vector 11390 /// of the SDNodes* in assigned order by reference. 11391 unsigned SelectionDAG::AssignTopologicalOrder() { 11392 unsigned DAGSize = 0; 11393 11394 // SortedPos tracks the progress of the algorithm. Nodes before it are 11395 // sorted, nodes after it are unsorted. When the algorithm completes 11396 // it is at the end of the list. 11397 allnodes_iterator SortedPos = allnodes_begin(); 11398 11399 // Visit all the nodes. Move nodes with no operands to the front of 11400 // the list immediately. Annotate nodes that do have operands with their 11401 // operand count. Before we do this, the Node Id fields of the nodes 11402 // may contain arbitrary values. After, the Node Id fields for nodes 11403 // before SortedPos will contain the topological sort index, and the 11404 // Node Id fields for nodes At SortedPos and after will contain the 11405 // count of outstanding operands. 11406 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 11407 checkForCycles(&N, this); 11408 unsigned Degree = N.getNumOperands(); 11409 if (Degree == 0) { 11410 // A node with no uses, add it to the result array immediately. 11411 N.setNodeId(DAGSize++); 11412 allnodes_iterator Q(&N); 11413 if (Q != SortedPos) 11414 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 11415 assert(SortedPos != AllNodes.end() && "Overran node list"); 11416 ++SortedPos; 11417 } else { 11418 // Temporarily use the Node Id as scratch space for the degree count. 11419 N.setNodeId(Degree); 11420 } 11421 } 11422 11423 // Visit all the nodes. As we iterate, move nodes into sorted order, 11424 // such that by the time the end is reached all nodes will be sorted. 11425 for (SDNode &Node : allnodes()) { 11426 SDNode *N = &Node; 11427 checkForCycles(N, this); 11428 // N is in sorted position, so all its uses have one less operand 11429 // that needs to be sorted. 11430 for (SDNode *P : N->uses()) { 11431 unsigned Degree = P->getNodeId(); 11432 assert(Degree != 0 && "Invalid node degree"); 11433 --Degree; 11434 if (Degree == 0) { 11435 // All of P's operands are sorted, so P may sorted now. 11436 P->setNodeId(DAGSize++); 11437 if (P->getIterator() != SortedPos) 11438 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 11439 assert(SortedPos != AllNodes.end() && "Overran node list"); 11440 ++SortedPos; 11441 } else { 11442 // Update P's outstanding operand count. 11443 P->setNodeId(Degree); 11444 } 11445 } 11446 if (Node.getIterator() == SortedPos) { 11447 #ifndef NDEBUG 11448 allnodes_iterator I(N); 11449 SDNode *S = &*++I; 11450 dbgs() << "Overran sorted position:\n"; 11451 S->dumprFull(this); dbgs() << "\n"; 11452 dbgs() << "Checking if this is due to cycles\n"; 11453 checkForCycles(this, true); 11454 #endif 11455 llvm_unreachable(nullptr); 11456 } 11457 } 11458 11459 assert(SortedPos == AllNodes.end() && 11460 "Topological sort incomplete!"); 11461 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 11462 "First node in topological sort is not the entry token!"); 11463 assert(AllNodes.front().getNodeId() == 0 && 11464 "First node in topological sort has non-zero id!"); 11465 assert(AllNodes.front().getNumOperands() == 0 && 11466 "First node in topological sort has operands!"); 11467 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 11468 "Last node in topologic sort has unexpected id!"); 11469 assert(AllNodes.back().use_empty() && 11470 "Last node in topologic sort has users!"); 11471 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 11472 return DAGSize; 11473 } 11474 11475 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 11476 /// value is produced by SD. 11477 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 11478 for (SDNode *SD : DB->getSDNodes()) { 11479 if (!SD) 11480 continue; 11481 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 11482 SD->setHasDebugValue(true); 11483 } 11484 DbgInfo->add(DB, isParameter); 11485 } 11486 11487 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 11488 11489 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 11490 SDValue NewMemOpChain) { 11491 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 11492 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 11493 // The new memory operation must have the same position as the old load in 11494 // terms of memory dependency. Create a TokenFactor for the old load and new 11495 // memory operation and update uses of the old load's output chain to use that 11496 // TokenFactor. 11497 if (OldChain == NewMemOpChain || OldChain.use_empty()) 11498 return NewMemOpChain; 11499 11500 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 11501 OldChain, NewMemOpChain); 11502 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 11503 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 11504 return TokenFactor; 11505 } 11506 11507 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 11508 SDValue NewMemOp) { 11509 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 11510 SDValue OldChain = SDValue(OldLoad, 1); 11511 SDValue NewMemOpChain = NewMemOp.getValue(1); 11512 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 11513 } 11514 11515 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 11516 Function **OutFunction) { 11517 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 11518 11519 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 11520 auto *Module = MF->getFunction().getParent(); 11521 auto *Function = Module->getFunction(Symbol); 11522 11523 if (OutFunction != nullptr) 11524 *OutFunction = Function; 11525 11526 if (Function != nullptr) { 11527 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 11528 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 11529 } 11530 11531 std::string ErrorStr; 11532 raw_string_ostream ErrorFormatter(ErrorStr); 11533 ErrorFormatter << "Undefined external symbol "; 11534 ErrorFormatter << '"' << Symbol << '"'; 11535 report_fatal_error(Twine(ErrorFormatter.str())); 11536 } 11537 11538 //===----------------------------------------------------------------------===// 11539 // SDNode Class 11540 //===----------------------------------------------------------------------===// 11541 11542 bool llvm::isNullConstant(SDValue V) { 11543 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11544 return Const != nullptr && Const->isZero(); 11545 } 11546 11547 bool llvm::isNullFPConstant(SDValue V) { 11548 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 11549 return Const != nullptr && Const->isZero() && !Const->isNegative(); 11550 } 11551 11552 bool llvm::isAllOnesConstant(SDValue V) { 11553 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11554 return Const != nullptr && Const->isAllOnes(); 11555 } 11556 11557 bool llvm::isOneConstant(SDValue V) { 11558 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11559 return Const != nullptr && Const->isOne(); 11560 } 11561 11562 bool llvm::isMinSignedConstant(SDValue V) { 11563 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11564 return Const != nullptr && Const->isMinSignedValue(); 11565 } 11566 11567 bool llvm::isNeutralConstant(unsigned Opcode, SDNodeFlags Flags, SDValue V, 11568 unsigned OperandNo) { 11569 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity(). 11570 // TODO: Target-specific opcodes could be added. 11571 if (auto *Const = isConstOrConstSplat(V)) { 11572 switch (Opcode) { 11573 case ISD::ADD: 11574 case ISD::OR: 11575 case ISD::XOR: 11576 case ISD::UMAX: 11577 return Const->isZero(); 11578 case ISD::MUL: 11579 return Const->isOne(); 11580 case ISD::AND: 11581 case ISD::UMIN: 11582 return Const->isAllOnes(); 11583 case ISD::SMAX: 11584 return Const->isMinSignedValue(); 11585 case ISD::SMIN: 11586 return Const->isMaxSignedValue(); 11587 case ISD::SUB: 11588 case ISD::SHL: 11589 case ISD::SRA: 11590 case ISD::SRL: 11591 return OperandNo == 1 && Const->isZero(); 11592 case ISD::UDIV: 11593 case ISD::SDIV: 11594 return OperandNo == 1 && Const->isOne(); 11595 } 11596 } else if (auto *ConstFP = isConstOrConstSplatFP(V)) { 11597 switch (Opcode) { 11598 case ISD::FADD: 11599 return ConstFP->isZero() && 11600 (Flags.hasNoSignedZeros() || ConstFP->isNegative()); 11601 case ISD::FSUB: 11602 return OperandNo == 1 && ConstFP->isZero() && 11603 (Flags.hasNoSignedZeros() || !ConstFP->isNegative()); 11604 case ISD::FMUL: 11605 return ConstFP->isExactlyValue(1.0); 11606 case ISD::FDIV: 11607 return OperandNo == 1 && ConstFP->isExactlyValue(1.0); 11608 case ISD::FMINNUM: 11609 case ISD::FMAXNUM: { 11610 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11611 EVT VT = V.getValueType(); 11612 const fltSemantics &Semantics = SelectionDAG::EVTToAPFloatSemantics(VT); 11613 APFloat NeutralAF = !Flags.hasNoNaNs() 11614 ? APFloat::getQNaN(Semantics) 11615 : !Flags.hasNoInfs() 11616 ? APFloat::getInf(Semantics) 11617 : APFloat::getLargest(Semantics); 11618 if (Opcode == ISD::FMAXNUM) 11619 NeutralAF.changeSign(); 11620 11621 return ConstFP->isExactlyValue(NeutralAF); 11622 } 11623 } 11624 } 11625 return false; 11626 } 11627 11628 SDValue llvm::peekThroughBitcasts(SDValue V) { 11629 while (V.getOpcode() == ISD::BITCAST) 11630 V = V.getOperand(0); 11631 return V; 11632 } 11633 11634 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 11635 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 11636 V = V.getOperand(0); 11637 return V; 11638 } 11639 11640 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 11641 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 11642 V = V.getOperand(0); 11643 return V; 11644 } 11645 11646 SDValue llvm::peekThroughTruncates(SDValue V) { 11647 while (V.getOpcode() == ISD::TRUNCATE) 11648 V = V.getOperand(0); 11649 return V; 11650 } 11651 11652 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 11653 if (V.getOpcode() != ISD::XOR) 11654 return false; 11655 V = peekThroughBitcasts(V.getOperand(1)); 11656 unsigned NumBits = V.getScalarValueSizeInBits(); 11657 ConstantSDNode *C = 11658 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 11659 return C && (C->getAPIntValue().countr_one() >= NumBits); 11660 } 11661 11662 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 11663 bool AllowTruncation) { 11664 EVT VT = N.getValueType(); 11665 APInt DemandedElts = VT.isFixedLengthVector() 11666 ? APInt::getAllOnes(VT.getVectorMinNumElements()) 11667 : APInt(1, 1); 11668 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation); 11669 } 11670 11671 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 11672 bool AllowUndefs, 11673 bool AllowTruncation) { 11674 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 11675 return CN; 11676 11677 // SplatVectors can truncate their operands. Ignore that case here unless 11678 // AllowTruncation is set. 11679 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 11680 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 11681 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 11682 EVT CVT = CN->getValueType(0); 11683 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 11684 if (AllowTruncation || CVT == VecEltVT) 11685 return CN; 11686 } 11687 } 11688 11689 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 11690 BitVector UndefElements; 11691 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 11692 11693 // BuildVectors can truncate their operands. Ignore that case here unless 11694 // AllowTruncation is set. 11695 // TODO: Look into whether we should allow UndefElements in non-DemandedElts 11696 if (CN && (UndefElements.none() || AllowUndefs)) { 11697 EVT CVT = CN->getValueType(0); 11698 EVT NSVT = N.getValueType().getScalarType(); 11699 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 11700 if (AllowTruncation || (CVT == NSVT)) 11701 return CN; 11702 } 11703 } 11704 11705 return nullptr; 11706 } 11707 11708 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 11709 EVT VT = N.getValueType(); 11710 APInt DemandedElts = VT.isFixedLengthVector() 11711 ? APInt::getAllOnes(VT.getVectorMinNumElements()) 11712 : APInt(1, 1); 11713 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs); 11714 } 11715 11716 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 11717 const APInt &DemandedElts, 11718 bool AllowUndefs) { 11719 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 11720 return CN; 11721 11722 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 11723 BitVector UndefElements; 11724 ConstantFPSDNode *CN = 11725 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 11726 // TODO: Look into whether we should allow UndefElements in non-DemandedElts 11727 if (CN && (UndefElements.none() || AllowUndefs)) 11728 return CN; 11729 } 11730 11731 if (N.getOpcode() == ISD::SPLAT_VECTOR) 11732 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 11733 return CN; 11734 11735 return nullptr; 11736 } 11737 11738 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 11739 // TODO: may want to use peekThroughBitcast() here. 11740 ConstantSDNode *C = 11741 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 11742 return C && C->isZero(); 11743 } 11744 11745 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 11746 ConstantSDNode *C = 11747 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true); 11748 return C && C->isOne(); 11749 } 11750 11751 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 11752 N = peekThroughBitcasts(N); 11753 unsigned BitWidth = N.getScalarValueSizeInBits(); 11754 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 11755 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 11756 } 11757 11758 HandleSDNode::~HandleSDNode() { 11759 DropOperands(); 11760 } 11761 11762 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 11763 const DebugLoc &DL, 11764 const GlobalValue *GA, EVT VT, 11765 int64_t o, unsigned TF) 11766 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 11767 TheGlobal = GA; 11768 } 11769 11770 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 11771 EVT VT, unsigned SrcAS, 11772 unsigned DestAS) 11773 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 11774 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 11775 11776 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 11777 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 11778 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 11779 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 11780 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 11781 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 11782 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 11783 11784 // We check here that the size of the memory operand fits within the size of 11785 // the MMO. This is because the MMO might indicate only a possible address 11786 // range instead of specifying the affected memory addresses precisely. 11787 // TODO: Make MachineMemOperands aware of scalable vectors. 11788 assert(memvt.getStoreSize().getKnownMinValue() <= MMO->getSize() && 11789 "Size mismatch!"); 11790 } 11791 11792 /// Profile - Gather unique data for the node. 11793 /// 11794 void SDNode::Profile(FoldingSetNodeID &ID) const { 11795 AddNodeIDNode(ID, this); 11796 } 11797 11798 namespace { 11799 11800 struct EVTArray { 11801 std::vector<EVT> VTs; 11802 11803 EVTArray() { 11804 VTs.reserve(MVT::VALUETYPE_SIZE); 11805 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 11806 VTs.push_back(MVT((MVT::SimpleValueType)i)); 11807 } 11808 }; 11809 11810 } // end anonymous namespace 11811 11812 /// getValueTypeList - Return a pointer to the specified value type. 11813 /// 11814 const EVT *SDNode::getValueTypeList(EVT VT) { 11815 static std::set<EVT, EVT::compareRawBits> EVTs; 11816 static EVTArray SimpleVTArray; 11817 static sys::SmartMutex<true> VTMutex; 11818 11819 if (VT.isExtended()) { 11820 sys::SmartScopedLock<true> Lock(VTMutex); 11821 return &(*EVTs.insert(VT).first); 11822 } 11823 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 11824 return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy]; 11825 } 11826 11827 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 11828 /// indicated value. This method ignores uses of other values defined by this 11829 /// operation. 11830 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 11831 assert(Value < getNumValues() && "Bad value!"); 11832 11833 // TODO: Only iterate over uses of a given value of the node 11834 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 11835 if (UI.getUse().getResNo() == Value) { 11836 if (NUses == 0) 11837 return false; 11838 --NUses; 11839 } 11840 } 11841 11842 // Found exactly the right number of uses? 11843 return NUses == 0; 11844 } 11845 11846 /// hasAnyUseOfValue - Return true if there are any use of the indicated 11847 /// value. This method ignores uses of other values defined by this operation. 11848 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 11849 assert(Value < getNumValues() && "Bad value!"); 11850 11851 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 11852 if (UI.getUse().getResNo() == Value) 11853 return true; 11854 11855 return false; 11856 } 11857 11858 /// isOnlyUserOf - Return true if this node is the only use of N. 11859 bool SDNode::isOnlyUserOf(const SDNode *N) const { 11860 bool Seen = false; 11861 for (const SDNode *User : N->uses()) { 11862 if (User == this) 11863 Seen = true; 11864 else 11865 return false; 11866 } 11867 11868 return Seen; 11869 } 11870 11871 /// Return true if the only users of N are contained in Nodes. 11872 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 11873 bool Seen = false; 11874 for (const SDNode *User : N->uses()) { 11875 if (llvm::is_contained(Nodes, User)) 11876 Seen = true; 11877 else 11878 return false; 11879 } 11880 11881 return Seen; 11882 } 11883 11884 /// isOperand - Return true if this node is an operand of N. 11885 bool SDValue::isOperandOf(const SDNode *N) const { 11886 return is_contained(N->op_values(), *this); 11887 } 11888 11889 bool SDNode::isOperandOf(const SDNode *N) const { 11890 return any_of(N->op_values(), 11891 [this](SDValue Op) { return this == Op.getNode(); }); 11892 } 11893 11894 /// reachesChainWithoutSideEffects - Return true if this operand (which must 11895 /// be a chain) reaches the specified operand without crossing any 11896 /// side-effecting instructions on any chain path. In practice, this looks 11897 /// through token factors and non-volatile loads. In order to remain efficient, 11898 /// this only looks a couple of nodes in, it does not do an exhaustive search. 11899 /// 11900 /// Note that we only need to examine chains when we're searching for 11901 /// side-effects; SelectionDAG requires that all side-effects are represented 11902 /// by chains, even if another operand would force a specific ordering. This 11903 /// constraint is necessary to allow transformations like splitting loads. 11904 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 11905 unsigned Depth) const { 11906 if (*this == Dest) return true; 11907 11908 // Don't search too deeply, we just want to be able to see through 11909 // TokenFactor's etc. 11910 if (Depth == 0) return false; 11911 11912 // If this is a token factor, all inputs to the TF happen in parallel. 11913 if (getOpcode() == ISD::TokenFactor) { 11914 // First, try a shallow search. 11915 if (is_contained((*this)->ops(), Dest)) { 11916 // We found the chain we want as an operand of this TokenFactor. 11917 // Essentially, we reach the chain without side-effects if we could 11918 // serialize the TokenFactor into a simple chain of operations with 11919 // Dest as the last operation. This is automatically true if the 11920 // chain has one use: there are no other ordering constraints. 11921 // If the chain has more than one use, we give up: some other 11922 // use of Dest might force a side-effect between Dest and the current 11923 // node. 11924 if (Dest.hasOneUse()) 11925 return true; 11926 } 11927 // Next, try a deep search: check whether every operand of the TokenFactor 11928 // reaches Dest. 11929 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 11930 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 11931 }); 11932 } 11933 11934 // Loads don't have side effects, look through them. 11935 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 11936 if (Ld->isUnordered()) 11937 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 11938 } 11939 return false; 11940 } 11941 11942 bool SDNode::hasPredecessor(const SDNode *N) const { 11943 SmallPtrSet<const SDNode *, 32> Visited; 11944 SmallVector<const SDNode *, 16> Worklist; 11945 Worklist.push_back(this); 11946 return hasPredecessorHelper(N, Visited, Worklist); 11947 } 11948 11949 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 11950 this->Flags.intersectWith(Flags); 11951 } 11952 11953 SDValue 11954 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 11955 ArrayRef<ISD::NodeType> CandidateBinOps, 11956 bool AllowPartials) { 11957 // The pattern must end in an extract from index 0. 11958 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11959 !isNullConstant(Extract->getOperand(1))) 11960 return SDValue(); 11961 11962 // Match against one of the candidate binary ops. 11963 SDValue Op = Extract->getOperand(0); 11964 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 11965 return Op.getOpcode() == unsigned(BinOp); 11966 })) 11967 return SDValue(); 11968 11969 // Floating-point reductions may require relaxed constraints on the final step 11970 // of the reduction because they may reorder intermediate operations. 11971 unsigned CandidateBinOp = Op.getOpcode(); 11972 if (Op.getValueType().isFloatingPoint()) { 11973 SDNodeFlags Flags = Op->getFlags(); 11974 switch (CandidateBinOp) { 11975 case ISD::FADD: 11976 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 11977 return SDValue(); 11978 break; 11979 default: 11980 llvm_unreachable("Unhandled FP opcode for binop reduction"); 11981 } 11982 } 11983 11984 // Matching failed - attempt to see if we did enough stages that a partial 11985 // reduction from a subvector is possible. 11986 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 11987 if (!AllowPartials || !Op) 11988 return SDValue(); 11989 EVT OpVT = Op.getValueType(); 11990 EVT OpSVT = OpVT.getScalarType(); 11991 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 11992 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 11993 return SDValue(); 11994 BinOp = (ISD::NodeType)CandidateBinOp; 11995 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 11996 getVectorIdxConstant(0, SDLoc(Op))); 11997 }; 11998 11999 // At each stage, we're looking for something that looks like: 12000 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 12001 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 12002 // i32 undef, i32 undef, i32 undef, i32 undef> 12003 // %a = binop <8 x i32> %op, %s 12004 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 12005 // we expect something like: 12006 // <4,5,6,7,u,u,u,u> 12007 // <2,3,u,u,u,u,u,u> 12008 // <1,u,u,u,u,u,u,u> 12009 // While a partial reduction match would be: 12010 // <2,3,u,u,u,u,u,u> 12011 // <1,u,u,u,u,u,u,u> 12012 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 12013 SDValue PrevOp; 12014 for (unsigned i = 0; i < Stages; ++i) { 12015 unsigned MaskEnd = (1 << i); 12016 12017 if (Op.getOpcode() != CandidateBinOp) 12018 return PartialReduction(PrevOp, MaskEnd); 12019 12020 SDValue Op0 = Op.getOperand(0); 12021 SDValue Op1 = Op.getOperand(1); 12022 12023 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 12024 if (Shuffle) { 12025 Op = Op1; 12026 } else { 12027 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 12028 Op = Op0; 12029 } 12030 12031 // The first operand of the shuffle should be the same as the other operand 12032 // of the binop. 12033 if (!Shuffle || Shuffle->getOperand(0) != Op) 12034 return PartialReduction(PrevOp, MaskEnd); 12035 12036 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 12037 for (int Index = 0; Index < (int)MaskEnd; ++Index) 12038 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 12039 return PartialReduction(PrevOp, MaskEnd); 12040 12041 PrevOp = Op; 12042 } 12043 12044 // Handle subvector reductions, which tend to appear after the shuffle 12045 // reduction stages. 12046 while (Op.getOpcode() == CandidateBinOp) { 12047 unsigned NumElts = Op.getValueType().getVectorNumElements(); 12048 SDValue Op0 = Op.getOperand(0); 12049 SDValue Op1 = Op.getOperand(1); 12050 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 12051 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 12052 Op0.getOperand(0) != Op1.getOperand(0)) 12053 break; 12054 SDValue Src = Op0.getOperand(0); 12055 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 12056 if (NumSrcElts != (2 * NumElts)) 12057 break; 12058 if (!(Op0.getConstantOperandAPInt(1) == 0 && 12059 Op1.getConstantOperandAPInt(1) == NumElts) && 12060 !(Op1.getConstantOperandAPInt(1) == 0 && 12061 Op0.getConstantOperandAPInt(1) == NumElts)) 12062 break; 12063 Op = Src; 12064 } 12065 12066 BinOp = (ISD::NodeType)CandidateBinOp; 12067 return Op; 12068 } 12069 12070 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 12071 EVT VT = N->getValueType(0); 12072 EVT EltVT = VT.getVectorElementType(); 12073 unsigned NE = VT.getVectorNumElements(); 12074 12075 SDLoc dl(N); 12076 12077 // If ResNE is 0, fully unroll the vector op. 12078 if (ResNE == 0) 12079 ResNE = NE; 12080 else if (NE > ResNE) 12081 NE = ResNE; 12082 12083 if (N->getNumValues() == 2) { 12084 SmallVector<SDValue, 8> Scalars0, Scalars1; 12085 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 12086 EVT VT1 = N->getValueType(1); 12087 EVT EltVT1 = VT1.getVectorElementType(); 12088 12089 unsigned i; 12090 for (i = 0; i != NE; ++i) { 12091 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 12092 SDValue Operand = N->getOperand(j); 12093 EVT OperandVT = Operand.getValueType(); 12094 12095 // A vector operand; extract a single element. 12096 EVT OperandEltVT = OperandVT.getVectorElementType(); 12097 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 12098 Operand, getVectorIdxConstant(i, dl)); 12099 } 12100 12101 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands); 12102 Scalars0.push_back(EltOp); 12103 Scalars1.push_back(EltOp.getValue(1)); 12104 } 12105 12106 SDValue Vec0 = getBuildVector(VT, dl, Scalars0); 12107 SDValue Vec1 = getBuildVector(VT1, dl, Scalars1); 12108 return getMergeValues({Vec0, Vec1}, dl); 12109 } 12110 12111 assert(N->getNumValues() == 1 && 12112 "Can't unroll a vector with multiple results!"); 12113 12114 SmallVector<SDValue, 8> Scalars; 12115 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 12116 12117 unsigned i; 12118 for (i= 0; i != NE; ++i) { 12119 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 12120 SDValue Operand = N->getOperand(j); 12121 EVT OperandVT = Operand.getValueType(); 12122 if (OperandVT.isVector()) { 12123 // A vector operand; extract a single element. 12124 EVT OperandEltVT = OperandVT.getVectorElementType(); 12125 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 12126 Operand, getVectorIdxConstant(i, dl)); 12127 } else { 12128 // A scalar operand; just use it as is. 12129 Operands[j] = Operand; 12130 } 12131 } 12132 12133 switch (N->getOpcode()) { 12134 default: { 12135 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 12136 N->getFlags())); 12137 break; 12138 } 12139 case ISD::VSELECT: 12140 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 12141 break; 12142 case ISD::SHL: 12143 case ISD::SRA: 12144 case ISD::SRL: 12145 case ISD::ROTL: 12146 case ISD::ROTR: 12147 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 12148 getShiftAmountOperand(Operands[0].getValueType(), 12149 Operands[1]))); 12150 break; 12151 case ISD::SIGN_EXTEND_INREG: { 12152 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 12153 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 12154 Operands[0], 12155 getValueType(ExtVT))); 12156 } 12157 } 12158 } 12159 12160 for (; i < ResNE; ++i) 12161 Scalars.push_back(getUNDEF(EltVT)); 12162 12163 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 12164 return getBuildVector(VecVT, dl, Scalars); 12165 } 12166 12167 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 12168 SDNode *N, unsigned ResNE) { 12169 unsigned Opcode = N->getOpcode(); 12170 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 12171 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 12172 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 12173 "Expected an overflow opcode"); 12174 12175 EVT ResVT = N->getValueType(0); 12176 EVT OvVT = N->getValueType(1); 12177 EVT ResEltVT = ResVT.getVectorElementType(); 12178 EVT OvEltVT = OvVT.getVectorElementType(); 12179 SDLoc dl(N); 12180 12181 // If ResNE is 0, fully unroll the vector op. 12182 unsigned NE = ResVT.getVectorNumElements(); 12183 if (ResNE == 0) 12184 ResNE = NE; 12185 else if (NE > ResNE) 12186 NE = ResNE; 12187 12188 SmallVector<SDValue, 8> LHSScalars; 12189 SmallVector<SDValue, 8> RHSScalars; 12190 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 12191 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 12192 12193 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 12194 SDVTList VTs = getVTList(ResEltVT, SVT); 12195 SmallVector<SDValue, 8> ResScalars; 12196 SmallVector<SDValue, 8> OvScalars; 12197 for (unsigned i = 0; i < NE; ++i) { 12198 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 12199 SDValue Ov = 12200 getSelect(dl, OvEltVT, Res.getValue(1), 12201 getBoolConstant(true, dl, OvEltVT, ResVT), 12202 getConstant(0, dl, OvEltVT)); 12203 12204 ResScalars.push_back(Res); 12205 OvScalars.push_back(Ov); 12206 } 12207 12208 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 12209 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 12210 12211 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 12212 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 12213 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 12214 getBuildVector(NewOvVT, dl, OvScalars)); 12215 } 12216 12217 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 12218 LoadSDNode *Base, 12219 unsigned Bytes, 12220 int Dist) const { 12221 if (LD->isVolatile() || Base->isVolatile()) 12222 return false; 12223 // TODO: probably too restrictive for atomics, revisit 12224 if (!LD->isSimple()) 12225 return false; 12226 if (LD->isIndexed() || Base->isIndexed()) 12227 return false; 12228 if (LD->getChain() != Base->getChain()) 12229 return false; 12230 EVT VT = LD->getMemoryVT(); 12231 if (VT.getSizeInBits() / 8 != Bytes) 12232 return false; 12233 12234 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 12235 auto LocDecomp = BaseIndexOffset::match(LD, *this); 12236 12237 int64_t Offset = 0; 12238 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 12239 return (Dist * (int64_t)Bytes == Offset); 12240 return false; 12241 } 12242 12243 /// InferPtrAlignment - Infer alignment of a load / store address. Return 12244 /// std::nullopt if it cannot be inferred. 12245 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 12246 // If this is a GlobalAddress + cst, return the alignment. 12247 const GlobalValue *GV = nullptr; 12248 int64_t GVOffset = 0; 12249 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 12250 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 12251 KnownBits Known(PtrWidth); 12252 llvm::computeKnownBits(GV, Known, getDataLayout()); 12253 unsigned AlignBits = Known.countMinTrailingZeros(); 12254 if (AlignBits) 12255 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 12256 } 12257 12258 // If this is a direct reference to a stack slot, use information about the 12259 // stack slot's alignment. 12260 int FrameIdx = INT_MIN; 12261 int64_t FrameOffset = 0; 12262 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 12263 FrameIdx = FI->getIndex(); 12264 } else if (isBaseWithConstantOffset(Ptr) && 12265 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 12266 // Handle FI+Cst 12267 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 12268 FrameOffset = Ptr.getConstantOperandVal(1); 12269 } 12270 12271 if (FrameIdx != INT_MIN) { 12272 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 12273 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 12274 } 12275 12276 return std::nullopt; 12277 } 12278 12279 /// Split the scalar node with EXTRACT_ELEMENT using the provided 12280 /// VTs and return the low/high part. 12281 std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N, 12282 const SDLoc &DL, 12283 const EVT &LoVT, 12284 const EVT &HiVT) { 12285 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() && 12286 "Split node must be a scalar type"); 12287 SDValue Lo = 12288 getNode(ISD::EXTRACT_ELEMENT, DL, LoVT, N, getIntPtrConstant(0, DL)); 12289 SDValue Hi = 12290 getNode(ISD::EXTRACT_ELEMENT, DL, HiVT, N, getIntPtrConstant(1, DL)); 12291 return std::make_pair(Lo, Hi); 12292 } 12293 12294 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 12295 /// which is split (or expanded) into two not necessarily identical pieces. 12296 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 12297 // Currently all types are split in half. 12298 EVT LoVT, HiVT; 12299 if (!VT.isVector()) 12300 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 12301 else 12302 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 12303 12304 return std::make_pair(LoVT, HiVT); 12305 } 12306 12307 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 12308 /// type, dependent on an enveloping VT that has been split into two identical 12309 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 12310 std::pair<EVT, EVT> 12311 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 12312 bool *HiIsEmpty) const { 12313 EVT EltTp = VT.getVectorElementType(); 12314 // Examples: 12315 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 12316 // custom VL=9 with enveloping VL=8/8 yields 8/1 12317 // custom VL=10 with enveloping VL=8/8 yields 8/2 12318 // etc. 12319 ElementCount VTNumElts = VT.getVectorElementCount(); 12320 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 12321 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 12322 "Mixing fixed width and scalable vectors when enveloping a type"); 12323 EVT LoVT, HiVT; 12324 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 12325 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 12326 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 12327 *HiIsEmpty = false; 12328 } else { 12329 // Flag that hi type has zero storage size, but return split envelop type 12330 // (this would be easier if vector types with zero elements were allowed). 12331 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 12332 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 12333 *HiIsEmpty = true; 12334 } 12335 return std::make_pair(LoVT, HiVT); 12336 } 12337 12338 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 12339 /// low/high part. 12340 std::pair<SDValue, SDValue> 12341 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 12342 const EVT &HiVT) { 12343 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 12344 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 12345 "Splitting vector with an invalid mixture of fixed and scalable " 12346 "vector types"); 12347 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 12348 N.getValueType().getVectorMinNumElements() && 12349 "More vector elements requested than available!"); 12350 SDValue Lo, Hi; 12351 Lo = 12352 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 12353 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 12354 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 12355 // IDX with the runtime scaling factor of the result vector type. For 12356 // fixed-width result vectors, that runtime scaling factor is 1. 12357 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 12358 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 12359 return std::make_pair(Lo, Hi); 12360 } 12361 12362 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 12363 const SDLoc &DL) { 12364 // Split the vector length parameter. 12365 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 12366 EVT VT = N.getValueType(); 12367 assert(VecVT.getVectorElementCount().isKnownEven() && 12368 "Expecting the mask to be an evenly-sized vector"); 12369 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 12370 SDValue HalfNumElts = 12371 VecVT.isFixedLengthVector() 12372 ? getConstant(HalfMinNumElts, DL, VT) 12373 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 12374 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 12375 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 12376 return std::make_pair(Lo, Hi); 12377 } 12378 12379 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 12380 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 12381 EVT VT = N.getValueType(); 12382 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 12383 NextPowerOf2(VT.getVectorNumElements())); 12384 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 12385 getVectorIdxConstant(0, DL)); 12386 } 12387 12388 void SelectionDAG::ExtractVectorElements(SDValue Op, 12389 SmallVectorImpl<SDValue> &Args, 12390 unsigned Start, unsigned Count, 12391 EVT EltVT) { 12392 EVT VT = Op.getValueType(); 12393 if (Count == 0) 12394 Count = VT.getVectorNumElements(); 12395 if (EltVT == EVT()) 12396 EltVT = VT.getVectorElementType(); 12397 SDLoc SL(Op); 12398 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 12399 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 12400 getVectorIdxConstant(i, SL))); 12401 } 12402 } 12403 12404 // getAddressSpace - Return the address space this GlobalAddress belongs to. 12405 unsigned GlobalAddressSDNode::getAddressSpace() const { 12406 return getGlobal()->getType()->getAddressSpace(); 12407 } 12408 12409 Type *ConstantPoolSDNode::getType() const { 12410 if (isMachineConstantPoolEntry()) 12411 return Val.MachineCPVal->getType(); 12412 return Val.ConstVal->getType(); 12413 } 12414 12415 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 12416 unsigned &SplatBitSize, 12417 bool &HasAnyUndefs, 12418 unsigned MinSplatBits, 12419 bool IsBigEndian) const { 12420 EVT VT = getValueType(0); 12421 assert(VT.isVector() && "Expected a vector type"); 12422 unsigned VecWidth = VT.getSizeInBits(); 12423 if (MinSplatBits > VecWidth) 12424 return false; 12425 12426 // FIXME: The widths are based on this node's type, but build vectors can 12427 // truncate their operands. 12428 SplatValue = APInt(VecWidth, 0); 12429 SplatUndef = APInt(VecWidth, 0); 12430 12431 // Get the bits. Bits with undefined values (when the corresponding element 12432 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 12433 // in SplatValue. If any of the values are not constant, give up and return 12434 // false. 12435 unsigned int NumOps = getNumOperands(); 12436 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 12437 unsigned EltWidth = VT.getScalarSizeInBits(); 12438 12439 for (unsigned j = 0; j < NumOps; ++j) { 12440 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 12441 SDValue OpVal = getOperand(i); 12442 unsigned BitPos = j * EltWidth; 12443 12444 if (OpVal.isUndef()) 12445 SplatUndef.setBits(BitPos, BitPos + EltWidth); 12446 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 12447 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 12448 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 12449 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 12450 else 12451 return false; 12452 } 12453 12454 // The build_vector is all constants or undefs. Find the smallest element 12455 // size that splats the vector. 12456 HasAnyUndefs = (SplatUndef != 0); 12457 12458 // FIXME: This does not work for vectors with elements less than 8 bits. 12459 while (VecWidth > 8) { 12460 // If we can't split in half, stop here. 12461 if (VecWidth & 1) 12462 break; 12463 12464 unsigned HalfSize = VecWidth / 2; 12465 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 12466 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 12467 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 12468 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 12469 12470 // If the two halves do not match (ignoring undef bits), stop here. 12471 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 12472 MinSplatBits > HalfSize) 12473 break; 12474 12475 SplatValue = HighValue | LowValue; 12476 SplatUndef = HighUndef & LowUndef; 12477 12478 VecWidth = HalfSize; 12479 } 12480 12481 // FIXME: The loop above only tries to split in halves. But if the input 12482 // vector for example is <3 x i16> it wouldn't be able to detect a 12483 // SplatBitSize of 16. No idea if that is a design flaw currently limiting 12484 // optimizations. I guess that back in the days when this helper was created 12485 // vectors normally was power-of-2 sized. 12486 12487 SplatBitSize = VecWidth; 12488 return true; 12489 } 12490 12491 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 12492 BitVector *UndefElements) const { 12493 unsigned NumOps = getNumOperands(); 12494 if (UndefElements) { 12495 UndefElements->clear(); 12496 UndefElements->resize(NumOps); 12497 } 12498 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 12499 if (!DemandedElts) 12500 return SDValue(); 12501 SDValue Splatted; 12502 for (unsigned i = 0; i != NumOps; ++i) { 12503 if (!DemandedElts[i]) 12504 continue; 12505 SDValue Op = getOperand(i); 12506 if (Op.isUndef()) { 12507 if (UndefElements) 12508 (*UndefElements)[i] = true; 12509 } else if (!Splatted) { 12510 Splatted = Op; 12511 } else if (Splatted != Op) { 12512 return SDValue(); 12513 } 12514 } 12515 12516 if (!Splatted) { 12517 unsigned FirstDemandedIdx = DemandedElts.countr_zero(); 12518 assert(getOperand(FirstDemandedIdx).isUndef() && 12519 "Can only have a splat without a constant for all undefs."); 12520 return getOperand(FirstDemandedIdx); 12521 } 12522 12523 return Splatted; 12524 } 12525 12526 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 12527 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 12528 return getSplatValue(DemandedElts, UndefElements); 12529 } 12530 12531 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 12532 SmallVectorImpl<SDValue> &Sequence, 12533 BitVector *UndefElements) const { 12534 unsigned NumOps = getNumOperands(); 12535 Sequence.clear(); 12536 if (UndefElements) { 12537 UndefElements->clear(); 12538 UndefElements->resize(NumOps); 12539 } 12540 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 12541 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 12542 return false; 12543 12544 // Set the undefs even if we don't find a sequence (like getSplatValue). 12545 if (UndefElements) 12546 for (unsigned I = 0; I != NumOps; ++I) 12547 if (DemandedElts[I] && getOperand(I).isUndef()) 12548 (*UndefElements)[I] = true; 12549 12550 // Iteratively widen the sequence length looking for repetitions. 12551 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 12552 Sequence.append(SeqLen, SDValue()); 12553 for (unsigned I = 0; I != NumOps; ++I) { 12554 if (!DemandedElts[I]) 12555 continue; 12556 SDValue &SeqOp = Sequence[I % SeqLen]; 12557 SDValue Op = getOperand(I); 12558 if (Op.isUndef()) { 12559 if (!SeqOp) 12560 SeqOp = Op; 12561 continue; 12562 } 12563 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 12564 Sequence.clear(); 12565 break; 12566 } 12567 SeqOp = Op; 12568 } 12569 if (!Sequence.empty()) 12570 return true; 12571 } 12572 12573 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 12574 return false; 12575 } 12576 12577 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 12578 BitVector *UndefElements) const { 12579 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 12580 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 12581 } 12582 12583 ConstantSDNode * 12584 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 12585 BitVector *UndefElements) const { 12586 return dyn_cast_or_null<ConstantSDNode>( 12587 getSplatValue(DemandedElts, UndefElements)); 12588 } 12589 12590 ConstantSDNode * 12591 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 12592 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 12593 } 12594 12595 ConstantFPSDNode * 12596 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 12597 BitVector *UndefElements) const { 12598 return dyn_cast_or_null<ConstantFPSDNode>( 12599 getSplatValue(DemandedElts, UndefElements)); 12600 } 12601 12602 ConstantFPSDNode * 12603 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 12604 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 12605 } 12606 12607 int32_t 12608 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 12609 uint32_t BitWidth) const { 12610 if (ConstantFPSDNode *CN = 12611 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 12612 bool IsExact; 12613 APSInt IntVal(BitWidth); 12614 const APFloat &APF = CN->getValueAPF(); 12615 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 12616 APFloat::opOK || 12617 !IsExact) 12618 return -1; 12619 12620 return IntVal.exactLogBase2(); 12621 } 12622 return -1; 12623 } 12624 12625 bool BuildVectorSDNode::getConstantRawBits( 12626 bool IsLittleEndian, unsigned DstEltSizeInBits, 12627 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 12628 // Early-out if this contains anything but Undef/Constant/ConstantFP. 12629 if (!isConstant()) 12630 return false; 12631 12632 unsigned NumSrcOps = getNumOperands(); 12633 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 12634 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 12635 "Invalid bitcast scale"); 12636 12637 // Extract raw src bits. 12638 SmallVector<APInt> SrcBitElements(NumSrcOps, 12639 APInt::getZero(SrcEltSizeInBits)); 12640 BitVector SrcUndeElements(NumSrcOps, false); 12641 12642 for (unsigned I = 0; I != NumSrcOps; ++I) { 12643 SDValue Op = getOperand(I); 12644 if (Op.isUndef()) { 12645 SrcUndeElements.set(I); 12646 continue; 12647 } 12648 auto *CInt = dyn_cast<ConstantSDNode>(Op); 12649 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 12650 assert((CInt || CFP) && "Unknown constant"); 12651 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits) 12652 : CFP->getValueAPF().bitcastToAPInt(); 12653 } 12654 12655 // Recast to dst width. 12656 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 12657 SrcBitElements, UndefElements, SrcUndeElements); 12658 return true; 12659 } 12660 12661 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 12662 unsigned DstEltSizeInBits, 12663 SmallVectorImpl<APInt> &DstBitElements, 12664 ArrayRef<APInt> SrcBitElements, 12665 BitVector &DstUndefElements, 12666 const BitVector &SrcUndefElements) { 12667 unsigned NumSrcOps = SrcBitElements.size(); 12668 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 12669 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 12670 "Invalid bitcast scale"); 12671 assert(NumSrcOps == SrcUndefElements.size() && 12672 "Vector size mismatch"); 12673 12674 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 12675 DstUndefElements.clear(); 12676 DstUndefElements.resize(NumDstOps, false); 12677 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits)); 12678 12679 // Concatenate src elements constant bits together into dst element. 12680 if (SrcEltSizeInBits <= DstEltSizeInBits) { 12681 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 12682 for (unsigned I = 0; I != NumDstOps; ++I) { 12683 DstUndefElements.set(I); 12684 APInt &DstBits = DstBitElements[I]; 12685 for (unsigned J = 0; J != Scale; ++J) { 12686 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 12687 if (SrcUndefElements[Idx]) 12688 continue; 12689 DstUndefElements.reset(I); 12690 const APInt &SrcBits = SrcBitElements[Idx]; 12691 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 12692 "Illegal constant bitwidths"); 12693 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 12694 } 12695 } 12696 return; 12697 } 12698 12699 // Split src element constant bits into dst elements. 12700 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 12701 for (unsigned I = 0; I != NumSrcOps; ++I) { 12702 if (SrcUndefElements[I]) { 12703 DstUndefElements.set(I * Scale, (I + 1) * Scale); 12704 continue; 12705 } 12706 const APInt &SrcBits = SrcBitElements[I]; 12707 for (unsigned J = 0; J != Scale; ++J) { 12708 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 12709 APInt &DstBits = DstBitElements[Idx]; 12710 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 12711 } 12712 } 12713 } 12714 12715 bool BuildVectorSDNode::isConstant() const { 12716 for (const SDValue &Op : op_values()) { 12717 unsigned Opc = Op.getOpcode(); 12718 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 12719 return false; 12720 } 12721 return true; 12722 } 12723 12724 std::optional<std::pair<APInt, APInt>> 12725 BuildVectorSDNode::isConstantSequence() const { 12726 unsigned NumOps = getNumOperands(); 12727 if (NumOps < 2) 12728 return std::nullopt; 12729 12730 if (!isa<ConstantSDNode>(getOperand(0)) || 12731 !isa<ConstantSDNode>(getOperand(1))) 12732 return std::nullopt; 12733 12734 unsigned EltSize = getValueType(0).getScalarSizeInBits(); 12735 APInt Start = getConstantOperandAPInt(0).trunc(EltSize); 12736 APInt Stride = getConstantOperandAPInt(1).trunc(EltSize) - Start; 12737 12738 if (Stride.isZero()) 12739 return std::nullopt; 12740 12741 for (unsigned i = 2; i < NumOps; ++i) { 12742 if (!isa<ConstantSDNode>(getOperand(i))) 12743 return std::nullopt; 12744 12745 APInt Val = getConstantOperandAPInt(i).trunc(EltSize); 12746 if (Val != (Start + (Stride * i))) 12747 return std::nullopt; 12748 } 12749 12750 return std::make_pair(Start, Stride); 12751 } 12752 12753 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 12754 // Find the first non-undef value in the shuffle mask. 12755 unsigned i, e; 12756 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 12757 /* search */; 12758 12759 // If all elements are undefined, this shuffle can be considered a splat 12760 // (although it should eventually get simplified away completely). 12761 if (i == e) 12762 return true; 12763 12764 // Make sure all remaining elements are either undef or the same as the first 12765 // non-undef value. 12766 for (int Idx = Mask[i]; i != e; ++i) 12767 if (Mask[i] >= 0 && Mask[i] != Idx) 12768 return false; 12769 return true; 12770 } 12771 12772 // Returns the SDNode if it is a constant integer BuildVector 12773 // or constant integer. 12774 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 12775 if (isa<ConstantSDNode>(N)) 12776 return N.getNode(); 12777 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 12778 return N.getNode(); 12779 // Treat a GlobalAddress supporting constant offset folding as a 12780 // constant integer. 12781 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 12782 if (GA->getOpcode() == ISD::GlobalAddress && 12783 TLI->isOffsetFoldingLegal(GA)) 12784 return GA; 12785 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 12786 isa<ConstantSDNode>(N.getOperand(0))) 12787 return N.getNode(); 12788 return nullptr; 12789 } 12790 12791 // Returns the SDNode if it is a constant float BuildVector 12792 // or constant float. 12793 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 12794 if (isa<ConstantFPSDNode>(N)) 12795 return N.getNode(); 12796 12797 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 12798 return N.getNode(); 12799 12800 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 12801 isa<ConstantFPSDNode>(N.getOperand(0))) 12802 return N.getNode(); 12803 12804 return nullptr; 12805 } 12806 12807 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 12808 assert(!Node->OperandList && "Node already has operands"); 12809 assert(SDNode::getMaxNumOperands() >= Vals.size() && 12810 "too many operands to fit into SDNode"); 12811 SDUse *Ops = OperandRecycler.allocate( 12812 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 12813 12814 bool IsDivergent = false; 12815 for (unsigned I = 0; I != Vals.size(); ++I) { 12816 Ops[I].setUser(Node); 12817 Ops[I].setInitial(Vals[I]); 12818 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 12819 IsDivergent |= Ops[I].getNode()->isDivergent(); 12820 } 12821 Node->NumOperands = Vals.size(); 12822 Node->OperandList = Ops; 12823 if (!TLI->isSDNodeAlwaysUniform(Node)) { 12824 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA); 12825 Node->SDNodeBits.IsDivergent = IsDivergent; 12826 } 12827 checkForCycles(Node); 12828 } 12829 12830 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 12831 SmallVectorImpl<SDValue> &Vals) { 12832 size_t Limit = SDNode::getMaxNumOperands(); 12833 while (Vals.size() > Limit) { 12834 unsigned SliceIdx = Vals.size() - Limit; 12835 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 12836 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 12837 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 12838 Vals.emplace_back(NewTF); 12839 } 12840 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 12841 } 12842 12843 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 12844 EVT VT, SDNodeFlags Flags) { 12845 switch (Opcode) { 12846 default: 12847 return SDValue(); 12848 case ISD::ADD: 12849 case ISD::OR: 12850 case ISD::XOR: 12851 case ISD::UMAX: 12852 return getConstant(0, DL, VT); 12853 case ISD::MUL: 12854 return getConstant(1, DL, VT); 12855 case ISD::AND: 12856 case ISD::UMIN: 12857 return getAllOnesConstant(DL, VT); 12858 case ISD::SMAX: 12859 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 12860 case ISD::SMIN: 12861 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 12862 case ISD::FADD: 12863 return getConstantFP(-0.0, DL, VT); 12864 case ISD::FMUL: 12865 return getConstantFP(1.0, DL, VT); 12866 case ISD::FMINNUM: 12867 case ISD::FMAXNUM: { 12868 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 12869 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 12870 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 12871 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 12872 APFloat::getLargest(Semantics); 12873 if (Opcode == ISD::FMAXNUM) 12874 NeutralAF.changeSign(); 12875 12876 return getConstantFP(NeutralAF, DL, VT); 12877 } 12878 case ISD::FMINIMUM: 12879 case ISD::FMAXIMUM: { 12880 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF. 12881 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 12882 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics) 12883 : APFloat::getLargest(Semantics); 12884 if (Opcode == ISD::FMAXIMUM) 12885 NeutralAF.changeSign(); 12886 12887 return getConstantFP(NeutralAF, DL, VT); 12888 } 12889 12890 } 12891 } 12892 12893 /// Helper used to make a call to a library function that has one argument of 12894 /// pointer type. 12895 /// 12896 /// Such functions include 'fegetmode', 'fesetenv' and some others, which are 12897 /// used to get or set floating-point state. They have one argument of pointer 12898 /// type, which points to the memory region containing bits of the 12899 /// floating-point state. The value returned by such function is ignored in the 12900 /// created call. 12901 /// 12902 /// \param LibFunc Reference to library function (value of RTLIB::Libcall). 12903 /// \param Ptr Pointer used to save/load state. 12904 /// \param InChain Ingoing token chain. 12905 /// \returns Outgoing chain token. 12906 SDValue SelectionDAG::makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, 12907 SDValue InChain, 12908 const SDLoc &DLoc) { 12909 assert(InChain.getValueType() == MVT::Other && "Expected token chain"); 12910 TargetLowering::ArgListTy Args; 12911 TargetLowering::ArgListEntry Entry; 12912 Entry.Node = Ptr; 12913 Entry.Ty = Ptr.getValueType().getTypeForEVT(*getContext()); 12914 Args.push_back(Entry); 12915 RTLIB::Libcall LC = static_cast<RTLIB::Libcall>(LibFunc); 12916 SDValue Callee = getExternalSymbol(TLI->getLibcallName(LC), 12917 TLI->getPointerTy(getDataLayout())); 12918 TargetLowering::CallLoweringInfo CLI(*this); 12919 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee( 12920 TLI->getLibcallCallingConv(LC), Type::getVoidTy(*getContext()), Callee, 12921 std::move(Args)); 12922 return TLI->LowerCallTo(CLI).second; 12923 } 12924 12925 void SelectionDAG::copyExtraInfo(SDNode *From, SDNode *To) { 12926 assert(From && To && "Invalid SDNode; empty source SDValue?"); 12927 auto I = SDEI.find(From); 12928 if (I == SDEI.end()) 12929 return; 12930 12931 // Use of operator[] on the DenseMap may cause an insertion, which invalidates 12932 // the iterator, hence the need to make a copy to prevent a use-after-free. 12933 NodeExtraInfo NEI = I->second; 12934 if (LLVM_LIKELY(!NEI.PCSections)) { 12935 // No deep copy required for the types of extra info set. 12936 // 12937 // FIXME: Investigate if other types of extra info also need deep copy. This 12938 // depends on the types of nodes they can be attached to: if some extra info 12939 // is only ever attached to nodes where a replacement To node is always the 12940 // node where later use and propagation of the extra info has the intended 12941 // semantics, no deep copy is required. 12942 SDEI[To] = std::move(NEI); 12943 return; 12944 } 12945 12946 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced 12947 // through the replacement of From with To. Otherwise, replacements of a node 12948 // (From) with more complex nodes (To and its operands) may result in lost 12949 // extra info where the root node (To) is insignificant in further propagating 12950 // and using extra info when further lowering to MIR. 12951 // 12952 // In the first step pre-populate the visited set with the nodes reachable 12953 // from the old From node. This avoids copying NodeExtraInfo to parts of the 12954 // DAG that is not new and should be left untouched. 12955 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom. 12956 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From. 12957 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) { 12958 if (MaxDepth == 0) { 12959 // Remember this node in case we need to increase MaxDepth and continue 12960 // populating FromReach from this node. 12961 Leafs.emplace_back(N); 12962 return; 12963 } 12964 if (!FromReach.insert(N).second) 12965 return; 12966 for (const SDValue &Op : N->op_values()) 12967 Self(Self, Op.getNode(), MaxDepth - 1); 12968 }; 12969 12970 // Copy extra info to To and all its transitive operands (that are new). 12971 SmallPtrSet<const SDNode *, 8> Visited; 12972 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) { 12973 if (FromReach.contains(N)) 12974 return true; 12975 if (!Visited.insert(N).second) 12976 return true; 12977 if (getEntryNode().getNode() == N) 12978 return false; 12979 for (const SDValue &Op : N->op_values()) { 12980 if (!Self(Self, Op.getNode())) 12981 return false; 12982 } 12983 // Copy only if entry node was not reached. 12984 SDEI[N] = NEI; 12985 return true; 12986 }; 12987 12988 // We first try with a lower MaxDepth, assuming that the path to common 12989 // operands between From and To is relatively short. This significantly 12990 // improves performance in the common case. The initial MaxDepth is big 12991 // enough to avoid retry in the common case; the last MaxDepth is large 12992 // enough to avoid having to use the fallback below (and protects from 12993 // potential stack exhaustion from recursion). 12994 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024; 12995 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) { 12996 // StartFrom is the previous (or initial) set of leafs reachable at the 12997 // previous maximum depth. 12998 SmallVector<const SDNode *> StartFrom; 12999 std::swap(StartFrom, Leafs); 13000 for (const SDNode *N : StartFrom) 13001 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth); 13002 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To))) 13003 return; 13004 // This should happen very rarely (reached the entry node). 13005 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n"); 13006 assert(!Leafs.empty()); 13007 } 13008 13009 // This should not happen - but if it did, that means the subgraph reachable 13010 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom() 13011 // could not visit all reachable common operands. Consequently, we were able 13012 // to reach the entry node. 13013 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n"; 13014 assert(false && "From subgraph too complex - increase max. MaxDepth?"); 13015 // Best-effort fallback if assertions disabled. 13016 SDEI[To] = std::move(NEI); 13017 } 13018 13019 #ifndef NDEBUG 13020 static void checkForCyclesHelper(const SDNode *N, 13021 SmallPtrSetImpl<const SDNode*> &Visited, 13022 SmallPtrSetImpl<const SDNode*> &Checked, 13023 const llvm::SelectionDAG *DAG) { 13024 // If this node has already been checked, don't check it again. 13025 if (Checked.count(N)) 13026 return; 13027 13028 // If a node has already been visited on this depth-first walk, reject it as 13029 // a cycle. 13030 if (!Visited.insert(N).second) { 13031 errs() << "Detected cycle in SelectionDAG\n"; 13032 dbgs() << "Offending node:\n"; 13033 N->dumprFull(DAG); dbgs() << "\n"; 13034 abort(); 13035 } 13036 13037 for (const SDValue &Op : N->op_values()) 13038 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 13039 13040 Checked.insert(N); 13041 Visited.erase(N); 13042 } 13043 #endif 13044 13045 void llvm::checkForCycles(const llvm::SDNode *N, 13046 const llvm::SelectionDAG *DAG, 13047 bool force) { 13048 #ifndef NDEBUG 13049 bool check = force; 13050 #ifdef EXPENSIVE_CHECKS 13051 check = true; 13052 #endif // EXPENSIVE_CHECKS 13053 if (check) { 13054 assert(N && "Checking nonexistent SDNode"); 13055 SmallPtrSet<const SDNode*, 32> visited; 13056 SmallPtrSet<const SDNode*, 32> checked; 13057 checkForCyclesHelper(N, visited, checked, DAG); 13058 } 13059 #endif // !NDEBUG 13060 } 13061 13062 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 13063 checkForCycles(DAG->getRoot().getNode(), DAG, force); 13064 } 13065