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/FoldingSet.h" 21 #include "llvm/ADT/None.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Triple.h" 26 #include "llvm/ADT/Twine.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/CodeGen/Analysis.h" 30 #include "llvm/CodeGen/FunctionLoweringInfo.h" 31 #include "llvm/CodeGen/ISDOpcodes.h" 32 #include "llvm/CodeGen/MachineBasicBlock.h" 33 #include "llvm/CodeGen/MachineConstantPool.h" 34 #include "llvm/CodeGen/MachineFrameInfo.h" 35 #include "llvm/CodeGen/MachineFunction.h" 36 #include "llvm/CodeGen/MachineMemOperand.h" 37 #include "llvm/CodeGen/RuntimeLibcalls.h" 38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 39 #include "llvm/CodeGen/SelectionDAGNodes.h" 40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 41 #include "llvm/CodeGen/TargetFrameLowering.h" 42 #include "llvm/CodeGen/TargetLowering.h" 43 #include "llvm/CodeGen/TargetRegisterInfo.h" 44 #include "llvm/CodeGen/TargetSubtargetInfo.h" 45 #include "llvm/CodeGen/ValueTypes.h" 46 #include "llvm/IR/Constant.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DebugInfoMetadata.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/IR/GlobalValue.h" 54 #include "llvm/IR/Metadata.h" 55 #include "llvm/IR/Type.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CodeGen.h" 58 #include "llvm/Support/Compiler.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/KnownBits.h" 62 #include "llvm/Support/MachineValueType.h" 63 #include "llvm/Support/ManagedStatic.h" 64 #include "llvm/Support/MathExtras.h" 65 #include "llvm/Support/Mutex.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include "llvm/Target/TargetOptions.h" 69 #include "llvm/Transforms/Utils/SizeOpts.h" 70 #include <algorithm> 71 #include <cassert> 72 #include <cstdint> 73 #include <cstdlib> 74 #include <limits> 75 #include <set> 76 #include <string> 77 #include <utility> 78 #include <vector> 79 80 using namespace llvm; 81 82 /// makeVTList - Return an instance of the SDVTList struct initialized with the 83 /// specified members. 84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 85 SDVTList Res = {VTs, NumVTs}; 86 return Res; 87 } 88 89 // Default null implementations of the callbacks. 90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 93 94 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 95 96 #define DEBUG_TYPE "selectiondag" 97 98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 99 cl::Hidden, cl::init(true), 100 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 101 102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 103 cl::desc("Number limit for gluing ld/st of memcpy."), 104 cl::Hidden, cl::init(0)); 105 106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 107 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 108 } 109 110 //===----------------------------------------------------------------------===// 111 // ConstantFPSDNode Class 112 //===----------------------------------------------------------------------===// 113 114 /// isExactlyValue - We don't rely on operator== working on double values, as 115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 116 /// As such, this method can be used to do an exact bit-for-bit comparison of 117 /// two floating point values. 118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 119 return getValueAPF().bitwiseIsEqual(V); 120 } 121 122 bool ConstantFPSDNode::isValueValidForType(EVT VT, 123 const APFloat& Val) { 124 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 125 126 // convert modifies in place, so make a copy. 127 APFloat Val2 = APFloat(Val); 128 bool losesInfo; 129 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 130 APFloat::rmNearestTiesToEven, 131 &losesInfo); 132 return !losesInfo; 133 } 134 135 //===----------------------------------------------------------------------===// 136 // ISD Namespace 137 //===----------------------------------------------------------------------===// 138 139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 140 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 141 unsigned EltSize = 142 N->getValueType(0).getVectorElementType().getSizeInBits(); 143 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 144 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize); 145 return true; 146 } 147 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 148 SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize); 149 return true; 150 } 151 } 152 153 auto *BV = dyn_cast<BuildVectorSDNode>(N); 154 if (!BV) 155 return false; 156 157 APInt SplatUndef; 158 unsigned SplatBitSize; 159 bool HasUndefs; 160 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 161 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 162 EltSize) && 163 EltSize == SplatBitSize; 164 } 165 166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 167 // specializations of the more general isConstantSplatVector()? 168 169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 170 // Look through a bit convert. 171 while (N->getOpcode() == ISD::BITCAST) 172 N = N->getOperand(0).getNode(); 173 174 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 175 APInt SplatVal; 176 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 177 } 178 179 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 180 181 unsigned i = 0, e = N->getNumOperands(); 182 183 // Skip over all of the undef values. 184 while (i != e && N->getOperand(i).isUndef()) 185 ++i; 186 187 // Do not accept an all-undef vector. 188 if (i == e) return false; 189 190 // Do not accept build_vectors that aren't all constants or which have non-~0 191 // elements. We have to be a bit careful here, as the type of the constant 192 // may not be the same as the type of the vector elements due to type 193 // legalization (the elements are promoted to a legal type for the target and 194 // a vector of a type may be legal when the base element type is not). 195 // We only want to check enough bits to cover the vector elements, because 196 // we care if the resultant vector is all ones, not whether the individual 197 // constants are. 198 SDValue NotZero = N->getOperand(i); 199 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 200 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 201 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 202 return false; 203 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 204 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 205 return false; 206 } else 207 return false; 208 209 // Okay, we have at least one ~0 value, check to see if the rest match or are 210 // undefs. Even with the above element type twiddling, this should be OK, as 211 // the same type legalization should have applied to all the elements. 212 for (++i; i != e; ++i) 213 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 214 return false; 215 return true; 216 } 217 218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 219 // Look through a bit convert. 220 while (N->getOpcode() == ISD::BITCAST) 221 N = N->getOperand(0).getNode(); 222 223 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 224 APInt SplatVal; 225 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 226 } 227 228 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 229 230 bool IsAllUndef = true; 231 for (const SDValue &Op : N->op_values()) { 232 if (Op.isUndef()) 233 continue; 234 IsAllUndef = false; 235 // Do not accept build_vectors that aren't all constants or which have non-0 236 // elements. We have to be a bit careful here, as the type of the constant 237 // may not be the same as the type of the vector elements due to type 238 // legalization (the elements are promoted to a legal type for the target 239 // and a vector of a type may be legal when the base element type is not). 240 // We only want to check enough bits to cover the vector elements, because 241 // we care if the resultant vector is all zeros, not whether the individual 242 // constants are. 243 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 244 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 245 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 246 return false; 247 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 248 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 249 return false; 250 } else 251 return false; 252 } 253 254 // Do not accept an all-undef vector. 255 if (IsAllUndef) 256 return false; 257 return true; 258 } 259 260 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 261 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 262 } 263 264 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 265 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 266 } 267 268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 269 if (N->getOpcode() != ISD::BUILD_VECTOR) 270 return false; 271 272 for (const SDValue &Op : N->op_values()) { 273 if (Op.isUndef()) 274 continue; 275 if (!isa<ConstantSDNode>(Op)) 276 return false; 277 } 278 return true; 279 } 280 281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 282 if (N->getOpcode() != ISD::BUILD_VECTOR) 283 return false; 284 285 for (const SDValue &Op : N->op_values()) { 286 if (Op.isUndef()) 287 continue; 288 if (!isa<ConstantFPSDNode>(Op)) 289 return false; 290 } 291 return true; 292 } 293 294 bool ISD::allOperandsUndef(const SDNode *N) { 295 // Return false if the node has no operands. 296 // This is "logically inconsistent" with the definition of "all" but 297 // is probably the desired behavior. 298 if (N->getNumOperands() == 0) 299 return false; 300 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 301 } 302 303 bool ISD::matchUnaryPredicate(SDValue Op, 304 std::function<bool(ConstantSDNode *)> Match, 305 bool AllowUndefs) { 306 // FIXME: Add support for scalar UNDEF cases? 307 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 308 return Match(Cst); 309 310 // FIXME: Add support for vector UNDEF cases? 311 if (ISD::BUILD_VECTOR != Op.getOpcode() && 312 ISD::SPLAT_VECTOR != Op.getOpcode()) 313 return false; 314 315 EVT SVT = Op.getValueType().getScalarType(); 316 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 317 if (AllowUndefs && Op.getOperand(i).isUndef()) { 318 if (!Match(nullptr)) 319 return false; 320 continue; 321 } 322 323 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 324 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 325 return false; 326 } 327 return true; 328 } 329 330 bool ISD::matchBinaryPredicate( 331 SDValue LHS, SDValue RHS, 332 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 333 bool AllowUndefs, bool AllowTypeMismatch) { 334 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 335 return false; 336 337 // TODO: Add support for scalar UNDEF cases? 338 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 339 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 340 return Match(LHSCst, RHSCst); 341 342 // TODO: Add support for vector UNDEF cases? 343 if (LHS.getOpcode() != RHS.getOpcode() || 344 (LHS.getOpcode() != ISD::BUILD_VECTOR && 345 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 346 return false; 347 348 EVT SVT = LHS.getValueType().getScalarType(); 349 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 350 SDValue LHSOp = LHS.getOperand(i); 351 SDValue RHSOp = RHS.getOperand(i); 352 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 353 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 354 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 355 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 356 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 357 return false; 358 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 359 LHSOp.getValueType() != RHSOp.getValueType())) 360 return false; 361 if (!Match(LHSCst, RHSCst)) 362 return false; 363 } 364 return true; 365 } 366 367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 368 switch (VecReduceOpcode) { 369 default: 370 llvm_unreachable("Expected VECREDUCE opcode"); 371 case ISD::VECREDUCE_FADD: 372 case ISD::VECREDUCE_SEQ_FADD: 373 case ISD::VP_REDUCE_FADD: 374 case ISD::VP_REDUCE_SEQ_FADD: 375 return ISD::FADD; 376 case ISD::VECREDUCE_FMUL: 377 case ISD::VECREDUCE_SEQ_FMUL: 378 case ISD::VP_REDUCE_FMUL: 379 case ISD::VP_REDUCE_SEQ_FMUL: 380 return ISD::FMUL; 381 case ISD::VECREDUCE_ADD: 382 case ISD::VP_REDUCE_ADD: 383 return ISD::ADD; 384 case ISD::VECREDUCE_MUL: 385 case ISD::VP_REDUCE_MUL: 386 return ISD::MUL; 387 case ISD::VECREDUCE_AND: 388 case ISD::VP_REDUCE_AND: 389 return ISD::AND; 390 case ISD::VECREDUCE_OR: 391 case ISD::VP_REDUCE_OR: 392 return ISD::OR; 393 case ISD::VECREDUCE_XOR: 394 case ISD::VP_REDUCE_XOR: 395 return ISD::XOR; 396 case ISD::VECREDUCE_SMAX: 397 case ISD::VP_REDUCE_SMAX: 398 return ISD::SMAX; 399 case ISD::VECREDUCE_SMIN: 400 case ISD::VP_REDUCE_SMIN: 401 return ISD::SMIN; 402 case ISD::VECREDUCE_UMAX: 403 case ISD::VP_REDUCE_UMAX: 404 return ISD::UMAX; 405 case ISD::VECREDUCE_UMIN: 406 case ISD::VP_REDUCE_UMIN: 407 return ISD::UMIN; 408 case ISD::VECREDUCE_FMAX: 409 case ISD::VP_REDUCE_FMAX: 410 return ISD::FMAXNUM; 411 case ISD::VECREDUCE_FMIN: 412 case ISD::VP_REDUCE_FMIN: 413 return ISD::FMINNUM; 414 } 415 } 416 417 bool ISD::isVPOpcode(unsigned Opcode) { 418 switch (Opcode) { 419 default: 420 return false; 421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 422 case ISD::VPSD: \ 423 return true; 424 #include "llvm/IR/VPIntrinsics.def" 425 } 426 } 427 428 bool ISD::isVPBinaryOp(unsigned Opcode) { 429 switch (Opcode) { 430 default: 431 break; 432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 433 #define VP_PROPERTY_BINARYOP return true; 434 #define END_REGISTER_VP_SDNODE(VPSD) break; 435 #include "llvm/IR/VPIntrinsics.def" 436 } 437 return false; 438 } 439 440 bool ISD::isVPReduction(unsigned Opcode) { 441 switch (Opcode) { 442 default: 443 break; 444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 446 #define END_REGISTER_VP_SDNODE(VPSD) break; 447 #include "llvm/IR/VPIntrinsics.def" 448 } 449 return false; 450 } 451 452 /// The operand position of the vector mask. 453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 454 switch (Opcode) { 455 default: 456 return None; 457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 458 case ISD::VPSD: \ 459 return MASKPOS; 460 #include "llvm/IR/VPIntrinsics.def" 461 } 462 } 463 464 /// The operand position of the explicit vector length parameter. 465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 466 switch (Opcode) { 467 default: 468 return None; 469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 470 case ISD::VPSD: \ 471 return EVLPOS; 472 #include "llvm/IR/VPIntrinsics.def" 473 } 474 } 475 476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 477 switch (ExtType) { 478 case ISD::EXTLOAD: 479 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 480 case ISD::SEXTLOAD: 481 return ISD::SIGN_EXTEND; 482 case ISD::ZEXTLOAD: 483 return ISD::ZERO_EXTEND; 484 default: 485 break; 486 } 487 488 llvm_unreachable("Invalid LoadExtType"); 489 } 490 491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 492 // To perform this operation, we just need to swap the L and G bits of the 493 // operation. 494 unsigned OldL = (Operation >> 2) & 1; 495 unsigned OldG = (Operation >> 1) & 1; 496 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 497 (OldL << 1) | // New G bit 498 (OldG << 2)); // New L bit. 499 } 500 501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 502 unsigned Operation = Op; 503 if (isIntegerLike) 504 Operation ^= 7; // Flip L, G, E bits, but not U. 505 else 506 Operation ^= 15; // Flip all of the condition bits. 507 508 if (Operation > ISD::SETTRUE2) 509 Operation &= ~8; // Don't let N and U bits get set. 510 511 return ISD::CondCode(Operation); 512 } 513 514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 515 return getSetCCInverseImpl(Op, Type.isInteger()); 516 } 517 518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 519 bool isIntegerLike) { 520 return getSetCCInverseImpl(Op, isIntegerLike); 521 } 522 523 /// For an integer comparison, return 1 if the comparison is a signed operation 524 /// and 2 if the result is an unsigned comparison. Return zero if the operation 525 /// does not depend on the sign of the input (setne and seteq). 526 static int isSignedOp(ISD::CondCode Opcode) { 527 switch (Opcode) { 528 default: llvm_unreachable("Illegal integer setcc operation!"); 529 case ISD::SETEQ: 530 case ISD::SETNE: return 0; 531 case ISD::SETLT: 532 case ISD::SETLE: 533 case ISD::SETGT: 534 case ISD::SETGE: return 1; 535 case ISD::SETULT: 536 case ISD::SETULE: 537 case ISD::SETUGT: 538 case ISD::SETUGE: return 2; 539 } 540 } 541 542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 543 EVT Type) { 544 bool IsInteger = Type.isInteger(); 545 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 546 // Cannot fold a signed integer setcc with an unsigned integer setcc. 547 return ISD::SETCC_INVALID; 548 549 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 550 551 // If the N and U bits get set, then the resultant comparison DOES suddenly 552 // care about orderedness, and it is true when ordered. 553 if (Op > ISD::SETTRUE2) 554 Op &= ~16; // Clear the U bit if the N bit is set. 555 556 // Canonicalize illegal integer setcc's. 557 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 558 Op = ISD::SETNE; 559 560 return ISD::CondCode(Op); 561 } 562 563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 564 EVT Type) { 565 bool IsInteger = Type.isInteger(); 566 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 567 // Cannot fold a signed setcc with an unsigned setcc. 568 return ISD::SETCC_INVALID; 569 570 // Combine all of the condition bits. 571 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 572 573 // Canonicalize illegal integer setcc's. 574 if (IsInteger) { 575 switch (Result) { 576 default: break; 577 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 578 case ISD::SETOEQ: // SETEQ & SETU[LG]E 579 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 580 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 581 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 582 } 583 } 584 585 return Result; 586 } 587 588 //===----------------------------------------------------------------------===// 589 // SDNode Profile Support 590 //===----------------------------------------------------------------------===// 591 592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 594 ID.AddInteger(OpC); 595 } 596 597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 598 /// solely with their pointer. 599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 600 ID.AddPointer(VTList.VTs); 601 } 602 603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 604 static void AddNodeIDOperands(FoldingSetNodeID &ID, 605 ArrayRef<SDValue> Ops) { 606 for (auto& Op : Ops) { 607 ID.AddPointer(Op.getNode()); 608 ID.AddInteger(Op.getResNo()); 609 } 610 } 611 612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 613 static void AddNodeIDOperands(FoldingSetNodeID &ID, 614 ArrayRef<SDUse> Ops) { 615 for (auto& Op : Ops) { 616 ID.AddPointer(Op.getNode()); 617 ID.AddInteger(Op.getResNo()); 618 } 619 } 620 621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 622 SDVTList VTList, ArrayRef<SDValue> OpList) { 623 AddNodeIDOpcode(ID, OpC); 624 AddNodeIDValueTypes(ID, VTList); 625 AddNodeIDOperands(ID, OpList); 626 } 627 628 /// If this is an SDNode with special info, add this info to the NodeID data. 629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 630 switch (N->getOpcode()) { 631 case ISD::TargetExternalSymbol: 632 case ISD::ExternalSymbol: 633 case ISD::MCSymbol: 634 llvm_unreachable("Should only be used on nodes with operands"); 635 default: break; // Normal nodes don't need extra info. 636 case ISD::TargetConstant: 637 case ISD::Constant: { 638 const ConstantSDNode *C = cast<ConstantSDNode>(N); 639 ID.AddPointer(C->getConstantIntValue()); 640 ID.AddBoolean(C->isOpaque()); 641 break; 642 } 643 case ISD::TargetConstantFP: 644 case ISD::ConstantFP: 645 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 646 break; 647 case ISD::TargetGlobalAddress: 648 case ISD::GlobalAddress: 649 case ISD::TargetGlobalTLSAddress: 650 case ISD::GlobalTLSAddress: { 651 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 652 ID.AddPointer(GA->getGlobal()); 653 ID.AddInteger(GA->getOffset()); 654 ID.AddInteger(GA->getTargetFlags()); 655 break; 656 } 657 case ISD::BasicBlock: 658 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 659 break; 660 case ISD::Register: 661 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 662 break; 663 case ISD::RegisterMask: 664 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 665 break; 666 case ISD::SRCVALUE: 667 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 668 break; 669 case ISD::FrameIndex: 670 case ISD::TargetFrameIndex: 671 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 672 break; 673 case ISD::LIFETIME_START: 674 case ISD::LIFETIME_END: 675 if (cast<LifetimeSDNode>(N)->hasOffset()) { 676 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 677 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 678 } 679 break; 680 case ISD::PSEUDO_PROBE: 681 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 682 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 683 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 684 break; 685 case ISD::JumpTable: 686 case ISD::TargetJumpTable: 687 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 688 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 689 break; 690 case ISD::ConstantPool: 691 case ISD::TargetConstantPool: { 692 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 693 ID.AddInteger(CP->getAlign().value()); 694 ID.AddInteger(CP->getOffset()); 695 if (CP->isMachineConstantPoolEntry()) 696 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 697 else 698 ID.AddPointer(CP->getConstVal()); 699 ID.AddInteger(CP->getTargetFlags()); 700 break; 701 } 702 case ISD::TargetIndex: { 703 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 704 ID.AddInteger(TI->getIndex()); 705 ID.AddInteger(TI->getOffset()); 706 ID.AddInteger(TI->getTargetFlags()); 707 break; 708 } 709 case ISD::LOAD: { 710 const LoadSDNode *LD = cast<LoadSDNode>(N); 711 ID.AddInteger(LD->getMemoryVT().getRawBits()); 712 ID.AddInteger(LD->getRawSubclassData()); 713 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 714 ID.AddInteger(LD->getMemOperand()->getFlags()); 715 break; 716 } 717 case ISD::STORE: { 718 const StoreSDNode *ST = cast<StoreSDNode>(N); 719 ID.AddInteger(ST->getMemoryVT().getRawBits()); 720 ID.AddInteger(ST->getRawSubclassData()); 721 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 722 ID.AddInteger(ST->getMemOperand()->getFlags()); 723 break; 724 } 725 case ISD::VP_LOAD: { 726 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 727 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 728 ID.AddInteger(ELD->getRawSubclassData()); 729 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 730 ID.AddInteger(ELD->getMemOperand()->getFlags()); 731 break; 732 } 733 case ISD::VP_STORE: { 734 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 735 ID.AddInteger(EST->getMemoryVT().getRawBits()); 736 ID.AddInteger(EST->getRawSubclassData()); 737 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 738 ID.AddInteger(EST->getMemOperand()->getFlags()); 739 break; 740 } 741 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: { 742 const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N); 743 ID.AddInteger(SLD->getMemoryVT().getRawBits()); 744 ID.AddInteger(SLD->getRawSubclassData()); 745 ID.AddInteger(SLD->getPointerInfo().getAddrSpace()); 746 break; 747 } 748 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: { 749 const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N); 750 ID.AddInteger(SST->getMemoryVT().getRawBits()); 751 ID.AddInteger(SST->getRawSubclassData()); 752 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 753 break; 754 } 755 case ISD::VP_GATHER: { 756 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 757 ID.AddInteger(EG->getMemoryVT().getRawBits()); 758 ID.AddInteger(EG->getRawSubclassData()); 759 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 760 ID.AddInteger(EG->getMemOperand()->getFlags()); 761 break; 762 } 763 case ISD::VP_SCATTER: { 764 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 765 ID.AddInteger(ES->getMemoryVT().getRawBits()); 766 ID.AddInteger(ES->getRawSubclassData()); 767 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 768 ID.AddInteger(ES->getMemOperand()->getFlags()); 769 break; 770 } 771 case ISD::MLOAD: { 772 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 773 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 774 ID.AddInteger(MLD->getRawSubclassData()); 775 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 776 ID.AddInteger(MLD->getMemOperand()->getFlags()); 777 break; 778 } 779 case ISD::MSTORE: { 780 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 781 ID.AddInteger(MST->getMemoryVT().getRawBits()); 782 ID.AddInteger(MST->getRawSubclassData()); 783 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 784 ID.AddInteger(MST->getMemOperand()->getFlags()); 785 break; 786 } 787 case ISD::MGATHER: { 788 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 789 ID.AddInteger(MG->getMemoryVT().getRawBits()); 790 ID.AddInteger(MG->getRawSubclassData()); 791 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 792 ID.AddInteger(MG->getMemOperand()->getFlags()); 793 break; 794 } 795 case ISD::MSCATTER: { 796 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 797 ID.AddInteger(MS->getMemoryVT().getRawBits()); 798 ID.AddInteger(MS->getRawSubclassData()); 799 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 800 ID.AddInteger(MS->getMemOperand()->getFlags()); 801 break; 802 } 803 case ISD::ATOMIC_CMP_SWAP: 804 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 805 case ISD::ATOMIC_SWAP: 806 case ISD::ATOMIC_LOAD_ADD: 807 case ISD::ATOMIC_LOAD_SUB: 808 case ISD::ATOMIC_LOAD_AND: 809 case ISD::ATOMIC_LOAD_CLR: 810 case ISD::ATOMIC_LOAD_OR: 811 case ISD::ATOMIC_LOAD_XOR: 812 case ISD::ATOMIC_LOAD_NAND: 813 case ISD::ATOMIC_LOAD_MIN: 814 case ISD::ATOMIC_LOAD_MAX: 815 case ISD::ATOMIC_LOAD_UMIN: 816 case ISD::ATOMIC_LOAD_UMAX: 817 case ISD::ATOMIC_LOAD: 818 case ISD::ATOMIC_STORE: { 819 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 820 ID.AddInteger(AT->getMemoryVT().getRawBits()); 821 ID.AddInteger(AT->getRawSubclassData()); 822 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 823 ID.AddInteger(AT->getMemOperand()->getFlags()); 824 break; 825 } 826 case ISD::PREFETCH: { 827 const MemSDNode *PF = cast<MemSDNode>(N); 828 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 829 ID.AddInteger(PF->getMemOperand()->getFlags()); 830 break; 831 } 832 case ISD::VECTOR_SHUFFLE: { 833 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 834 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 835 i != e; ++i) 836 ID.AddInteger(SVN->getMaskElt(i)); 837 break; 838 } 839 case ISD::TargetBlockAddress: 840 case ISD::BlockAddress: { 841 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 842 ID.AddPointer(BA->getBlockAddress()); 843 ID.AddInteger(BA->getOffset()); 844 ID.AddInteger(BA->getTargetFlags()); 845 break; 846 } 847 case ISD::AssertAlign: 848 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value()); 849 break; 850 } // end switch (N->getOpcode()) 851 852 // Target specific memory nodes could also have address spaces and flags 853 // to check. 854 if (N->isTargetMemoryOpcode()) { 855 const MemSDNode *MN = cast<MemSDNode>(N); 856 ID.AddInteger(MN->getPointerInfo().getAddrSpace()); 857 ID.AddInteger(MN->getMemOperand()->getFlags()); 858 } 859 } 860 861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 862 /// data. 863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 864 AddNodeIDOpcode(ID, N->getOpcode()); 865 // Add the return value info. 866 AddNodeIDValueTypes(ID, N->getVTList()); 867 // Add the operand info. 868 AddNodeIDOperands(ID, N->ops()); 869 870 // Handle SDNode leafs with special info. 871 AddNodeIDCustom(ID, N); 872 } 873 874 //===----------------------------------------------------------------------===// 875 // SelectionDAG Class 876 //===----------------------------------------------------------------------===// 877 878 /// doNotCSE - Return true if CSE should not be performed for this node. 879 static bool doNotCSE(SDNode *N) { 880 if (N->getValueType(0) == MVT::Glue) 881 return true; // Never CSE anything that produces a flag. 882 883 switch (N->getOpcode()) { 884 default: break; 885 case ISD::HANDLENODE: 886 case ISD::EH_LABEL: 887 return true; // Never CSE these nodes. 888 } 889 890 // Check that remaining values produced are not flags. 891 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 892 if (N->getValueType(i) == MVT::Glue) 893 return true; // Never CSE anything that produces a flag. 894 895 return false; 896 } 897 898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 899 /// SelectionDAG. 900 void SelectionDAG::RemoveDeadNodes() { 901 // Create a dummy node (which is not added to allnodes), that adds a reference 902 // to the root node, preventing it from being deleted. 903 HandleSDNode Dummy(getRoot()); 904 905 SmallVector<SDNode*, 128> DeadNodes; 906 907 // Add all obviously-dead nodes to the DeadNodes worklist. 908 for (SDNode &Node : allnodes()) 909 if (Node.use_empty()) 910 DeadNodes.push_back(&Node); 911 912 RemoveDeadNodes(DeadNodes); 913 914 // If the root changed (e.g. it was a dead load, update the root). 915 setRoot(Dummy.getValue()); 916 } 917 918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 919 /// given list, and any nodes that become unreachable as a result. 920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 921 922 // Process the worklist, deleting the nodes and adding their uses to the 923 // worklist. 924 while (!DeadNodes.empty()) { 925 SDNode *N = DeadNodes.pop_back_val(); 926 // Skip to next node if we've already managed to delete the node. This could 927 // happen if replacing a node causes a node previously added to the node to 928 // be deleted. 929 if (N->getOpcode() == ISD::DELETED_NODE) 930 continue; 931 932 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 933 DUL->NodeDeleted(N, nullptr); 934 935 // Take the node out of the appropriate CSE map. 936 RemoveNodeFromCSEMaps(N); 937 938 // Next, brutally remove the operand list. This is safe to do, as there are 939 // no cycles in the graph. 940 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 941 SDUse &Use = *I++; 942 SDNode *Operand = Use.getNode(); 943 Use.set(SDValue()); 944 945 // Now that we removed this operand, see if there are no uses of it left. 946 if (Operand->use_empty()) 947 DeadNodes.push_back(Operand); 948 } 949 950 DeallocateNode(N); 951 } 952 } 953 954 void SelectionDAG::RemoveDeadNode(SDNode *N){ 955 SmallVector<SDNode*, 16> DeadNodes(1, N); 956 957 // Create a dummy node that adds a reference to the root node, preventing 958 // it from being deleted. (This matters if the root is an operand of the 959 // dead node.) 960 HandleSDNode Dummy(getRoot()); 961 962 RemoveDeadNodes(DeadNodes); 963 } 964 965 void SelectionDAG::DeleteNode(SDNode *N) { 966 // First take this out of the appropriate CSE map. 967 RemoveNodeFromCSEMaps(N); 968 969 // Finally, remove uses due to operands of this node, remove from the 970 // AllNodes list, and delete the node. 971 DeleteNodeNotInCSEMaps(N); 972 } 973 974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 975 assert(N->getIterator() != AllNodes.begin() && 976 "Cannot delete the entry node!"); 977 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 978 979 // Drop all of the operands and decrement used node's use counts. 980 N->DropOperands(); 981 982 DeallocateNode(N); 983 } 984 985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 986 assert(!(V->isVariadic() && isParameter)); 987 if (isParameter) 988 ByvalParmDbgValues.push_back(V); 989 else 990 DbgValues.push_back(V); 991 for (const SDNode *Node : V->getSDNodes()) 992 if (Node) 993 DbgValMap[Node].push_back(V); 994 } 995 996 void SDDbgInfo::erase(const SDNode *Node) { 997 DbgValMapType::iterator I = DbgValMap.find(Node); 998 if (I == DbgValMap.end()) 999 return; 1000 for (auto &Val: I->second) 1001 Val->setIsInvalidated(); 1002 DbgValMap.erase(I); 1003 } 1004 1005 void SelectionDAG::DeallocateNode(SDNode *N) { 1006 // If we have operands, deallocate them. 1007 removeOperands(N); 1008 1009 NodeAllocator.Deallocate(AllNodes.remove(N)); 1010 1011 // Set the opcode to DELETED_NODE to help catch bugs when node 1012 // memory is reallocated. 1013 // FIXME: There are places in SDag that have grown a dependency on the opcode 1014 // value in the released node. 1015 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 1016 N->NodeType = ISD::DELETED_NODE; 1017 1018 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 1019 // them and forget about that node. 1020 DbgInfo->erase(N); 1021 } 1022 1023 #ifndef NDEBUG 1024 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 1025 static void VerifySDNode(SDNode *N) { 1026 switch (N->getOpcode()) { 1027 default: 1028 break; 1029 case ISD::BUILD_PAIR: { 1030 EVT VT = N->getValueType(0); 1031 assert(N->getNumValues() == 1 && "Too many results!"); 1032 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1033 "Wrong return type!"); 1034 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1035 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1036 "Mismatched operand types!"); 1037 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1038 "Wrong operand type!"); 1039 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1040 "Wrong return type size"); 1041 break; 1042 } 1043 case ISD::BUILD_VECTOR: { 1044 assert(N->getNumValues() == 1 && "Too many results!"); 1045 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1046 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1047 "Wrong number of operands!"); 1048 EVT EltVT = N->getValueType(0).getVectorElementType(); 1049 for (const SDUse &Op : N->ops()) { 1050 assert((Op.getValueType() == EltVT || 1051 (EltVT.isInteger() && Op.getValueType().isInteger() && 1052 EltVT.bitsLE(Op.getValueType()))) && 1053 "Wrong operand type!"); 1054 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1055 "Operands must all have the same type"); 1056 } 1057 break; 1058 } 1059 } 1060 } 1061 #endif // NDEBUG 1062 1063 /// Insert a newly allocated node into the DAG. 1064 /// 1065 /// Handles insertion into the all nodes list and CSE map, as well as 1066 /// verification and other common operations when a new node is allocated. 1067 void SelectionDAG::InsertNode(SDNode *N) { 1068 AllNodes.push_back(N); 1069 #ifndef NDEBUG 1070 N->PersistentId = NextPersistentId++; 1071 VerifySDNode(N); 1072 #endif 1073 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1074 DUL->NodeInserted(N); 1075 } 1076 1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1078 /// correspond to it. This is useful when we're about to delete or repurpose 1079 /// the node. We don't want future request for structurally identical nodes 1080 /// to return N anymore. 1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1082 bool Erased = false; 1083 switch (N->getOpcode()) { 1084 case ISD::HANDLENODE: return false; // noop. 1085 case ISD::CONDCODE: 1086 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1087 "Cond code doesn't exist!"); 1088 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1089 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1090 break; 1091 case ISD::ExternalSymbol: 1092 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1093 break; 1094 case ISD::TargetExternalSymbol: { 1095 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1096 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1097 ESN->getSymbol(), ESN->getTargetFlags())); 1098 break; 1099 } 1100 case ISD::MCSymbol: { 1101 auto *MCSN = cast<MCSymbolSDNode>(N); 1102 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1103 break; 1104 } 1105 case ISD::VALUETYPE: { 1106 EVT VT = cast<VTSDNode>(N)->getVT(); 1107 if (VT.isExtended()) { 1108 Erased = ExtendedValueTypeNodes.erase(VT); 1109 } else { 1110 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1111 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1112 } 1113 break; 1114 } 1115 default: 1116 // Remove it from the CSE Map. 1117 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1118 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1119 Erased = CSEMap.RemoveNode(N); 1120 break; 1121 } 1122 #ifndef NDEBUG 1123 // Verify that the node was actually in one of the CSE maps, unless it has a 1124 // flag result (which cannot be CSE'd) or is one of the special cases that are 1125 // not subject to CSE. 1126 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1127 !N->isMachineOpcode() && !doNotCSE(N)) { 1128 N->dump(this); 1129 dbgs() << "\n"; 1130 llvm_unreachable("Node is not in map!"); 1131 } 1132 #endif 1133 return Erased; 1134 } 1135 1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1138 /// node already exists, in which case transfer all its users to the existing 1139 /// node. This transfer can potentially trigger recursive merging. 1140 void 1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1142 // For node types that aren't CSE'd, just act as if no identical node 1143 // already exists. 1144 if (!doNotCSE(N)) { 1145 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1146 if (Existing != N) { 1147 // If there was already an existing matching node, use ReplaceAllUsesWith 1148 // to replace the dead one with the existing one. This can cause 1149 // recursive merging of other unrelated nodes down the line. 1150 ReplaceAllUsesWith(N, Existing); 1151 1152 // N is now dead. Inform the listeners and delete it. 1153 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1154 DUL->NodeDeleted(N, Existing); 1155 DeleteNodeNotInCSEMaps(N); 1156 return; 1157 } 1158 } 1159 1160 // If the node doesn't already exist, we updated it. Inform listeners. 1161 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1162 DUL->NodeUpdated(N); 1163 } 1164 1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1166 /// were replaced with those specified. If this node is never memoized, 1167 /// return null, otherwise return a pointer to the slot it would take. If a 1168 /// node already exists with these operands, the slot will be non-null. 1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1170 void *&InsertPos) { 1171 if (doNotCSE(N)) 1172 return nullptr; 1173 1174 SDValue Ops[] = { Op }; 1175 FoldingSetNodeID ID; 1176 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1177 AddNodeIDCustom(ID, N); 1178 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1179 if (Node) 1180 Node->intersectFlagsWith(N->getFlags()); 1181 return Node; 1182 } 1183 1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1185 /// were replaced with those specified. If this node is never memoized, 1186 /// return null, otherwise return a pointer to the slot it would take. If a 1187 /// node already exists with these operands, the slot will be non-null. 1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1189 SDValue Op1, SDValue Op2, 1190 void *&InsertPos) { 1191 if (doNotCSE(N)) 1192 return nullptr; 1193 1194 SDValue Ops[] = { Op1, Op2 }; 1195 FoldingSetNodeID ID; 1196 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1197 AddNodeIDCustom(ID, N); 1198 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1199 if (Node) 1200 Node->intersectFlagsWith(N->getFlags()); 1201 return Node; 1202 } 1203 1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1205 /// were replaced with those specified. If this node is never memoized, 1206 /// return null, otherwise return a pointer to the slot it would take. If a 1207 /// node already exists with these operands, the slot will be non-null. 1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1209 void *&InsertPos) { 1210 if (doNotCSE(N)) 1211 return nullptr; 1212 1213 FoldingSetNodeID ID; 1214 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1215 AddNodeIDCustom(ID, N); 1216 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1217 if (Node) 1218 Node->intersectFlagsWith(N->getFlags()); 1219 return Node; 1220 } 1221 1222 Align SelectionDAG::getEVTAlign(EVT VT) const { 1223 Type *Ty = VT == MVT::iPTR ? 1224 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1225 VT.getTypeForEVT(*getContext()); 1226 1227 return getDataLayout().getABITypeAlign(Ty); 1228 } 1229 1230 // EntryNode could meaningfully have debug info if we can find it... 1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1232 : TM(tm), OptLevel(OL), 1233 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1234 Root(getEntryNode()) { 1235 InsertNode(&EntryNode); 1236 DbgInfo = new SDDbgInfo(); 1237 } 1238 1239 void SelectionDAG::init(MachineFunction &NewMF, 1240 OptimizationRemarkEmitter &NewORE, 1241 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1242 LegacyDivergenceAnalysis * Divergence, 1243 ProfileSummaryInfo *PSIin, 1244 BlockFrequencyInfo *BFIin) { 1245 MF = &NewMF; 1246 SDAGISelPass = PassPtr; 1247 ORE = &NewORE; 1248 TLI = getSubtarget().getTargetLowering(); 1249 TSI = getSubtarget().getSelectionDAGInfo(); 1250 LibInfo = LibraryInfo; 1251 Context = &MF->getFunction().getContext(); 1252 DA = Divergence; 1253 PSI = PSIin; 1254 BFI = BFIin; 1255 } 1256 1257 SelectionDAG::~SelectionDAG() { 1258 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1259 allnodes_clear(); 1260 OperandRecycler.clear(OperandAllocator); 1261 delete DbgInfo; 1262 } 1263 1264 bool SelectionDAG::shouldOptForSize() const { 1265 return MF->getFunction().hasOptSize() || 1266 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1267 } 1268 1269 void SelectionDAG::allnodes_clear() { 1270 assert(&*AllNodes.begin() == &EntryNode); 1271 AllNodes.remove(AllNodes.begin()); 1272 while (!AllNodes.empty()) 1273 DeallocateNode(&AllNodes.front()); 1274 #ifndef NDEBUG 1275 NextPersistentId = 0; 1276 #endif 1277 } 1278 1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1280 void *&InsertPos) { 1281 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1282 if (N) { 1283 switch (N->getOpcode()) { 1284 default: break; 1285 case ISD::Constant: 1286 case ISD::ConstantFP: 1287 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1288 "debug location. Use another overload."); 1289 } 1290 } 1291 return N; 1292 } 1293 1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1295 const SDLoc &DL, void *&InsertPos) { 1296 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1297 if (N) { 1298 switch (N->getOpcode()) { 1299 case ISD::Constant: 1300 case ISD::ConstantFP: 1301 // Erase debug location from the node if the node is used at several 1302 // different places. Do not propagate one location to all uses as it 1303 // will cause a worse single stepping debugging experience. 1304 if (N->getDebugLoc() != DL.getDebugLoc()) 1305 N->setDebugLoc(DebugLoc()); 1306 break; 1307 default: 1308 // When the node's point of use is located earlier in the instruction 1309 // sequence than its prior point of use, update its debug info to the 1310 // earlier location. 1311 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1312 N->setDebugLoc(DL.getDebugLoc()); 1313 break; 1314 } 1315 } 1316 return N; 1317 } 1318 1319 void SelectionDAG::clear() { 1320 allnodes_clear(); 1321 OperandRecycler.clear(OperandAllocator); 1322 OperandAllocator.Reset(); 1323 CSEMap.clear(); 1324 1325 ExtendedValueTypeNodes.clear(); 1326 ExternalSymbols.clear(); 1327 TargetExternalSymbols.clear(); 1328 MCSymbols.clear(); 1329 SDCallSiteDbgInfo.clear(); 1330 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1331 static_cast<CondCodeSDNode*>(nullptr)); 1332 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1333 static_cast<SDNode*>(nullptr)); 1334 1335 EntryNode.UseList = nullptr; 1336 InsertNode(&EntryNode); 1337 Root = getEntryNode(); 1338 DbgInfo->clear(); 1339 } 1340 1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1342 return VT.bitsGT(Op.getValueType()) 1343 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1344 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1345 } 1346 1347 std::pair<SDValue, SDValue> 1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1349 const SDLoc &DL, EVT VT) { 1350 assert(!VT.bitsEq(Op.getValueType()) && 1351 "Strict no-op FP extend/round not allowed."); 1352 SDValue Res = 1353 VT.bitsGT(Op.getValueType()) 1354 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1355 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1356 {Chain, Op, getIntPtrConstant(0, DL)}); 1357 1358 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1359 } 1360 1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1362 return VT.bitsGT(Op.getValueType()) ? 1363 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1364 getNode(ISD::TRUNCATE, DL, VT, Op); 1365 } 1366 1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1368 return VT.bitsGT(Op.getValueType()) ? 1369 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1370 getNode(ISD::TRUNCATE, DL, VT, Op); 1371 } 1372 1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1374 return VT.bitsGT(Op.getValueType()) ? 1375 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1376 getNode(ISD::TRUNCATE, DL, VT, Op); 1377 } 1378 1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1380 EVT OpVT) { 1381 if (VT.bitsLE(Op.getValueType())) 1382 return getNode(ISD::TRUNCATE, SL, VT, Op); 1383 1384 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1385 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1386 } 1387 1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1389 EVT OpVT = Op.getValueType(); 1390 assert(VT.isInteger() && OpVT.isInteger() && 1391 "Cannot getZeroExtendInReg FP types"); 1392 assert(VT.isVector() == OpVT.isVector() && 1393 "getZeroExtendInReg type should be vector iff the operand " 1394 "type is vector!"); 1395 assert((!VT.isVector() || 1396 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1397 "Vector element counts must match in getZeroExtendInReg"); 1398 assert(VT.bitsLE(OpVT) && "Not extending!"); 1399 if (OpVT == VT) 1400 return Op; 1401 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1402 VT.getScalarSizeInBits()); 1403 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1404 } 1405 1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1407 // Only unsigned pointer semantics are supported right now. In the future this 1408 // might delegate to TLI to check pointer signedness. 1409 return getZExtOrTrunc(Op, DL, VT); 1410 } 1411 1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1413 // Only unsigned pointer semantics are supported right now. In the future this 1414 // might delegate to TLI to check pointer signedness. 1415 return getZeroExtendInReg(Op, DL, VT); 1416 } 1417 1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1420 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1421 } 1422 1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1424 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1425 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1426 } 1427 1428 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1429 EVT OpVT) { 1430 if (!V) 1431 return getConstant(0, DL, VT); 1432 1433 switch (TLI->getBooleanContents(OpVT)) { 1434 case TargetLowering::ZeroOrOneBooleanContent: 1435 case TargetLowering::UndefinedBooleanContent: 1436 return getConstant(1, DL, VT); 1437 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1438 return getAllOnesConstant(DL, VT); 1439 } 1440 llvm_unreachable("Unexpected boolean content enum!"); 1441 } 1442 1443 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1444 bool isT, bool isO) { 1445 EVT EltVT = VT.getScalarType(); 1446 assert((EltVT.getSizeInBits() >= 64 || 1447 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1448 "getConstant with a uint64_t value that doesn't fit in the type!"); 1449 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1450 } 1451 1452 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1453 bool isT, bool isO) { 1454 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1455 } 1456 1457 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1458 EVT VT, bool isT, bool isO) { 1459 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1460 1461 EVT EltVT = VT.getScalarType(); 1462 const ConstantInt *Elt = &Val; 1463 1464 // In some cases the vector type is legal but the element type is illegal and 1465 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1466 // inserted value (the type does not need to match the vector element type). 1467 // Any extra bits introduced will be truncated away. 1468 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1469 TargetLowering::TypePromoteInteger) { 1470 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1471 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1472 Elt = ConstantInt::get(*getContext(), NewVal); 1473 } 1474 // In other cases the element type is illegal and needs to be expanded, for 1475 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1476 // the value into n parts and use a vector type with n-times the elements. 1477 // Then bitcast to the type requested. 1478 // Legalizing constants too early makes the DAGCombiner's job harder so we 1479 // only legalize if the DAG tells us we must produce legal types. 1480 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1481 TLI->getTypeAction(*getContext(), EltVT) == 1482 TargetLowering::TypeExpandInteger) { 1483 const APInt &NewVal = Elt->getValue(); 1484 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1485 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1486 1487 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1488 if (VT.isScalableVector()) { 1489 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1490 "Can only handle an even split!"); 1491 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1492 1493 SmallVector<SDValue, 2> ScalarParts; 1494 for (unsigned i = 0; i != Parts; ++i) 1495 ScalarParts.push_back(getConstant( 1496 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1497 ViaEltVT, isT, isO)); 1498 1499 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1500 } 1501 1502 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1503 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1504 1505 // Check the temporary vector is the correct size. If this fails then 1506 // getTypeToTransformTo() probably returned a type whose size (in bits) 1507 // isn't a power-of-2 factor of the requested type size. 1508 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1509 1510 SmallVector<SDValue, 2> EltParts; 1511 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1512 EltParts.push_back(getConstant( 1513 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1514 ViaEltVT, isT, isO)); 1515 1516 // EltParts is currently in little endian order. If we actually want 1517 // big-endian order then reverse it now. 1518 if (getDataLayout().isBigEndian()) 1519 std::reverse(EltParts.begin(), EltParts.end()); 1520 1521 // The elements must be reversed when the element order is different 1522 // to the endianness of the elements (because the BITCAST is itself a 1523 // vector shuffle in this situation). However, we do not need any code to 1524 // perform this reversal because getConstant() is producing a vector 1525 // splat. 1526 // This situation occurs in MIPS MSA. 1527 1528 SmallVector<SDValue, 8> Ops; 1529 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1530 llvm::append_range(Ops, EltParts); 1531 1532 SDValue V = 1533 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1534 return V; 1535 } 1536 1537 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1538 "APInt size does not match type size!"); 1539 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1540 FoldingSetNodeID ID; 1541 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1542 ID.AddPointer(Elt); 1543 ID.AddBoolean(isO); 1544 void *IP = nullptr; 1545 SDNode *N = nullptr; 1546 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1547 if (!VT.isVector()) 1548 return SDValue(N, 0); 1549 1550 if (!N) { 1551 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1552 CSEMap.InsertNode(N, IP); 1553 InsertNode(N); 1554 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1555 } 1556 1557 SDValue Result(N, 0); 1558 if (VT.isScalableVector()) 1559 Result = getSplatVector(VT, DL, Result); 1560 else if (VT.isVector()) 1561 Result = getSplatBuildVector(VT, DL, Result); 1562 1563 return Result; 1564 } 1565 1566 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1567 bool isTarget) { 1568 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1569 } 1570 1571 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1572 const SDLoc &DL, bool LegalTypes) { 1573 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1574 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1575 return getConstant(Val, DL, ShiftVT); 1576 } 1577 1578 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1579 bool isTarget) { 1580 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1581 } 1582 1583 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1584 bool isTarget) { 1585 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1586 } 1587 1588 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1589 EVT VT, bool isTarget) { 1590 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1591 1592 EVT EltVT = VT.getScalarType(); 1593 1594 // Do the map lookup using the actual bit pattern for the floating point 1595 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1596 // we don't have issues with SNANs. 1597 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1598 FoldingSetNodeID ID; 1599 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1600 ID.AddPointer(&V); 1601 void *IP = nullptr; 1602 SDNode *N = nullptr; 1603 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1604 if (!VT.isVector()) 1605 return SDValue(N, 0); 1606 1607 if (!N) { 1608 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1609 CSEMap.InsertNode(N, IP); 1610 InsertNode(N); 1611 } 1612 1613 SDValue Result(N, 0); 1614 if (VT.isScalableVector()) 1615 Result = getSplatVector(VT, DL, Result); 1616 else if (VT.isVector()) 1617 Result = getSplatBuildVector(VT, DL, Result); 1618 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1619 return Result; 1620 } 1621 1622 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1623 bool isTarget) { 1624 EVT EltVT = VT.getScalarType(); 1625 if (EltVT == MVT::f32) 1626 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1627 if (EltVT == MVT::f64) 1628 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1629 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1630 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1631 bool Ignored; 1632 APFloat APF = APFloat(Val); 1633 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1634 &Ignored); 1635 return getConstantFP(APF, DL, VT, isTarget); 1636 } 1637 llvm_unreachable("Unsupported type in getConstantFP"); 1638 } 1639 1640 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1641 EVT VT, int64_t Offset, bool isTargetGA, 1642 unsigned TargetFlags) { 1643 assert((TargetFlags == 0 || isTargetGA) && 1644 "Cannot set target flags on target-independent globals"); 1645 1646 // Truncate (with sign-extension) the offset value to the pointer size. 1647 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1648 if (BitWidth < 64) 1649 Offset = SignExtend64(Offset, BitWidth); 1650 1651 unsigned Opc; 1652 if (GV->isThreadLocal()) 1653 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1654 else 1655 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1656 1657 FoldingSetNodeID ID; 1658 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1659 ID.AddPointer(GV); 1660 ID.AddInteger(Offset); 1661 ID.AddInteger(TargetFlags); 1662 void *IP = nullptr; 1663 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1664 return SDValue(E, 0); 1665 1666 auto *N = newSDNode<GlobalAddressSDNode>( 1667 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1668 CSEMap.InsertNode(N, IP); 1669 InsertNode(N); 1670 return SDValue(N, 0); 1671 } 1672 1673 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1674 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1675 FoldingSetNodeID ID; 1676 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1677 ID.AddInteger(FI); 1678 void *IP = nullptr; 1679 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1680 return SDValue(E, 0); 1681 1682 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1683 CSEMap.InsertNode(N, IP); 1684 InsertNode(N); 1685 return SDValue(N, 0); 1686 } 1687 1688 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1689 unsigned TargetFlags) { 1690 assert((TargetFlags == 0 || isTarget) && 1691 "Cannot set target flags on target-independent jump tables"); 1692 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1693 FoldingSetNodeID ID; 1694 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1695 ID.AddInteger(JTI); 1696 ID.AddInteger(TargetFlags); 1697 void *IP = nullptr; 1698 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1699 return SDValue(E, 0); 1700 1701 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1702 CSEMap.InsertNode(N, IP); 1703 InsertNode(N); 1704 return SDValue(N, 0); 1705 } 1706 1707 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1708 MaybeAlign Alignment, int Offset, 1709 bool isTarget, unsigned TargetFlags) { 1710 assert((TargetFlags == 0 || isTarget) && 1711 "Cannot set target flags on target-independent globals"); 1712 if (!Alignment) 1713 Alignment = shouldOptForSize() 1714 ? getDataLayout().getABITypeAlign(C->getType()) 1715 : getDataLayout().getPrefTypeAlign(C->getType()); 1716 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1717 FoldingSetNodeID ID; 1718 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1719 ID.AddInteger(Alignment->value()); 1720 ID.AddInteger(Offset); 1721 ID.AddPointer(C); 1722 ID.AddInteger(TargetFlags); 1723 void *IP = nullptr; 1724 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1725 return SDValue(E, 0); 1726 1727 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1728 TargetFlags); 1729 CSEMap.InsertNode(N, IP); 1730 InsertNode(N); 1731 SDValue V = SDValue(N, 0); 1732 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1733 return V; 1734 } 1735 1736 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1737 MaybeAlign Alignment, int Offset, 1738 bool isTarget, unsigned TargetFlags) { 1739 assert((TargetFlags == 0 || isTarget) && 1740 "Cannot set target flags on target-independent globals"); 1741 if (!Alignment) 1742 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1743 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1744 FoldingSetNodeID ID; 1745 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1746 ID.AddInteger(Alignment->value()); 1747 ID.AddInteger(Offset); 1748 C->addSelectionDAGCSEId(ID); 1749 ID.AddInteger(TargetFlags); 1750 void *IP = nullptr; 1751 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1752 return SDValue(E, 0); 1753 1754 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1755 TargetFlags); 1756 CSEMap.InsertNode(N, IP); 1757 InsertNode(N); 1758 return SDValue(N, 0); 1759 } 1760 1761 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1762 unsigned TargetFlags) { 1763 FoldingSetNodeID ID; 1764 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1765 ID.AddInteger(Index); 1766 ID.AddInteger(Offset); 1767 ID.AddInteger(TargetFlags); 1768 void *IP = nullptr; 1769 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1770 return SDValue(E, 0); 1771 1772 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1773 CSEMap.InsertNode(N, IP); 1774 InsertNode(N); 1775 return SDValue(N, 0); 1776 } 1777 1778 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1779 FoldingSetNodeID ID; 1780 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1781 ID.AddPointer(MBB); 1782 void *IP = nullptr; 1783 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1784 return SDValue(E, 0); 1785 1786 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1787 CSEMap.InsertNode(N, IP); 1788 InsertNode(N); 1789 return SDValue(N, 0); 1790 } 1791 1792 SDValue SelectionDAG::getValueType(EVT VT) { 1793 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1794 ValueTypeNodes.size()) 1795 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1796 1797 SDNode *&N = VT.isExtended() ? 1798 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1799 1800 if (N) return SDValue(N, 0); 1801 N = newSDNode<VTSDNode>(VT); 1802 InsertNode(N); 1803 return SDValue(N, 0); 1804 } 1805 1806 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1807 SDNode *&N = ExternalSymbols[Sym]; 1808 if (N) return SDValue(N, 0); 1809 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1810 InsertNode(N); 1811 return SDValue(N, 0); 1812 } 1813 1814 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1815 SDNode *&N = MCSymbols[Sym]; 1816 if (N) 1817 return SDValue(N, 0); 1818 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1819 InsertNode(N); 1820 return SDValue(N, 0); 1821 } 1822 1823 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1824 unsigned TargetFlags) { 1825 SDNode *&N = 1826 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1827 if (N) return SDValue(N, 0); 1828 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1829 InsertNode(N); 1830 return SDValue(N, 0); 1831 } 1832 1833 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1834 if ((unsigned)Cond >= CondCodeNodes.size()) 1835 CondCodeNodes.resize(Cond+1); 1836 1837 if (!CondCodeNodes[Cond]) { 1838 auto *N = newSDNode<CondCodeSDNode>(Cond); 1839 CondCodeNodes[Cond] = N; 1840 InsertNode(N); 1841 } 1842 1843 return SDValue(CondCodeNodes[Cond], 0); 1844 } 1845 1846 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1847 APInt One(ResVT.getScalarSizeInBits(), 1); 1848 return getStepVector(DL, ResVT, One); 1849 } 1850 1851 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1852 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1853 if (ResVT.isScalableVector()) 1854 return getNode( 1855 ISD::STEP_VECTOR, DL, ResVT, 1856 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1857 1858 SmallVector<SDValue, 16> OpsStepConstants; 1859 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1860 OpsStepConstants.push_back( 1861 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1862 return getBuildVector(ResVT, DL, OpsStepConstants); 1863 } 1864 1865 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1866 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1867 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1868 std::swap(N1, N2); 1869 ShuffleVectorSDNode::commuteMask(M); 1870 } 1871 1872 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1873 SDValue N2, ArrayRef<int> Mask) { 1874 assert(VT.getVectorNumElements() == Mask.size() && 1875 "Must have the same number of vector elements as mask elements!"); 1876 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1877 "Invalid VECTOR_SHUFFLE"); 1878 1879 // Canonicalize shuffle undef, undef -> undef 1880 if (N1.isUndef() && N2.isUndef()) 1881 return getUNDEF(VT); 1882 1883 // Validate that all indices in Mask are within the range of the elements 1884 // input to the shuffle. 1885 int NElts = Mask.size(); 1886 assert(llvm::all_of(Mask, 1887 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1888 "Index out of range"); 1889 1890 // Copy the mask so we can do any needed cleanup. 1891 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1892 1893 // Canonicalize shuffle v, v -> v, undef 1894 if (N1 == N2) { 1895 N2 = getUNDEF(VT); 1896 for (int i = 0; i != NElts; ++i) 1897 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1898 } 1899 1900 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1901 if (N1.isUndef()) 1902 commuteShuffle(N1, N2, MaskVec); 1903 1904 if (TLI->hasVectorBlend()) { 1905 // If shuffling a splat, try to blend the splat instead. We do this here so 1906 // that even when this arises during lowering we don't have to re-handle it. 1907 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1908 BitVector UndefElements; 1909 SDValue Splat = BV->getSplatValue(&UndefElements); 1910 if (!Splat) 1911 return; 1912 1913 for (int i = 0; i < NElts; ++i) { 1914 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1915 continue; 1916 1917 // If this input comes from undef, mark it as such. 1918 if (UndefElements[MaskVec[i] - Offset]) { 1919 MaskVec[i] = -1; 1920 continue; 1921 } 1922 1923 // If we can blend a non-undef lane, use that instead. 1924 if (!UndefElements[i]) 1925 MaskVec[i] = i + Offset; 1926 } 1927 }; 1928 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1929 BlendSplat(N1BV, 0); 1930 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1931 BlendSplat(N2BV, NElts); 1932 } 1933 1934 // Canonicalize all index into lhs, -> shuffle lhs, undef 1935 // Canonicalize all index into rhs, -> shuffle rhs, undef 1936 bool AllLHS = true, AllRHS = true; 1937 bool N2Undef = N2.isUndef(); 1938 for (int i = 0; i != NElts; ++i) { 1939 if (MaskVec[i] >= NElts) { 1940 if (N2Undef) 1941 MaskVec[i] = -1; 1942 else 1943 AllLHS = false; 1944 } else if (MaskVec[i] >= 0) { 1945 AllRHS = false; 1946 } 1947 } 1948 if (AllLHS && AllRHS) 1949 return getUNDEF(VT); 1950 if (AllLHS && !N2Undef) 1951 N2 = getUNDEF(VT); 1952 if (AllRHS) { 1953 N1 = getUNDEF(VT); 1954 commuteShuffle(N1, N2, MaskVec); 1955 } 1956 // Reset our undef status after accounting for the mask. 1957 N2Undef = N2.isUndef(); 1958 // Re-check whether both sides ended up undef. 1959 if (N1.isUndef() && N2Undef) 1960 return getUNDEF(VT); 1961 1962 // If Identity shuffle return that node. 1963 bool Identity = true, AllSame = true; 1964 for (int i = 0; i != NElts; ++i) { 1965 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1966 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1967 } 1968 if (Identity && NElts) 1969 return N1; 1970 1971 // Shuffling a constant splat doesn't change the result. 1972 if (N2Undef) { 1973 SDValue V = N1; 1974 1975 // Look through any bitcasts. We check that these don't change the number 1976 // (and size) of elements and just changes their types. 1977 while (V.getOpcode() == ISD::BITCAST) 1978 V = V->getOperand(0); 1979 1980 // A splat should always show up as a build vector node. 1981 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1982 BitVector UndefElements; 1983 SDValue Splat = BV->getSplatValue(&UndefElements); 1984 // If this is a splat of an undef, shuffling it is also undef. 1985 if (Splat && Splat.isUndef()) 1986 return getUNDEF(VT); 1987 1988 bool SameNumElts = 1989 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1990 1991 // We only have a splat which can skip shuffles if there is a splatted 1992 // value and no undef lanes rearranged by the shuffle. 1993 if (Splat && UndefElements.none()) { 1994 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1995 // number of elements match or the value splatted is a zero constant. 1996 if (SameNumElts) 1997 return N1; 1998 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1999 if (C->isZero()) 2000 return N1; 2001 } 2002 2003 // If the shuffle itself creates a splat, build the vector directly. 2004 if (AllSame && SameNumElts) { 2005 EVT BuildVT = BV->getValueType(0); 2006 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2007 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2008 2009 // We may have jumped through bitcasts, so the type of the 2010 // BUILD_VECTOR may not match the type of the shuffle. 2011 if (BuildVT != VT) 2012 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2013 return NewBV; 2014 } 2015 } 2016 } 2017 2018 FoldingSetNodeID ID; 2019 SDValue Ops[2] = { N1, N2 }; 2020 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2021 for (int i = 0; i != NElts; ++i) 2022 ID.AddInteger(MaskVec[i]); 2023 2024 void* IP = nullptr; 2025 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2026 return SDValue(E, 0); 2027 2028 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2029 // SDNode doesn't have access to it. This memory will be "leaked" when 2030 // the node is deallocated, but recovered when the NodeAllocator is released. 2031 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2032 llvm::copy(MaskVec, MaskAlloc); 2033 2034 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2035 dl.getDebugLoc(), MaskAlloc); 2036 createOperands(N, Ops); 2037 2038 CSEMap.InsertNode(N, IP); 2039 InsertNode(N); 2040 SDValue V = SDValue(N, 0); 2041 NewSDValueDbgMsg(V, "Creating new node: ", this); 2042 return V; 2043 } 2044 2045 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2046 EVT VT = SV.getValueType(0); 2047 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2048 ShuffleVectorSDNode::commuteMask(MaskVec); 2049 2050 SDValue Op0 = SV.getOperand(0); 2051 SDValue Op1 = SV.getOperand(1); 2052 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2053 } 2054 2055 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2056 FoldingSetNodeID ID; 2057 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2058 ID.AddInteger(RegNo); 2059 void *IP = nullptr; 2060 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2061 return SDValue(E, 0); 2062 2063 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2064 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2065 CSEMap.InsertNode(N, IP); 2066 InsertNode(N); 2067 return SDValue(N, 0); 2068 } 2069 2070 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2071 FoldingSetNodeID ID; 2072 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2073 ID.AddPointer(RegMask); 2074 void *IP = nullptr; 2075 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2076 return SDValue(E, 0); 2077 2078 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2079 CSEMap.InsertNode(N, IP); 2080 InsertNode(N); 2081 return SDValue(N, 0); 2082 } 2083 2084 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2085 MCSymbol *Label) { 2086 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2087 } 2088 2089 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2090 SDValue Root, MCSymbol *Label) { 2091 FoldingSetNodeID ID; 2092 SDValue Ops[] = { Root }; 2093 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2094 ID.AddPointer(Label); 2095 void *IP = nullptr; 2096 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2097 return SDValue(E, 0); 2098 2099 auto *N = 2100 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2101 createOperands(N, Ops); 2102 2103 CSEMap.InsertNode(N, IP); 2104 InsertNode(N); 2105 return SDValue(N, 0); 2106 } 2107 2108 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2109 int64_t Offset, bool isTarget, 2110 unsigned TargetFlags) { 2111 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2112 2113 FoldingSetNodeID ID; 2114 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2115 ID.AddPointer(BA); 2116 ID.AddInteger(Offset); 2117 ID.AddInteger(TargetFlags); 2118 void *IP = nullptr; 2119 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2120 return SDValue(E, 0); 2121 2122 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2123 CSEMap.InsertNode(N, IP); 2124 InsertNode(N); 2125 return SDValue(N, 0); 2126 } 2127 2128 SDValue SelectionDAG::getSrcValue(const Value *V) { 2129 FoldingSetNodeID ID; 2130 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2131 ID.AddPointer(V); 2132 2133 void *IP = nullptr; 2134 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2135 return SDValue(E, 0); 2136 2137 auto *N = newSDNode<SrcValueSDNode>(V); 2138 CSEMap.InsertNode(N, IP); 2139 InsertNode(N); 2140 return SDValue(N, 0); 2141 } 2142 2143 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2144 FoldingSetNodeID ID; 2145 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2146 ID.AddPointer(MD); 2147 2148 void *IP = nullptr; 2149 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2150 return SDValue(E, 0); 2151 2152 auto *N = newSDNode<MDNodeSDNode>(MD); 2153 CSEMap.InsertNode(N, IP); 2154 InsertNode(N); 2155 return SDValue(N, 0); 2156 } 2157 2158 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2159 if (VT == V.getValueType()) 2160 return V; 2161 2162 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2163 } 2164 2165 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2166 unsigned SrcAS, unsigned DestAS) { 2167 SDValue Ops[] = {Ptr}; 2168 FoldingSetNodeID ID; 2169 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2170 ID.AddInteger(SrcAS); 2171 ID.AddInteger(DestAS); 2172 2173 void *IP = nullptr; 2174 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2175 return SDValue(E, 0); 2176 2177 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2178 VT, SrcAS, DestAS); 2179 createOperands(N, Ops); 2180 2181 CSEMap.InsertNode(N, IP); 2182 InsertNode(N); 2183 return SDValue(N, 0); 2184 } 2185 2186 SDValue SelectionDAG::getFreeze(SDValue V) { 2187 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2188 } 2189 2190 /// getShiftAmountOperand - Return the specified value casted to 2191 /// the target's desired shift amount type. 2192 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2193 EVT OpTy = Op.getValueType(); 2194 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2195 if (OpTy == ShTy || OpTy.isVector()) return Op; 2196 2197 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2198 } 2199 2200 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2201 SDLoc dl(Node); 2202 const TargetLowering &TLI = getTargetLoweringInfo(); 2203 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2204 EVT VT = Node->getValueType(0); 2205 SDValue Tmp1 = Node->getOperand(0); 2206 SDValue Tmp2 = Node->getOperand(1); 2207 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2208 2209 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2210 Tmp2, MachinePointerInfo(V)); 2211 SDValue VAList = VAListLoad; 2212 2213 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2214 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2215 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2216 2217 VAList = 2218 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2219 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2220 } 2221 2222 // Increment the pointer, VAList, to the next vaarg 2223 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2224 getConstant(getDataLayout().getTypeAllocSize( 2225 VT.getTypeForEVT(*getContext())), 2226 dl, VAList.getValueType())); 2227 // Store the incremented VAList to the legalized pointer 2228 Tmp1 = 2229 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2230 // Load the actual argument out of the pointer VAList 2231 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2232 } 2233 2234 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2235 SDLoc dl(Node); 2236 const TargetLowering &TLI = getTargetLoweringInfo(); 2237 // This defaults to loading a pointer from the input and storing it to the 2238 // output, returning the chain. 2239 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2240 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2241 SDValue Tmp1 = 2242 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2243 Node->getOperand(2), MachinePointerInfo(VS)); 2244 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2245 MachinePointerInfo(VD)); 2246 } 2247 2248 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2249 const DataLayout &DL = getDataLayout(); 2250 Type *Ty = VT.getTypeForEVT(*getContext()); 2251 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2252 2253 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2254 return RedAlign; 2255 2256 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2257 const Align StackAlign = TFI->getStackAlign(); 2258 2259 // See if we can choose a smaller ABI alignment in cases where it's an 2260 // illegal vector type that will get broken down. 2261 if (RedAlign > StackAlign) { 2262 EVT IntermediateVT; 2263 MVT RegisterVT; 2264 unsigned NumIntermediates; 2265 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2266 NumIntermediates, RegisterVT); 2267 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2268 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2269 if (RedAlign2 < RedAlign) 2270 RedAlign = RedAlign2; 2271 } 2272 2273 return RedAlign; 2274 } 2275 2276 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2277 MachineFrameInfo &MFI = MF->getFrameInfo(); 2278 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2279 int StackID = 0; 2280 if (Bytes.isScalable()) 2281 StackID = TFI->getStackIDForScalableVectors(); 2282 // The stack id gives an indication of whether the object is scalable or 2283 // not, so it's safe to pass in the minimum size here. 2284 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2285 false, nullptr, StackID); 2286 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2287 } 2288 2289 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2290 Type *Ty = VT.getTypeForEVT(*getContext()); 2291 Align StackAlign = 2292 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2293 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2294 } 2295 2296 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2297 TypeSize VT1Size = VT1.getStoreSize(); 2298 TypeSize VT2Size = VT2.getStoreSize(); 2299 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2300 "Don't know how to choose the maximum size when creating a stack " 2301 "temporary"); 2302 TypeSize Bytes = 2303 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2304 2305 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2306 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2307 const DataLayout &DL = getDataLayout(); 2308 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2309 return CreateStackTemporary(Bytes, Align); 2310 } 2311 2312 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2313 ISD::CondCode Cond, const SDLoc &dl) { 2314 EVT OpVT = N1.getValueType(); 2315 2316 // These setcc operations always fold. 2317 switch (Cond) { 2318 default: break; 2319 case ISD::SETFALSE: 2320 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2321 case ISD::SETTRUE: 2322 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2323 2324 case ISD::SETOEQ: 2325 case ISD::SETOGT: 2326 case ISD::SETOGE: 2327 case ISD::SETOLT: 2328 case ISD::SETOLE: 2329 case ISD::SETONE: 2330 case ISD::SETO: 2331 case ISD::SETUO: 2332 case ISD::SETUEQ: 2333 case ISD::SETUNE: 2334 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2335 break; 2336 } 2337 2338 if (OpVT.isInteger()) { 2339 // For EQ and NE, we can always pick a value for the undef to make the 2340 // predicate pass or fail, so we can return undef. 2341 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2342 // icmp eq/ne X, undef -> undef. 2343 if ((N1.isUndef() || N2.isUndef()) && 2344 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2345 return getUNDEF(VT); 2346 2347 // If both operands are undef, we can return undef for int comparison. 2348 // icmp undef, undef -> undef. 2349 if (N1.isUndef() && N2.isUndef()) 2350 return getUNDEF(VT); 2351 2352 // icmp X, X -> true/false 2353 // icmp X, undef -> true/false because undef could be X. 2354 if (N1 == N2) 2355 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2356 } 2357 2358 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2359 const APInt &C2 = N2C->getAPIntValue(); 2360 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2361 const APInt &C1 = N1C->getAPIntValue(); 2362 2363 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2364 dl, VT, OpVT); 2365 } 2366 } 2367 2368 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2369 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2370 2371 if (N1CFP && N2CFP) { 2372 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2373 switch (Cond) { 2374 default: break; 2375 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2376 return getUNDEF(VT); 2377 LLVM_FALLTHROUGH; 2378 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2379 OpVT); 2380 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2381 return getUNDEF(VT); 2382 LLVM_FALLTHROUGH; 2383 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2384 R==APFloat::cmpLessThan, dl, VT, 2385 OpVT); 2386 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2387 return getUNDEF(VT); 2388 LLVM_FALLTHROUGH; 2389 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2390 OpVT); 2391 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2392 return getUNDEF(VT); 2393 LLVM_FALLTHROUGH; 2394 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2395 VT, OpVT); 2396 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2397 return getUNDEF(VT); 2398 LLVM_FALLTHROUGH; 2399 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2400 R==APFloat::cmpEqual, dl, VT, 2401 OpVT); 2402 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2403 return getUNDEF(VT); 2404 LLVM_FALLTHROUGH; 2405 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2406 R==APFloat::cmpEqual, dl, VT, OpVT); 2407 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2408 OpVT); 2409 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2410 OpVT); 2411 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2412 R==APFloat::cmpEqual, dl, VT, 2413 OpVT); 2414 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2415 OpVT); 2416 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2417 R==APFloat::cmpLessThan, dl, VT, 2418 OpVT); 2419 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2420 R==APFloat::cmpUnordered, dl, VT, 2421 OpVT); 2422 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2423 VT, OpVT); 2424 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2425 OpVT); 2426 } 2427 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2428 // Ensure that the constant occurs on the RHS. 2429 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2430 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2431 return SDValue(); 2432 return getSetCC(dl, VT, N2, N1, SwappedCond); 2433 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2434 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2435 // If an operand is known to be a nan (or undef that could be a nan), we can 2436 // fold it. 2437 // Choosing NaN for the undef will always make unordered comparison succeed 2438 // and ordered comparison fails. 2439 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2440 switch (ISD::getUnorderedFlavor(Cond)) { 2441 default: 2442 llvm_unreachable("Unknown flavor!"); 2443 case 0: // Known false. 2444 return getBoolConstant(false, dl, VT, OpVT); 2445 case 1: // Known true. 2446 return getBoolConstant(true, dl, VT, OpVT); 2447 case 2: // Undefined. 2448 return getUNDEF(VT); 2449 } 2450 } 2451 2452 // Could not fold it. 2453 return SDValue(); 2454 } 2455 2456 /// See if the specified operand can be simplified with the knowledge that only 2457 /// the bits specified by DemandedBits are used. 2458 /// TODO: really we should be making this into the DAG equivalent of 2459 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2460 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2461 EVT VT = V.getValueType(); 2462 2463 if (VT.isScalableVector()) 2464 return SDValue(); 2465 2466 APInt DemandedElts = VT.isVector() 2467 ? APInt::getAllOnes(VT.getVectorNumElements()) 2468 : APInt(1, 1); 2469 return GetDemandedBits(V, DemandedBits, DemandedElts); 2470 } 2471 2472 /// See if the specified operand can be simplified with the knowledge that only 2473 /// the bits specified by DemandedBits are used in the elements specified by 2474 /// DemandedElts. 2475 /// TODO: really we should be making this into the DAG equivalent of 2476 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2477 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2478 const APInt &DemandedElts) { 2479 switch (V.getOpcode()) { 2480 default: 2481 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2482 *this); 2483 case ISD::Constant: { 2484 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2485 APInt NewVal = CVal & DemandedBits; 2486 if (NewVal != CVal) 2487 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2488 break; 2489 } 2490 case ISD::SRL: 2491 // Only look at single-use SRLs. 2492 if (!V.getNode()->hasOneUse()) 2493 break; 2494 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2495 // See if we can recursively simplify the LHS. 2496 unsigned Amt = RHSC->getZExtValue(); 2497 2498 // Watch out for shift count overflow though. 2499 if (Amt >= DemandedBits.getBitWidth()) 2500 break; 2501 APInt SrcDemandedBits = DemandedBits << Amt; 2502 if (SDValue SimplifyLHS = 2503 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2504 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2505 V.getOperand(1)); 2506 } 2507 break; 2508 } 2509 return SDValue(); 2510 } 2511 2512 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2513 /// use this predicate to simplify operations downstream. 2514 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2515 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2516 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2517 } 2518 2519 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2520 /// this predicate to simplify operations downstream. Mask is known to be zero 2521 /// for bits that V cannot have. 2522 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2523 unsigned Depth) const { 2524 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2525 } 2526 2527 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2528 /// DemandedElts. We use this predicate to simplify operations downstream. 2529 /// Mask is known to be zero for bits that V cannot have. 2530 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2531 const APInt &DemandedElts, 2532 unsigned Depth) const { 2533 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2534 } 2535 2536 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2537 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2538 unsigned Depth) const { 2539 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2540 } 2541 2542 /// isSplatValue - Return true if the vector V has the same value 2543 /// across all DemandedElts. For scalable vectors it does not make 2544 /// sense to specify which elements are demanded or undefined, therefore 2545 /// they are simply ignored. 2546 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2547 APInt &UndefElts, unsigned Depth) const { 2548 unsigned Opcode = V.getOpcode(); 2549 EVT VT = V.getValueType(); 2550 assert(VT.isVector() && "Vector type expected"); 2551 2552 if (!VT.isScalableVector() && !DemandedElts) 2553 return false; // No demanded elts, better to assume we don't know anything. 2554 2555 if (Depth >= MaxRecursionDepth) 2556 return false; // Limit search depth. 2557 2558 // Deal with some common cases here that work for both fixed and scalable 2559 // vector types. 2560 switch (Opcode) { 2561 case ISD::SPLAT_VECTOR: 2562 UndefElts = V.getOperand(0).isUndef() 2563 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2564 : APInt(DemandedElts.getBitWidth(), 0); 2565 return true; 2566 case ISD::ADD: 2567 case ISD::SUB: 2568 case ISD::AND: 2569 case ISD::XOR: 2570 case ISD::OR: { 2571 APInt UndefLHS, UndefRHS; 2572 SDValue LHS = V.getOperand(0); 2573 SDValue RHS = V.getOperand(1); 2574 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2575 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2576 UndefElts = UndefLHS | UndefRHS; 2577 return true; 2578 } 2579 return false; 2580 } 2581 case ISD::ABS: 2582 case ISD::TRUNCATE: 2583 case ISD::SIGN_EXTEND: 2584 case ISD::ZERO_EXTEND: 2585 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2586 default: 2587 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2588 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2589 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth); 2590 break; 2591 } 2592 2593 // We don't support other cases than those above for scalable vectors at 2594 // the moment. 2595 if (VT.isScalableVector()) 2596 return false; 2597 2598 unsigned NumElts = VT.getVectorNumElements(); 2599 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2600 UndefElts = APInt::getZero(NumElts); 2601 2602 switch (Opcode) { 2603 case ISD::BUILD_VECTOR: { 2604 SDValue Scl; 2605 for (unsigned i = 0; i != NumElts; ++i) { 2606 SDValue Op = V.getOperand(i); 2607 if (Op.isUndef()) { 2608 UndefElts.setBit(i); 2609 continue; 2610 } 2611 if (!DemandedElts[i]) 2612 continue; 2613 if (Scl && Scl != Op) 2614 return false; 2615 Scl = Op; 2616 } 2617 return true; 2618 } 2619 case ISD::VECTOR_SHUFFLE: { 2620 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2621 APInt DemandedLHS = APInt::getNullValue(NumElts); 2622 APInt DemandedRHS = APInt::getNullValue(NumElts); 2623 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2624 for (int i = 0; i != (int)NumElts; ++i) { 2625 int M = Mask[i]; 2626 if (M < 0) { 2627 UndefElts.setBit(i); 2628 continue; 2629 } 2630 if (!DemandedElts[i]) 2631 continue; 2632 if (M < (int)NumElts) 2633 DemandedLHS.setBit(M); 2634 else 2635 DemandedRHS.setBit(M - NumElts); 2636 } 2637 2638 // If we aren't demanding either op, assume there's no splat. 2639 // If we are demanding both ops, assume there's no splat. 2640 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2641 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2642 return false; 2643 2644 // See if the demanded elts of the source op is a splat or we only demand 2645 // one element, which should always be a splat. 2646 // TODO: Handle source ops splats with undefs. 2647 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2648 APInt SrcUndefs; 2649 return (SrcElts.countPopulation() == 1) || 2650 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2651 (SrcElts & SrcUndefs).isZero()); 2652 }; 2653 if (!DemandedLHS.isZero()) 2654 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2655 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2656 } 2657 case ISD::EXTRACT_SUBVECTOR: { 2658 // Offset the demanded elts by the subvector index. 2659 SDValue Src = V.getOperand(0); 2660 // We don't support scalable vectors at the moment. 2661 if (Src.getValueType().isScalableVector()) 2662 return false; 2663 uint64_t Idx = V.getConstantOperandVal(1); 2664 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2665 APInt UndefSrcElts; 2666 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2667 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2668 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2669 return true; 2670 } 2671 break; 2672 } 2673 case ISD::ANY_EXTEND_VECTOR_INREG: 2674 case ISD::SIGN_EXTEND_VECTOR_INREG: 2675 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2676 // Widen the demanded elts by the src element count. 2677 SDValue Src = V.getOperand(0); 2678 // We don't support scalable vectors at the moment. 2679 if (Src.getValueType().isScalableVector()) 2680 return false; 2681 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2682 APInt UndefSrcElts; 2683 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 2684 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2685 UndefElts = UndefSrcElts.truncOrSelf(NumElts); 2686 return true; 2687 } 2688 break; 2689 } 2690 case ISD::BITCAST: { 2691 SDValue Src = V.getOperand(0); 2692 EVT SrcVT = Src.getValueType(); 2693 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2694 unsigned BitWidth = VT.getScalarSizeInBits(); 2695 2696 // Ignore bitcasts from unsupported types. 2697 // TODO: Add fp support? 2698 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2699 break; 2700 2701 // Bitcast 'small element' vector to 'large element' vector. 2702 if ((BitWidth % SrcBitWidth) == 0) { 2703 // See if each sub element is a splat. 2704 unsigned Scale = BitWidth / SrcBitWidth; 2705 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2706 APInt ScaledDemandedElts = 2707 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2708 for (unsigned I = 0; I != Scale; ++I) { 2709 APInt SubUndefElts; 2710 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2711 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2712 SubDemandedElts &= ScaledDemandedElts; 2713 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2714 return false; 2715 // TODO: Add support for merging sub undef elements. 2716 if (SubDemandedElts.isSubsetOf(SubUndefElts)) 2717 return false; 2718 } 2719 return true; 2720 } 2721 break; 2722 } 2723 } 2724 2725 return false; 2726 } 2727 2728 /// Helper wrapper to main isSplatValue function. 2729 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2730 EVT VT = V.getValueType(); 2731 assert(VT.isVector() && "Vector type expected"); 2732 2733 APInt UndefElts; 2734 APInt DemandedElts; 2735 2736 // For now we don't support this with scalable vectors. 2737 if (!VT.isScalableVector()) 2738 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2739 return isSplatValue(V, DemandedElts, UndefElts) && 2740 (AllowUndefs || !UndefElts); 2741 } 2742 2743 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2744 V = peekThroughExtractSubvectors(V); 2745 2746 EVT VT = V.getValueType(); 2747 unsigned Opcode = V.getOpcode(); 2748 switch (Opcode) { 2749 default: { 2750 APInt UndefElts; 2751 APInt DemandedElts; 2752 2753 if (!VT.isScalableVector()) 2754 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2755 2756 if (isSplatValue(V, DemandedElts, UndefElts)) { 2757 if (VT.isScalableVector()) { 2758 // DemandedElts and UndefElts are ignored for scalable vectors, since 2759 // the only supported cases are SPLAT_VECTOR nodes. 2760 SplatIdx = 0; 2761 } else { 2762 // Handle case where all demanded elements are UNDEF. 2763 if (DemandedElts.isSubsetOf(UndefElts)) { 2764 SplatIdx = 0; 2765 return getUNDEF(VT); 2766 } 2767 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2768 } 2769 return V; 2770 } 2771 break; 2772 } 2773 case ISD::SPLAT_VECTOR: 2774 SplatIdx = 0; 2775 return V; 2776 case ISD::VECTOR_SHUFFLE: { 2777 if (VT.isScalableVector()) 2778 return SDValue(); 2779 2780 // Check if this is a shuffle node doing a splat. 2781 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2782 // getTargetVShiftNode currently struggles without the splat source. 2783 auto *SVN = cast<ShuffleVectorSDNode>(V); 2784 if (!SVN->isSplat()) 2785 break; 2786 int Idx = SVN->getSplatIndex(); 2787 int NumElts = V.getValueType().getVectorNumElements(); 2788 SplatIdx = Idx % NumElts; 2789 return V.getOperand(Idx / NumElts); 2790 } 2791 } 2792 2793 return SDValue(); 2794 } 2795 2796 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2797 int SplatIdx; 2798 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2799 EVT SVT = SrcVector.getValueType().getScalarType(); 2800 EVT LegalSVT = SVT; 2801 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2802 if (!SVT.isInteger()) 2803 return SDValue(); 2804 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2805 if (LegalSVT.bitsLT(SVT)) 2806 return SDValue(); 2807 } 2808 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2809 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2810 } 2811 return SDValue(); 2812 } 2813 2814 const APInt * 2815 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2816 const APInt &DemandedElts) const { 2817 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2818 V.getOpcode() == ISD::SRA) && 2819 "Unknown shift node"); 2820 unsigned BitWidth = V.getScalarValueSizeInBits(); 2821 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2822 // Shifting more than the bitwidth is not valid. 2823 const APInt &ShAmt = SA->getAPIntValue(); 2824 if (ShAmt.ult(BitWidth)) 2825 return &ShAmt; 2826 } 2827 return nullptr; 2828 } 2829 2830 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2831 SDValue V, const APInt &DemandedElts) const { 2832 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2833 V.getOpcode() == ISD::SRA) && 2834 "Unknown shift node"); 2835 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2836 return ValidAmt; 2837 unsigned BitWidth = V.getScalarValueSizeInBits(); 2838 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2839 if (!BV) 2840 return nullptr; 2841 const APInt *MinShAmt = nullptr; 2842 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2843 if (!DemandedElts[i]) 2844 continue; 2845 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2846 if (!SA) 2847 return nullptr; 2848 // Shifting more than the bitwidth is not valid. 2849 const APInt &ShAmt = SA->getAPIntValue(); 2850 if (ShAmt.uge(BitWidth)) 2851 return nullptr; 2852 if (MinShAmt && MinShAmt->ule(ShAmt)) 2853 continue; 2854 MinShAmt = &ShAmt; 2855 } 2856 return MinShAmt; 2857 } 2858 2859 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2860 SDValue V, const APInt &DemandedElts) const { 2861 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2862 V.getOpcode() == ISD::SRA) && 2863 "Unknown shift node"); 2864 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2865 return ValidAmt; 2866 unsigned BitWidth = V.getScalarValueSizeInBits(); 2867 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2868 if (!BV) 2869 return nullptr; 2870 const APInt *MaxShAmt = nullptr; 2871 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2872 if (!DemandedElts[i]) 2873 continue; 2874 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2875 if (!SA) 2876 return nullptr; 2877 // Shifting more than the bitwidth is not valid. 2878 const APInt &ShAmt = SA->getAPIntValue(); 2879 if (ShAmt.uge(BitWidth)) 2880 return nullptr; 2881 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2882 continue; 2883 MaxShAmt = &ShAmt; 2884 } 2885 return MaxShAmt; 2886 } 2887 2888 /// Determine which bits of Op are known to be either zero or one and return 2889 /// them in Known. For vectors, the known bits are those that are shared by 2890 /// every vector element. 2891 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2892 EVT VT = Op.getValueType(); 2893 2894 // TOOD: Until we have a plan for how to represent demanded elements for 2895 // scalable vectors, we can just bail out for now. 2896 if (Op.getValueType().isScalableVector()) { 2897 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2898 return KnownBits(BitWidth); 2899 } 2900 2901 APInt DemandedElts = VT.isVector() 2902 ? APInt::getAllOnes(VT.getVectorNumElements()) 2903 : APInt(1, 1); 2904 return computeKnownBits(Op, DemandedElts, Depth); 2905 } 2906 2907 /// Determine which bits of Op are known to be either zero or one and return 2908 /// them in Known. The DemandedElts argument allows us to only collect the known 2909 /// bits that are shared by the requested vector elements. 2910 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2911 unsigned Depth) const { 2912 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2913 2914 KnownBits Known(BitWidth); // Don't know anything. 2915 2916 // TOOD: Until we have a plan for how to represent demanded elements for 2917 // scalable vectors, we can just bail out for now. 2918 if (Op.getValueType().isScalableVector()) 2919 return Known; 2920 2921 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2922 // We know all of the bits for a constant! 2923 return KnownBits::makeConstant(C->getAPIntValue()); 2924 } 2925 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2926 // We know all of the bits for a constant fp! 2927 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2928 } 2929 2930 if (Depth >= MaxRecursionDepth) 2931 return Known; // Limit search depth. 2932 2933 KnownBits Known2; 2934 unsigned NumElts = DemandedElts.getBitWidth(); 2935 assert((!Op.getValueType().isVector() || 2936 NumElts == Op.getValueType().getVectorNumElements()) && 2937 "Unexpected vector size"); 2938 2939 if (!DemandedElts) 2940 return Known; // No demanded elts, better to assume we don't know anything. 2941 2942 unsigned Opcode = Op.getOpcode(); 2943 switch (Opcode) { 2944 case ISD::BUILD_VECTOR: 2945 // Collect the known bits that are shared by every demanded vector element. 2946 Known.Zero.setAllBits(); Known.One.setAllBits(); 2947 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2948 if (!DemandedElts[i]) 2949 continue; 2950 2951 SDValue SrcOp = Op.getOperand(i); 2952 Known2 = computeKnownBits(SrcOp, Depth + 1); 2953 2954 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2955 if (SrcOp.getValueSizeInBits() != BitWidth) { 2956 assert(SrcOp.getValueSizeInBits() > BitWidth && 2957 "Expected BUILD_VECTOR implicit truncation"); 2958 Known2 = Known2.trunc(BitWidth); 2959 } 2960 2961 // Known bits are the values that are shared by every demanded element. 2962 Known = KnownBits::commonBits(Known, Known2); 2963 2964 // If we don't know any bits, early out. 2965 if (Known.isUnknown()) 2966 break; 2967 } 2968 break; 2969 case ISD::VECTOR_SHUFFLE: { 2970 // Collect the known bits that are shared by every vector element referenced 2971 // by the shuffle. 2972 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2973 Known.Zero.setAllBits(); Known.One.setAllBits(); 2974 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2975 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2976 for (unsigned i = 0; i != NumElts; ++i) { 2977 if (!DemandedElts[i]) 2978 continue; 2979 2980 int M = SVN->getMaskElt(i); 2981 if (M < 0) { 2982 // For UNDEF elements, we don't know anything about the common state of 2983 // the shuffle result. 2984 Known.resetAll(); 2985 DemandedLHS.clearAllBits(); 2986 DemandedRHS.clearAllBits(); 2987 break; 2988 } 2989 2990 if ((unsigned)M < NumElts) 2991 DemandedLHS.setBit((unsigned)M % NumElts); 2992 else 2993 DemandedRHS.setBit((unsigned)M % NumElts); 2994 } 2995 // Known bits are the values that are shared by every demanded element. 2996 if (!!DemandedLHS) { 2997 SDValue LHS = Op.getOperand(0); 2998 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2999 Known = KnownBits::commonBits(Known, Known2); 3000 } 3001 // If we don't know any bits, early out. 3002 if (Known.isUnknown()) 3003 break; 3004 if (!!DemandedRHS) { 3005 SDValue RHS = Op.getOperand(1); 3006 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3007 Known = KnownBits::commonBits(Known, Known2); 3008 } 3009 break; 3010 } 3011 case ISD::CONCAT_VECTORS: { 3012 // Split DemandedElts and test each of the demanded subvectors. 3013 Known.Zero.setAllBits(); Known.One.setAllBits(); 3014 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3015 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3016 unsigned NumSubVectors = Op.getNumOperands(); 3017 for (unsigned i = 0; i != NumSubVectors; ++i) { 3018 APInt DemandedSub = 3019 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3020 if (!!DemandedSub) { 3021 SDValue Sub = Op.getOperand(i); 3022 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3023 Known = KnownBits::commonBits(Known, Known2); 3024 } 3025 // If we don't know any bits, early out. 3026 if (Known.isUnknown()) 3027 break; 3028 } 3029 break; 3030 } 3031 case ISD::INSERT_SUBVECTOR: { 3032 // Demand any elements from the subvector and the remainder from the src its 3033 // inserted into. 3034 SDValue Src = Op.getOperand(0); 3035 SDValue Sub = Op.getOperand(1); 3036 uint64_t Idx = Op.getConstantOperandVal(2); 3037 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3038 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3039 APInt DemandedSrcElts = DemandedElts; 3040 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3041 3042 Known.One.setAllBits(); 3043 Known.Zero.setAllBits(); 3044 if (!!DemandedSubElts) { 3045 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3046 if (Known.isUnknown()) 3047 break; // early-out. 3048 } 3049 if (!!DemandedSrcElts) { 3050 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3051 Known = KnownBits::commonBits(Known, Known2); 3052 } 3053 break; 3054 } 3055 case ISD::EXTRACT_SUBVECTOR: { 3056 // Offset the demanded elts by the subvector index. 3057 SDValue Src = Op.getOperand(0); 3058 // Bail until we can represent demanded elements for scalable vectors. 3059 if (Src.getValueType().isScalableVector()) 3060 break; 3061 uint64_t Idx = Op.getConstantOperandVal(1); 3062 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3063 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 3064 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3065 break; 3066 } 3067 case ISD::SCALAR_TO_VECTOR: { 3068 // We know about scalar_to_vector as much as we know about it source, 3069 // which becomes the first element of otherwise unknown vector. 3070 if (DemandedElts != 1) 3071 break; 3072 3073 SDValue N0 = Op.getOperand(0); 3074 Known = computeKnownBits(N0, Depth + 1); 3075 if (N0.getValueSizeInBits() != BitWidth) 3076 Known = Known.trunc(BitWidth); 3077 3078 break; 3079 } 3080 case ISD::BITCAST: { 3081 SDValue N0 = Op.getOperand(0); 3082 EVT SubVT = N0.getValueType(); 3083 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3084 3085 // Ignore bitcasts from unsupported types. 3086 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3087 break; 3088 3089 // Fast handling of 'identity' bitcasts. 3090 if (BitWidth == SubBitWidth) { 3091 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3092 break; 3093 } 3094 3095 bool IsLE = getDataLayout().isLittleEndian(); 3096 3097 // Bitcast 'small element' vector to 'large element' scalar/vector. 3098 if ((BitWidth % SubBitWidth) == 0) { 3099 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3100 3101 // Collect known bits for the (larger) output by collecting the known 3102 // bits from each set of sub elements and shift these into place. 3103 // We need to separately call computeKnownBits for each set of 3104 // sub elements as the knownbits for each is likely to be different. 3105 unsigned SubScale = BitWidth / SubBitWidth; 3106 APInt SubDemandedElts(NumElts * SubScale, 0); 3107 for (unsigned i = 0; i != NumElts; ++i) 3108 if (DemandedElts[i]) 3109 SubDemandedElts.setBit(i * SubScale); 3110 3111 for (unsigned i = 0; i != SubScale; ++i) { 3112 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3113 Depth + 1); 3114 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3115 Known.insertBits(Known2, SubBitWidth * Shifts); 3116 } 3117 } 3118 3119 // Bitcast 'large element' scalar/vector to 'small element' vector. 3120 if ((SubBitWidth % BitWidth) == 0) { 3121 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3122 3123 // Collect known bits for the (smaller) output by collecting the known 3124 // bits from the overlapping larger input elements and extracting the 3125 // sub sections we actually care about. 3126 unsigned SubScale = SubBitWidth / BitWidth; 3127 APInt SubDemandedElts = 3128 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3129 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3130 3131 Known.Zero.setAllBits(); Known.One.setAllBits(); 3132 for (unsigned i = 0; i != NumElts; ++i) 3133 if (DemandedElts[i]) { 3134 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3135 unsigned Offset = (Shifts % SubScale) * BitWidth; 3136 Known = KnownBits::commonBits(Known, 3137 Known2.extractBits(BitWidth, Offset)); 3138 // If we don't know any bits, early out. 3139 if (Known.isUnknown()) 3140 break; 3141 } 3142 } 3143 break; 3144 } 3145 case ISD::AND: 3146 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3147 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3148 3149 Known &= Known2; 3150 break; 3151 case ISD::OR: 3152 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3153 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3154 3155 Known |= Known2; 3156 break; 3157 case ISD::XOR: 3158 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3159 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3160 3161 Known ^= Known2; 3162 break; 3163 case ISD::MUL: { 3164 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3165 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3166 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3167 // TODO: SelfMultiply can be poison, but not undef. 3168 if (SelfMultiply) 3169 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3170 Op.getOperand(0), DemandedElts, false, Depth + 1); 3171 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3172 break; 3173 } 3174 case ISD::MULHU: { 3175 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3176 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3177 Known = KnownBits::mulhu(Known, Known2); 3178 break; 3179 } 3180 case ISD::MULHS: { 3181 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3182 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3183 Known = KnownBits::mulhs(Known, Known2); 3184 break; 3185 } 3186 case ISD::UMUL_LOHI: { 3187 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3188 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3189 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3190 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3191 if (Op.getResNo() == 0) 3192 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3193 else 3194 Known = KnownBits::mulhu(Known, Known2); 3195 break; 3196 } 3197 case ISD::SMUL_LOHI: { 3198 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3199 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3200 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3201 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3202 if (Op.getResNo() == 0) 3203 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3204 else 3205 Known = KnownBits::mulhs(Known, Known2); 3206 break; 3207 } 3208 case ISD::UDIV: { 3209 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3210 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3211 Known = KnownBits::udiv(Known, Known2); 3212 break; 3213 } 3214 case ISD::AVGCEILU: { 3215 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3216 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3217 Known = Known.zext(BitWidth + 1); 3218 Known2 = Known2.zext(BitWidth + 1); 3219 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3220 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3221 Known = Known.extractBits(BitWidth, 1); 3222 break; 3223 } 3224 case ISD::SELECT: 3225 case ISD::VSELECT: 3226 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3227 // If we don't know any bits, early out. 3228 if (Known.isUnknown()) 3229 break; 3230 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3231 3232 // Only known if known in both the LHS and RHS. 3233 Known = KnownBits::commonBits(Known, Known2); 3234 break; 3235 case ISD::SELECT_CC: 3236 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3237 // If we don't know any bits, early out. 3238 if (Known.isUnknown()) 3239 break; 3240 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3241 3242 // Only known if known in both the LHS and RHS. 3243 Known = KnownBits::commonBits(Known, Known2); 3244 break; 3245 case ISD::SMULO: 3246 case ISD::UMULO: 3247 if (Op.getResNo() != 1) 3248 break; 3249 // The boolean result conforms to getBooleanContents. 3250 // If we know the result of a setcc has the top bits zero, use this info. 3251 // We know that we have an integer-based boolean since these operations 3252 // are only available for integer. 3253 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3254 TargetLowering::ZeroOrOneBooleanContent && 3255 BitWidth > 1) 3256 Known.Zero.setBitsFrom(1); 3257 break; 3258 case ISD::SETCC: 3259 case ISD::STRICT_FSETCC: 3260 case ISD::STRICT_FSETCCS: { 3261 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3262 // If we know the result of a setcc has the top bits zero, use this info. 3263 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3264 TargetLowering::ZeroOrOneBooleanContent && 3265 BitWidth > 1) 3266 Known.Zero.setBitsFrom(1); 3267 break; 3268 } 3269 case ISD::SHL: 3270 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3271 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3272 Known = KnownBits::shl(Known, Known2); 3273 3274 // Minimum shift low bits are known zero. 3275 if (const APInt *ShMinAmt = 3276 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3277 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3278 break; 3279 case ISD::SRL: 3280 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3281 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3282 Known = KnownBits::lshr(Known, Known2); 3283 3284 // Minimum shift high bits are known zero. 3285 if (const APInt *ShMinAmt = 3286 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3287 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3288 break; 3289 case ISD::SRA: 3290 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3291 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3292 Known = KnownBits::ashr(Known, Known2); 3293 // TODO: Add minimum shift high known sign bits. 3294 break; 3295 case ISD::FSHL: 3296 case ISD::FSHR: 3297 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3298 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3299 3300 // For fshl, 0-shift returns the 1st arg. 3301 // For fshr, 0-shift returns the 2nd arg. 3302 if (Amt == 0) { 3303 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3304 DemandedElts, Depth + 1); 3305 break; 3306 } 3307 3308 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3309 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3310 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3311 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3312 if (Opcode == ISD::FSHL) { 3313 Known.One <<= Amt; 3314 Known.Zero <<= Amt; 3315 Known2.One.lshrInPlace(BitWidth - Amt); 3316 Known2.Zero.lshrInPlace(BitWidth - Amt); 3317 } else { 3318 Known.One <<= BitWidth - Amt; 3319 Known.Zero <<= BitWidth - Amt; 3320 Known2.One.lshrInPlace(Amt); 3321 Known2.Zero.lshrInPlace(Amt); 3322 } 3323 Known.One |= Known2.One; 3324 Known.Zero |= Known2.Zero; 3325 } 3326 break; 3327 case ISD::SIGN_EXTEND_INREG: { 3328 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3329 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3330 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3331 break; 3332 } 3333 case ISD::CTTZ: 3334 case ISD::CTTZ_ZERO_UNDEF: { 3335 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3336 // If we have a known 1, its position is our upper bound. 3337 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3338 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3339 Known.Zero.setBitsFrom(LowBits); 3340 break; 3341 } 3342 case ISD::CTLZ: 3343 case ISD::CTLZ_ZERO_UNDEF: { 3344 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3345 // If we have a known 1, its position is our upper bound. 3346 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3347 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3348 Known.Zero.setBitsFrom(LowBits); 3349 break; 3350 } 3351 case ISD::CTPOP: { 3352 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3353 // If we know some of the bits are zero, they can't be one. 3354 unsigned PossibleOnes = Known2.countMaxPopulation(); 3355 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3356 break; 3357 } 3358 case ISD::PARITY: { 3359 // Parity returns 0 everywhere but the LSB. 3360 Known.Zero.setBitsFrom(1); 3361 break; 3362 } 3363 case ISD::LOAD: { 3364 LoadSDNode *LD = cast<LoadSDNode>(Op); 3365 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3366 if (ISD::isNON_EXTLoad(LD) && Cst) { 3367 // Determine any common known bits from the loaded constant pool value. 3368 Type *CstTy = Cst->getType(); 3369 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3370 // If its a vector splat, then we can (quickly) reuse the scalar path. 3371 // NOTE: We assume all elements match and none are UNDEF. 3372 if (CstTy->isVectorTy()) { 3373 if (const Constant *Splat = Cst->getSplatValue()) { 3374 Cst = Splat; 3375 CstTy = Cst->getType(); 3376 } 3377 } 3378 // TODO - do we need to handle different bitwidths? 3379 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3380 // Iterate across all vector elements finding common known bits. 3381 Known.One.setAllBits(); 3382 Known.Zero.setAllBits(); 3383 for (unsigned i = 0; i != NumElts; ++i) { 3384 if (!DemandedElts[i]) 3385 continue; 3386 if (Constant *Elt = Cst->getAggregateElement(i)) { 3387 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3388 const APInt &Value = CInt->getValue(); 3389 Known.One &= Value; 3390 Known.Zero &= ~Value; 3391 continue; 3392 } 3393 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3394 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3395 Known.One &= Value; 3396 Known.Zero &= ~Value; 3397 continue; 3398 } 3399 } 3400 Known.One.clearAllBits(); 3401 Known.Zero.clearAllBits(); 3402 break; 3403 } 3404 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3405 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3406 Known = KnownBits::makeConstant(CInt->getValue()); 3407 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3408 Known = 3409 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3410 } 3411 } 3412 } 3413 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3414 // If this is a ZEXTLoad and we are looking at the loaded value. 3415 EVT VT = LD->getMemoryVT(); 3416 unsigned MemBits = VT.getScalarSizeInBits(); 3417 Known.Zero.setBitsFrom(MemBits); 3418 } else if (const MDNode *Ranges = LD->getRanges()) { 3419 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3420 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3421 } 3422 break; 3423 } 3424 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3425 EVT InVT = Op.getOperand(0).getValueType(); 3426 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3427 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3428 Known = Known.zext(BitWidth); 3429 break; 3430 } 3431 case ISD::ZERO_EXTEND: { 3432 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3433 Known = Known.zext(BitWidth); 3434 break; 3435 } 3436 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3437 EVT InVT = Op.getOperand(0).getValueType(); 3438 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3439 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3440 // If the sign bit is known to be zero or one, then sext will extend 3441 // it to the top bits, else it will just zext. 3442 Known = Known.sext(BitWidth); 3443 break; 3444 } 3445 case ISD::SIGN_EXTEND: { 3446 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3447 // If the sign bit is known to be zero or one, then sext will extend 3448 // it to the top bits, else it will just zext. 3449 Known = Known.sext(BitWidth); 3450 break; 3451 } 3452 case ISD::ANY_EXTEND_VECTOR_INREG: { 3453 EVT InVT = Op.getOperand(0).getValueType(); 3454 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3455 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3456 Known = Known.anyext(BitWidth); 3457 break; 3458 } 3459 case ISD::ANY_EXTEND: { 3460 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3461 Known = Known.anyext(BitWidth); 3462 break; 3463 } 3464 case ISD::TRUNCATE: { 3465 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3466 Known = Known.trunc(BitWidth); 3467 break; 3468 } 3469 case ISD::AssertZext: { 3470 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3471 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3472 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3473 Known.Zero |= (~InMask); 3474 Known.One &= (~Known.Zero); 3475 break; 3476 } 3477 case ISD::AssertAlign: { 3478 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3479 assert(LogOfAlign != 0); 3480 3481 // TODO: Should use maximum with source 3482 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3483 // well as clearing one bits. 3484 Known.Zero.setLowBits(LogOfAlign); 3485 Known.One.clearLowBits(LogOfAlign); 3486 break; 3487 } 3488 case ISD::FGETSIGN: 3489 // All bits are zero except the low bit. 3490 Known.Zero.setBitsFrom(1); 3491 break; 3492 case ISD::USUBO: 3493 case ISD::SSUBO: 3494 if (Op.getResNo() == 1) { 3495 // If we know the result of a setcc has the top bits zero, use this info. 3496 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3497 TargetLowering::ZeroOrOneBooleanContent && 3498 BitWidth > 1) 3499 Known.Zero.setBitsFrom(1); 3500 break; 3501 } 3502 LLVM_FALLTHROUGH; 3503 case ISD::SUB: 3504 case ISD::SUBC: { 3505 assert(Op.getResNo() == 0 && 3506 "We only compute knownbits for the difference here."); 3507 3508 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3509 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3510 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3511 Known, Known2); 3512 break; 3513 } 3514 case ISD::UADDO: 3515 case ISD::SADDO: 3516 case ISD::ADDCARRY: 3517 if (Op.getResNo() == 1) { 3518 // If we know the result of a setcc has the top bits zero, use this info. 3519 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3520 TargetLowering::ZeroOrOneBooleanContent && 3521 BitWidth > 1) 3522 Known.Zero.setBitsFrom(1); 3523 break; 3524 } 3525 LLVM_FALLTHROUGH; 3526 case ISD::ADD: 3527 case ISD::ADDC: 3528 case ISD::ADDE: { 3529 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3530 3531 // With ADDE and ADDCARRY, a carry bit may be added in. 3532 KnownBits Carry(1); 3533 if (Opcode == ISD::ADDE) 3534 // Can't track carry from glue, set carry to unknown. 3535 Carry.resetAll(); 3536 else if (Opcode == ISD::ADDCARRY) 3537 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3538 // the trouble (how often will we find a known carry bit). And I haven't 3539 // tested this very much yet, but something like this might work: 3540 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3541 // Carry = Carry.zextOrTrunc(1, false); 3542 Carry.resetAll(); 3543 else 3544 Carry.setAllZero(); 3545 3546 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3547 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3548 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3549 break; 3550 } 3551 case ISD::SREM: { 3552 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3553 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3554 Known = KnownBits::srem(Known, Known2); 3555 break; 3556 } 3557 case ISD::UREM: { 3558 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3559 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3560 Known = KnownBits::urem(Known, Known2); 3561 break; 3562 } 3563 case ISD::EXTRACT_ELEMENT: { 3564 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3565 const unsigned Index = Op.getConstantOperandVal(1); 3566 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3567 3568 // Remove low part of known bits mask 3569 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3570 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3571 3572 // Remove high part of known bit mask 3573 Known = Known.trunc(EltBitWidth); 3574 break; 3575 } 3576 case ISD::EXTRACT_VECTOR_ELT: { 3577 SDValue InVec = Op.getOperand(0); 3578 SDValue EltNo = Op.getOperand(1); 3579 EVT VecVT = InVec.getValueType(); 3580 // computeKnownBits not yet implemented for scalable vectors. 3581 if (VecVT.isScalableVector()) 3582 break; 3583 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3584 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3585 3586 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3587 // anything about the extended bits. 3588 if (BitWidth > EltBitWidth) 3589 Known = Known.trunc(EltBitWidth); 3590 3591 // If we know the element index, just demand that vector element, else for 3592 // an unknown element index, ignore DemandedElts and demand them all. 3593 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3594 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3595 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3596 DemandedSrcElts = 3597 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3598 3599 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3600 if (BitWidth > EltBitWidth) 3601 Known = Known.anyext(BitWidth); 3602 break; 3603 } 3604 case ISD::INSERT_VECTOR_ELT: { 3605 // If we know the element index, split the demand between the 3606 // source vector and the inserted element, otherwise assume we need 3607 // the original demanded vector elements and the value. 3608 SDValue InVec = Op.getOperand(0); 3609 SDValue InVal = Op.getOperand(1); 3610 SDValue EltNo = Op.getOperand(2); 3611 bool DemandedVal = true; 3612 APInt DemandedVecElts = DemandedElts; 3613 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3614 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3615 unsigned EltIdx = CEltNo->getZExtValue(); 3616 DemandedVal = !!DemandedElts[EltIdx]; 3617 DemandedVecElts.clearBit(EltIdx); 3618 } 3619 Known.One.setAllBits(); 3620 Known.Zero.setAllBits(); 3621 if (DemandedVal) { 3622 Known2 = computeKnownBits(InVal, Depth + 1); 3623 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3624 } 3625 if (!!DemandedVecElts) { 3626 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3627 Known = KnownBits::commonBits(Known, Known2); 3628 } 3629 break; 3630 } 3631 case ISD::BITREVERSE: { 3632 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3633 Known = Known2.reverseBits(); 3634 break; 3635 } 3636 case ISD::BSWAP: { 3637 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3638 Known = Known2.byteSwap(); 3639 break; 3640 } 3641 case ISD::ABS: { 3642 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3643 Known = Known2.abs(); 3644 break; 3645 } 3646 case ISD::USUBSAT: { 3647 // The result of usubsat will never be larger than the LHS. 3648 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3649 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3650 break; 3651 } 3652 case ISD::UMIN: { 3653 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3654 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3655 Known = KnownBits::umin(Known, Known2); 3656 break; 3657 } 3658 case ISD::UMAX: { 3659 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3660 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3661 Known = KnownBits::umax(Known, Known2); 3662 break; 3663 } 3664 case ISD::SMIN: 3665 case ISD::SMAX: { 3666 // If we have a clamp pattern, we know that the number of sign bits will be 3667 // the minimum of the clamp min/max range. 3668 bool IsMax = (Opcode == ISD::SMAX); 3669 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3670 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3671 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3672 CstHigh = 3673 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3674 if (CstLow && CstHigh) { 3675 if (!IsMax) 3676 std::swap(CstLow, CstHigh); 3677 3678 const APInt &ValueLow = CstLow->getAPIntValue(); 3679 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3680 if (ValueLow.sle(ValueHigh)) { 3681 unsigned LowSignBits = ValueLow.getNumSignBits(); 3682 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3683 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3684 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3685 Known.One.setHighBits(MinSignBits); 3686 break; 3687 } 3688 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3689 Known.Zero.setHighBits(MinSignBits); 3690 break; 3691 } 3692 } 3693 } 3694 3695 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3696 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3697 if (IsMax) 3698 Known = KnownBits::smax(Known, Known2); 3699 else 3700 Known = KnownBits::smin(Known, Known2); 3701 break; 3702 } 3703 case ISD::FP_TO_UINT_SAT: { 3704 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3705 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3706 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3707 break; 3708 } 3709 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3710 if (Op.getResNo() == 1) { 3711 // The boolean result conforms to getBooleanContents. 3712 // If we know the result of a setcc has the top bits zero, use this info. 3713 // We know that we have an integer-based boolean since these operations 3714 // are only available for integer. 3715 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3716 TargetLowering::ZeroOrOneBooleanContent && 3717 BitWidth > 1) 3718 Known.Zero.setBitsFrom(1); 3719 break; 3720 } 3721 LLVM_FALLTHROUGH; 3722 case ISD::ATOMIC_CMP_SWAP: 3723 case ISD::ATOMIC_SWAP: 3724 case ISD::ATOMIC_LOAD_ADD: 3725 case ISD::ATOMIC_LOAD_SUB: 3726 case ISD::ATOMIC_LOAD_AND: 3727 case ISD::ATOMIC_LOAD_CLR: 3728 case ISD::ATOMIC_LOAD_OR: 3729 case ISD::ATOMIC_LOAD_XOR: 3730 case ISD::ATOMIC_LOAD_NAND: 3731 case ISD::ATOMIC_LOAD_MIN: 3732 case ISD::ATOMIC_LOAD_MAX: 3733 case ISD::ATOMIC_LOAD_UMIN: 3734 case ISD::ATOMIC_LOAD_UMAX: 3735 case ISD::ATOMIC_LOAD: { 3736 unsigned MemBits = 3737 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3738 // If we are looking at the loaded value. 3739 if (Op.getResNo() == 0) { 3740 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3741 Known.Zero.setBitsFrom(MemBits); 3742 } 3743 break; 3744 } 3745 case ISD::FrameIndex: 3746 case ISD::TargetFrameIndex: 3747 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3748 Known, getMachineFunction()); 3749 break; 3750 3751 default: 3752 if (Opcode < ISD::BUILTIN_OP_END) 3753 break; 3754 LLVM_FALLTHROUGH; 3755 case ISD::INTRINSIC_WO_CHAIN: 3756 case ISD::INTRINSIC_W_CHAIN: 3757 case ISD::INTRINSIC_VOID: 3758 // Allow the target to implement this method for its nodes. 3759 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3760 break; 3761 } 3762 3763 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3764 return Known; 3765 } 3766 3767 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3768 SDValue N1) const { 3769 // X + 0 never overflow 3770 if (isNullConstant(N1)) 3771 return OFK_Never; 3772 3773 KnownBits N1Known = computeKnownBits(N1); 3774 if (N1Known.Zero.getBoolValue()) { 3775 KnownBits N0Known = computeKnownBits(N0); 3776 3777 bool overflow; 3778 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3779 if (!overflow) 3780 return OFK_Never; 3781 } 3782 3783 // mulhi + 1 never overflow 3784 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3785 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3786 return OFK_Never; 3787 3788 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3789 KnownBits N0Known = computeKnownBits(N0); 3790 3791 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3792 return OFK_Never; 3793 } 3794 3795 return OFK_Sometime; 3796 } 3797 3798 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3799 EVT OpVT = Val.getValueType(); 3800 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3801 3802 // Is the constant a known power of 2? 3803 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3804 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3805 3806 // A left-shift of a constant one will have exactly one bit set because 3807 // shifting the bit off the end is undefined. 3808 if (Val.getOpcode() == ISD::SHL) { 3809 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3810 if (C && C->getAPIntValue() == 1) 3811 return true; 3812 } 3813 3814 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3815 // one bit set. 3816 if (Val.getOpcode() == ISD::SRL) { 3817 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3818 if (C && C->getAPIntValue().isSignMask()) 3819 return true; 3820 } 3821 3822 // Are all operands of a build vector constant powers of two? 3823 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3824 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3825 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3826 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3827 return false; 3828 })) 3829 return true; 3830 3831 // Is the operand of a splat vector a constant power of two? 3832 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3833 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3834 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3835 return true; 3836 3837 // More could be done here, though the above checks are enough 3838 // to handle some common cases. 3839 3840 // Fall back to computeKnownBits to catch other known cases. 3841 KnownBits Known = computeKnownBits(Val); 3842 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3843 } 3844 3845 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3846 EVT VT = Op.getValueType(); 3847 3848 // TODO: Assume we don't know anything for now. 3849 if (VT.isScalableVector()) 3850 return 1; 3851 3852 APInt DemandedElts = VT.isVector() 3853 ? APInt::getAllOnes(VT.getVectorNumElements()) 3854 : APInt(1, 1); 3855 return ComputeNumSignBits(Op, DemandedElts, Depth); 3856 } 3857 3858 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3859 unsigned Depth) const { 3860 EVT VT = Op.getValueType(); 3861 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3862 unsigned VTBits = VT.getScalarSizeInBits(); 3863 unsigned NumElts = DemandedElts.getBitWidth(); 3864 unsigned Tmp, Tmp2; 3865 unsigned FirstAnswer = 1; 3866 3867 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3868 const APInt &Val = C->getAPIntValue(); 3869 return Val.getNumSignBits(); 3870 } 3871 3872 if (Depth >= MaxRecursionDepth) 3873 return 1; // Limit search depth. 3874 3875 if (!DemandedElts || VT.isScalableVector()) 3876 return 1; // No demanded elts, better to assume we don't know anything. 3877 3878 unsigned Opcode = Op.getOpcode(); 3879 switch (Opcode) { 3880 default: break; 3881 case ISD::AssertSext: 3882 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3883 return VTBits-Tmp+1; 3884 case ISD::AssertZext: 3885 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3886 return VTBits-Tmp; 3887 3888 case ISD::BUILD_VECTOR: 3889 Tmp = VTBits; 3890 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3891 if (!DemandedElts[i]) 3892 continue; 3893 3894 SDValue SrcOp = Op.getOperand(i); 3895 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3896 3897 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3898 if (SrcOp.getValueSizeInBits() != VTBits) { 3899 assert(SrcOp.getValueSizeInBits() > VTBits && 3900 "Expected BUILD_VECTOR implicit truncation"); 3901 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3902 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3903 } 3904 Tmp = std::min(Tmp, Tmp2); 3905 } 3906 return Tmp; 3907 3908 case ISD::VECTOR_SHUFFLE: { 3909 // Collect the minimum number of sign bits that are shared by every vector 3910 // element referenced by the shuffle. 3911 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3912 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3913 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3914 for (unsigned i = 0; i != NumElts; ++i) { 3915 int M = SVN->getMaskElt(i); 3916 if (!DemandedElts[i]) 3917 continue; 3918 // For UNDEF elements, we don't know anything about the common state of 3919 // the shuffle result. 3920 if (M < 0) 3921 return 1; 3922 if ((unsigned)M < NumElts) 3923 DemandedLHS.setBit((unsigned)M % NumElts); 3924 else 3925 DemandedRHS.setBit((unsigned)M % NumElts); 3926 } 3927 Tmp = std::numeric_limits<unsigned>::max(); 3928 if (!!DemandedLHS) 3929 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3930 if (!!DemandedRHS) { 3931 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3932 Tmp = std::min(Tmp, Tmp2); 3933 } 3934 // If we don't know anything, early out and try computeKnownBits fall-back. 3935 if (Tmp == 1) 3936 break; 3937 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3938 return Tmp; 3939 } 3940 3941 case ISD::BITCAST: { 3942 SDValue N0 = Op.getOperand(0); 3943 EVT SrcVT = N0.getValueType(); 3944 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3945 3946 // Ignore bitcasts from unsupported types.. 3947 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3948 break; 3949 3950 // Fast handling of 'identity' bitcasts. 3951 if (VTBits == SrcBits) 3952 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3953 3954 bool IsLE = getDataLayout().isLittleEndian(); 3955 3956 // Bitcast 'large element' scalar/vector to 'small element' vector. 3957 if ((SrcBits % VTBits) == 0) { 3958 assert(VT.isVector() && "Expected bitcast to vector"); 3959 3960 unsigned Scale = SrcBits / VTBits; 3961 APInt SrcDemandedElts = 3962 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3963 3964 // Fast case - sign splat can be simply split across the small elements. 3965 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3966 if (Tmp == SrcBits) 3967 return VTBits; 3968 3969 // Slow case - determine how far the sign extends into each sub-element. 3970 Tmp2 = VTBits; 3971 for (unsigned i = 0; i != NumElts; ++i) 3972 if (DemandedElts[i]) { 3973 unsigned SubOffset = i % Scale; 3974 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3975 SubOffset = SubOffset * VTBits; 3976 if (Tmp <= SubOffset) 3977 return 1; 3978 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3979 } 3980 return Tmp2; 3981 } 3982 break; 3983 } 3984 3985 case ISD::FP_TO_SINT_SAT: 3986 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 3987 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3988 return VTBits - Tmp + 1; 3989 case ISD::SIGN_EXTEND: 3990 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3991 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3992 case ISD::SIGN_EXTEND_INREG: 3993 // Max of the input and what this extends. 3994 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3995 Tmp = VTBits-Tmp+1; 3996 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3997 return std::max(Tmp, Tmp2); 3998 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3999 SDValue Src = Op.getOperand(0); 4000 EVT SrcVT = Src.getValueType(); 4001 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 4002 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4003 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4004 } 4005 case ISD::SRA: 4006 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4007 // SRA X, C -> adds C sign bits. 4008 if (const APInt *ShAmt = 4009 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4010 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4011 return Tmp; 4012 case ISD::SHL: 4013 if (const APInt *ShAmt = 4014 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4015 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4016 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4017 if (ShAmt->ult(Tmp)) 4018 return Tmp - ShAmt->getZExtValue(); 4019 } 4020 break; 4021 case ISD::AND: 4022 case ISD::OR: 4023 case ISD::XOR: // NOT is handled here. 4024 // Logical binary ops preserve the number of sign bits at the worst. 4025 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4026 if (Tmp != 1) { 4027 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4028 FirstAnswer = std::min(Tmp, Tmp2); 4029 // We computed what we know about the sign bits as our first 4030 // answer. Now proceed to the generic code that uses 4031 // computeKnownBits, and pick whichever answer is better. 4032 } 4033 break; 4034 4035 case ISD::SELECT: 4036 case ISD::VSELECT: 4037 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4038 if (Tmp == 1) return 1; // Early out. 4039 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4040 return std::min(Tmp, Tmp2); 4041 case ISD::SELECT_CC: 4042 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4043 if (Tmp == 1) return 1; // Early out. 4044 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4045 return std::min(Tmp, Tmp2); 4046 4047 case ISD::SMIN: 4048 case ISD::SMAX: { 4049 // If we have a clamp pattern, we know that the number of sign bits will be 4050 // the minimum of the clamp min/max range. 4051 bool IsMax = (Opcode == ISD::SMAX); 4052 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4053 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4054 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4055 CstHigh = 4056 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4057 if (CstLow && CstHigh) { 4058 if (!IsMax) 4059 std::swap(CstLow, CstHigh); 4060 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4061 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4062 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4063 return std::min(Tmp, Tmp2); 4064 } 4065 } 4066 4067 // Fallback - just get the minimum number of sign bits of the operands. 4068 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4069 if (Tmp == 1) 4070 return 1; // Early out. 4071 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4072 return std::min(Tmp, Tmp2); 4073 } 4074 case ISD::UMIN: 4075 case ISD::UMAX: 4076 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4077 if (Tmp == 1) 4078 return 1; // Early out. 4079 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4080 return std::min(Tmp, Tmp2); 4081 case ISD::SADDO: 4082 case ISD::UADDO: 4083 case ISD::SSUBO: 4084 case ISD::USUBO: 4085 case ISD::SMULO: 4086 case ISD::UMULO: 4087 if (Op.getResNo() != 1) 4088 break; 4089 // The boolean result conforms to getBooleanContents. Fall through. 4090 // If setcc returns 0/-1, all bits are sign bits. 4091 // We know that we have an integer-based boolean since these operations 4092 // are only available for integer. 4093 if (TLI->getBooleanContents(VT.isVector(), false) == 4094 TargetLowering::ZeroOrNegativeOneBooleanContent) 4095 return VTBits; 4096 break; 4097 case ISD::SETCC: 4098 case ISD::STRICT_FSETCC: 4099 case ISD::STRICT_FSETCCS: { 4100 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4101 // If setcc returns 0/-1, all bits are sign bits. 4102 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4103 TargetLowering::ZeroOrNegativeOneBooleanContent) 4104 return VTBits; 4105 break; 4106 } 4107 case ISD::ROTL: 4108 case ISD::ROTR: 4109 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4110 4111 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4112 if (Tmp == VTBits) 4113 return VTBits; 4114 4115 if (ConstantSDNode *C = 4116 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4117 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4118 4119 // Handle rotate right by N like a rotate left by 32-N. 4120 if (Opcode == ISD::ROTR) 4121 RotAmt = (VTBits - RotAmt) % VTBits; 4122 4123 // If we aren't rotating out all of the known-in sign bits, return the 4124 // number that are left. This handles rotl(sext(x), 1) for example. 4125 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4126 } 4127 break; 4128 case ISD::ADD: 4129 case ISD::ADDC: 4130 // Add can have at most one carry bit. Thus we know that the output 4131 // is, at worst, one more bit than the inputs. 4132 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4133 if (Tmp == 1) return 1; // Early out. 4134 4135 // Special case decrementing a value (ADD X, -1): 4136 if (ConstantSDNode *CRHS = 4137 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4138 if (CRHS->isAllOnes()) { 4139 KnownBits Known = 4140 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4141 4142 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4143 // sign bits set. 4144 if ((Known.Zero | 1).isAllOnes()) 4145 return VTBits; 4146 4147 // If we are subtracting one from a positive number, there is no carry 4148 // out of the result. 4149 if (Known.isNonNegative()) 4150 return Tmp; 4151 } 4152 4153 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4154 if (Tmp2 == 1) return 1; // Early out. 4155 return std::min(Tmp, Tmp2) - 1; 4156 case ISD::SUB: 4157 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4158 if (Tmp2 == 1) return 1; // Early out. 4159 4160 // Handle NEG. 4161 if (ConstantSDNode *CLHS = 4162 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4163 if (CLHS->isZero()) { 4164 KnownBits Known = 4165 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4166 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4167 // sign bits set. 4168 if ((Known.Zero | 1).isAllOnes()) 4169 return VTBits; 4170 4171 // If the input is known to be positive (the sign bit is known clear), 4172 // the output of the NEG has the same number of sign bits as the input. 4173 if (Known.isNonNegative()) 4174 return Tmp2; 4175 4176 // Otherwise, we treat this like a SUB. 4177 } 4178 4179 // Sub can have at most one carry bit. Thus we know that the output 4180 // is, at worst, one more bit than the inputs. 4181 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4182 if (Tmp == 1) return 1; // Early out. 4183 return std::min(Tmp, Tmp2) - 1; 4184 case ISD::MUL: { 4185 // The output of the Mul can be at most twice the valid bits in the inputs. 4186 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4187 if (SignBitsOp0 == 1) 4188 break; 4189 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4190 if (SignBitsOp1 == 1) 4191 break; 4192 unsigned OutValidBits = 4193 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4194 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4195 } 4196 case ISD::SREM: 4197 // The sign bit is the LHS's sign bit, except when the result of the 4198 // remainder is zero. The magnitude of the result should be less than or 4199 // equal to the magnitude of the LHS. Therefore, the result should have 4200 // at least as many sign bits as the left hand side. 4201 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4202 case ISD::TRUNCATE: { 4203 // Check if the sign bits of source go down as far as the truncated value. 4204 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4205 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4206 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4207 return NumSrcSignBits - (NumSrcBits - VTBits); 4208 break; 4209 } 4210 case ISD::EXTRACT_ELEMENT: { 4211 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4212 const int BitWidth = Op.getValueSizeInBits(); 4213 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4214 4215 // Get reverse index (starting from 1), Op1 value indexes elements from 4216 // little end. Sign starts at big end. 4217 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4218 4219 // If the sign portion ends in our element the subtraction gives correct 4220 // result. Otherwise it gives either negative or > bitwidth result 4221 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4222 } 4223 case ISD::INSERT_VECTOR_ELT: { 4224 // If we know the element index, split the demand between the 4225 // source vector and the inserted element, otherwise assume we need 4226 // the original demanded vector elements and the value. 4227 SDValue InVec = Op.getOperand(0); 4228 SDValue InVal = Op.getOperand(1); 4229 SDValue EltNo = Op.getOperand(2); 4230 bool DemandedVal = true; 4231 APInt DemandedVecElts = DemandedElts; 4232 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4233 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4234 unsigned EltIdx = CEltNo->getZExtValue(); 4235 DemandedVal = !!DemandedElts[EltIdx]; 4236 DemandedVecElts.clearBit(EltIdx); 4237 } 4238 Tmp = std::numeric_limits<unsigned>::max(); 4239 if (DemandedVal) { 4240 // TODO - handle implicit truncation of inserted elements. 4241 if (InVal.getScalarValueSizeInBits() != VTBits) 4242 break; 4243 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4244 Tmp = std::min(Tmp, Tmp2); 4245 } 4246 if (!!DemandedVecElts) { 4247 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4248 Tmp = std::min(Tmp, Tmp2); 4249 } 4250 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4251 return Tmp; 4252 } 4253 case ISD::EXTRACT_VECTOR_ELT: { 4254 SDValue InVec = Op.getOperand(0); 4255 SDValue EltNo = Op.getOperand(1); 4256 EVT VecVT = InVec.getValueType(); 4257 // ComputeNumSignBits not yet implemented for scalable vectors. 4258 if (VecVT.isScalableVector()) 4259 break; 4260 const unsigned BitWidth = Op.getValueSizeInBits(); 4261 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4262 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4263 4264 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4265 // anything about sign bits. But if the sizes match we can derive knowledge 4266 // about sign bits from the vector operand. 4267 if (BitWidth != EltBitWidth) 4268 break; 4269 4270 // If we know the element index, just demand that vector element, else for 4271 // an unknown element index, ignore DemandedElts and demand them all. 4272 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4273 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4274 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4275 DemandedSrcElts = 4276 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4277 4278 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4279 } 4280 case ISD::EXTRACT_SUBVECTOR: { 4281 // Offset the demanded elts by the subvector index. 4282 SDValue Src = Op.getOperand(0); 4283 // Bail until we can represent demanded elements for scalable vectors. 4284 if (Src.getValueType().isScalableVector()) 4285 break; 4286 uint64_t Idx = Op.getConstantOperandVal(1); 4287 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4288 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4289 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4290 } 4291 case ISD::CONCAT_VECTORS: { 4292 // Determine the minimum number of sign bits across all demanded 4293 // elts of the input vectors. Early out if the result is already 1. 4294 Tmp = std::numeric_limits<unsigned>::max(); 4295 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4296 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4297 unsigned NumSubVectors = Op.getNumOperands(); 4298 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4299 APInt DemandedSub = 4300 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4301 if (!DemandedSub) 4302 continue; 4303 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4304 Tmp = std::min(Tmp, Tmp2); 4305 } 4306 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4307 return Tmp; 4308 } 4309 case ISD::INSERT_SUBVECTOR: { 4310 // Demand any elements from the subvector and the remainder from the src its 4311 // inserted into. 4312 SDValue Src = Op.getOperand(0); 4313 SDValue Sub = Op.getOperand(1); 4314 uint64_t Idx = Op.getConstantOperandVal(2); 4315 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4316 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4317 APInt DemandedSrcElts = DemandedElts; 4318 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4319 4320 Tmp = std::numeric_limits<unsigned>::max(); 4321 if (!!DemandedSubElts) { 4322 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4323 if (Tmp == 1) 4324 return 1; // early-out 4325 } 4326 if (!!DemandedSrcElts) { 4327 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4328 Tmp = std::min(Tmp, Tmp2); 4329 } 4330 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4331 return Tmp; 4332 } 4333 case ISD::ATOMIC_CMP_SWAP: 4334 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4335 case ISD::ATOMIC_SWAP: 4336 case ISD::ATOMIC_LOAD_ADD: 4337 case ISD::ATOMIC_LOAD_SUB: 4338 case ISD::ATOMIC_LOAD_AND: 4339 case ISD::ATOMIC_LOAD_CLR: 4340 case ISD::ATOMIC_LOAD_OR: 4341 case ISD::ATOMIC_LOAD_XOR: 4342 case ISD::ATOMIC_LOAD_NAND: 4343 case ISD::ATOMIC_LOAD_MIN: 4344 case ISD::ATOMIC_LOAD_MAX: 4345 case ISD::ATOMIC_LOAD_UMIN: 4346 case ISD::ATOMIC_LOAD_UMAX: 4347 case ISD::ATOMIC_LOAD: { 4348 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4349 // If we are looking at the loaded value. 4350 if (Op.getResNo() == 0) { 4351 if (Tmp == VTBits) 4352 return 1; // early-out 4353 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4354 return VTBits - Tmp + 1; 4355 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4356 return VTBits - Tmp; 4357 } 4358 break; 4359 } 4360 } 4361 4362 // If we are looking at the loaded value of the SDNode. 4363 if (Op.getResNo() == 0) { 4364 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4365 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4366 unsigned ExtType = LD->getExtensionType(); 4367 switch (ExtType) { 4368 default: break; 4369 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4370 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4371 return VTBits - Tmp + 1; 4372 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4373 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4374 return VTBits - Tmp; 4375 case ISD::NON_EXTLOAD: 4376 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4377 // We only need to handle vectors - computeKnownBits should handle 4378 // scalar cases. 4379 Type *CstTy = Cst->getType(); 4380 if (CstTy->isVectorTy() && 4381 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4382 VTBits == CstTy->getScalarSizeInBits()) { 4383 Tmp = VTBits; 4384 for (unsigned i = 0; i != NumElts; ++i) { 4385 if (!DemandedElts[i]) 4386 continue; 4387 if (Constant *Elt = Cst->getAggregateElement(i)) { 4388 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4389 const APInt &Value = CInt->getValue(); 4390 Tmp = std::min(Tmp, Value.getNumSignBits()); 4391 continue; 4392 } 4393 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4394 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4395 Tmp = std::min(Tmp, Value.getNumSignBits()); 4396 continue; 4397 } 4398 } 4399 // Unknown type. Conservatively assume no bits match sign bit. 4400 return 1; 4401 } 4402 return Tmp; 4403 } 4404 } 4405 break; 4406 } 4407 } 4408 } 4409 4410 // Allow the target to implement this method for its nodes. 4411 if (Opcode >= ISD::BUILTIN_OP_END || 4412 Opcode == ISD::INTRINSIC_WO_CHAIN || 4413 Opcode == ISD::INTRINSIC_W_CHAIN || 4414 Opcode == ISD::INTRINSIC_VOID) { 4415 unsigned NumBits = 4416 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4417 if (NumBits > 1) 4418 FirstAnswer = std::max(FirstAnswer, NumBits); 4419 } 4420 4421 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4422 // use this information. 4423 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4424 return std::max(FirstAnswer, Known.countMinSignBits()); 4425 } 4426 4427 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4428 unsigned Depth) const { 4429 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4430 return Op.getScalarValueSizeInBits() - SignBits + 1; 4431 } 4432 4433 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4434 const APInt &DemandedElts, 4435 unsigned Depth) const { 4436 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4437 return Op.getScalarValueSizeInBits() - SignBits + 1; 4438 } 4439 4440 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4441 unsigned Depth) const { 4442 // Early out for FREEZE. 4443 if (Op.getOpcode() == ISD::FREEZE) 4444 return true; 4445 4446 // TODO: Assume we don't know anything for now. 4447 EVT VT = Op.getValueType(); 4448 if (VT.isScalableVector()) 4449 return false; 4450 4451 APInt DemandedElts = VT.isVector() 4452 ? APInt::getAllOnes(VT.getVectorNumElements()) 4453 : APInt(1, 1); 4454 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4455 } 4456 4457 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4458 const APInt &DemandedElts, 4459 bool PoisonOnly, 4460 unsigned Depth) const { 4461 unsigned Opcode = Op.getOpcode(); 4462 4463 // Early out for FREEZE. 4464 if (Opcode == ISD::FREEZE) 4465 return true; 4466 4467 if (Depth >= MaxRecursionDepth) 4468 return false; // Limit search depth. 4469 4470 if (isIntOrFPConstant(Op)) 4471 return true; 4472 4473 switch (Opcode) { 4474 case ISD::UNDEF: 4475 return PoisonOnly; 4476 4477 case ISD::BUILD_VECTOR: 4478 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4479 // this shouldn't affect the result. 4480 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4481 if (!DemandedElts[i]) 4482 continue; 4483 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4484 Depth + 1)) 4485 return false; 4486 } 4487 return true; 4488 4489 // TODO: Search for noundef attributes from library functions. 4490 4491 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4492 4493 default: 4494 // Allow the target to implement this method for its nodes. 4495 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4496 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4497 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4498 Op, DemandedElts, *this, PoisonOnly, Depth); 4499 break; 4500 } 4501 4502 return false; 4503 } 4504 4505 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4506 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4507 !isa<ConstantSDNode>(Op.getOperand(1))) 4508 return false; 4509 4510 if (Op.getOpcode() == ISD::OR && 4511 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4512 return false; 4513 4514 return true; 4515 } 4516 4517 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4518 // If we're told that NaNs won't happen, assume they won't. 4519 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4520 return true; 4521 4522 if (Depth >= MaxRecursionDepth) 4523 return false; // Limit search depth. 4524 4525 // TODO: Handle vectors. 4526 // If the value is a constant, we can obviously see if it is a NaN or not. 4527 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4528 return !C->getValueAPF().isNaN() || 4529 (SNaN && !C->getValueAPF().isSignaling()); 4530 } 4531 4532 unsigned Opcode = Op.getOpcode(); 4533 switch (Opcode) { 4534 case ISD::FADD: 4535 case ISD::FSUB: 4536 case ISD::FMUL: 4537 case ISD::FDIV: 4538 case ISD::FREM: 4539 case ISD::FSIN: 4540 case ISD::FCOS: { 4541 if (SNaN) 4542 return true; 4543 // TODO: Need isKnownNeverInfinity 4544 return false; 4545 } 4546 case ISD::FCANONICALIZE: 4547 case ISD::FEXP: 4548 case ISD::FEXP2: 4549 case ISD::FTRUNC: 4550 case ISD::FFLOOR: 4551 case ISD::FCEIL: 4552 case ISD::FROUND: 4553 case ISD::FROUNDEVEN: 4554 case ISD::FRINT: 4555 case ISD::FNEARBYINT: { 4556 if (SNaN) 4557 return true; 4558 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4559 } 4560 case ISD::FABS: 4561 case ISD::FNEG: 4562 case ISD::FCOPYSIGN: { 4563 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4564 } 4565 case ISD::SELECT: 4566 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4567 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4568 case ISD::FP_EXTEND: 4569 case ISD::FP_ROUND: { 4570 if (SNaN) 4571 return true; 4572 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4573 } 4574 case ISD::SINT_TO_FP: 4575 case ISD::UINT_TO_FP: 4576 return true; 4577 case ISD::FMA: 4578 case ISD::FMAD: { 4579 if (SNaN) 4580 return true; 4581 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4582 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4583 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4584 } 4585 case ISD::FSQRT: // Need is known positive 4586 case ISD::FLOG: 4587 case ISD::FLOG2: 4588 case ISD::FLOG10: 4589 case ISD::FPOWI: 4590 case ISD::FPOW: { 4591 if (SNaN) 4592 return true; 4593 // TODO: Refine on operand 4594 return false; 4595 } 4596 case ISD::FMINNUM: 4597 case ISD::FMAXNUM: { 4598 // Only one needs to be known not-nan, since it will be returned if the 4599 // other ends up being one. 4600 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4601 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4602 } 4603 case ISD::FMINNUM_IEEE: 4604 case ISD::FMAXNUM_IEEE: { 4605 if (SNaN) 4606 return true; 4607 // This can return a NaN if either operand is an sNaN, or if both operands 4608 // are NaN. 4609 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4610 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4611 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4612 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4613 } 4614 case ISD::FMINIMUM: 4615 case ISD::FMAXIMUM: { 4616 // TODO: Does this quiet or return the origina NaN as-is? 4617 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4618 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4619 } 4620 case ISD::EXTRACT_VECTOR_ELT: { 4621 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4622 } 4623 default: 4624 if (Opcode >= ISD::BUILTIN_OP_END || 4625 Opcode == ISD::INTRINSIC_WO_CHAIN || 4626 Opcode == ISD::INTRINSIC_W_CHAIN || 4627 Opcode == ISD::INTRINSIC_VOID) { 4628 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4629 } 4630 4631 return false; 4632 } 4633 } 4634 4635 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4636 assert(Op.getValueType().isFloatingPoint() && 4637 "Floating point type expected"); 4638 4639 // If the value is a constant, we can obviously see if it is a zero or not. 4640 // TODO: Add BuildVector support. 4641 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4642 return !C->isZero(); 4643 return false; 4644 } 4645 4646 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4647 assert(!Op.getValueType().isFloatingPoint() && 4648 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4649 4650 // If the value is a constant, we can obviously see if it is a zero or not. 4651 if (ISD::matchUnaryPredicate(Op, 4652 [](ConstantSDNode *C) { return !C->isZero(); })) 4653 return true; 4654 4655 // TODO: Recognize more cases here. 4656 switch (Op.getOpcode()) { 4657 default: break; 4658 case ISD::OR: 4659 if (isKnownNeverZero(Op.getOperand(1)) || 4660 isKnownNeverZero(Op.getOperand(0))) 4661 return true; 4662 break; 4663 } 4664 4665 return false; 4666 } 4667 4668 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4669 // Check the obvious case. 4670 if (A == B) return true; 4671 4672 // For for negative and positive zero. 4673 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4674 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4675 if (CA->isZero() && CB->isZero()) return true; 4676 4677 // Otherwise they may not be equal. 4678 return false; 4679 } 4680 4681 // FIXME: unify with llvm::haveNoCommonBitsSet. 4682 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4683 assert(A.getValueType() == B.getValueType() && 4684 "Values must have the same type"); 4685 // Match masked merge pattern (X & ~M) op (Y & M) 4686 if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) { 4687 auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) { 4688 if (isBitwiseNot(NotM, true)) { 4689 SDValue NotOperand = NotM->getOperand(0); 4690 return NotOperand == And->getOperand(0) || 4691 NotOperand == And->getOperand(1); 4692 } 4693 return false; 4694 }; 4695 if (MatchNoCommonBitsPattern(A->getOperand(0), B) || 4696 MatchNoCommonBitsPattern(A->getOperand(1), B) || 4697 MatchNoCommonBitsPattern(B->getOperand(0), A) || 4698 MatchNoCommonBitsPattern(B->getOperand(1), A)) 4699 return true; 4700 } 4701 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4702 computeKnownBits(B)); 4703 } 4704 4705 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4706 SelectionDAG &DAG) { 4707 if (cast<ConstantSDNode>(Step)->isZero()) 4708 return DAG.getConstant(0, DL, VT); 4709 4710 return SDValue(); 4711 } 4712 4713 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4714 ArrayRef<SDValue> Ops, 4715 SelectionDAG &DAG) { 4716 int NumOps = Ops.size(); 4717 assert(NumOps != 0 && "Can't build an empty vector!"); 4718 assert(!VT.isScalableVector() && 4719 "BUILD_VECTOR cannot be used with scalable types"); 4720 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4721 "Incorrect element count in BUILD_VECTOR!"); 4722 4723 // BUILD_VECTOR of UNDEFs is UNDEF. 4724 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4725 return DAG.getUNDEF(VT); 4726 4727 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4728 SDValue IdentitySrc; 4729 bool IsIdentity = true; 4730 for (int i = 0; i != NumOps; ++i) { 4731 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4732 Ops[i].getOperand(0).getValueType() != VT || 4733 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4734 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4735 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4736 IsIdentity = false; 4737 break; 4738 } 4739 IdentitySrc = Ops[i].getOperand(0); 4740 } 4741 if (IsIdentity) 4742 return IdentitySrc; 4743 4744 return SDValue(); 4745 } 4746 4747 /// Try to simplify vector concatenation to an input value, undef, or build 4748 /// vector. 4749 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4750 ArrayRef<SDValue> Ops, 4751 SelectionDAG &DAG) { 4752 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4753 assert(llvm::all_of(Ops, 4754 [Ops](SDValue Op) { 4755 return Ops[0].getValueType() == Op.getValueType(); 4756 }) && 4757 "Concatenation of vectors with inconsistent value types!"); 4758 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4759 VT.getVectorElementCount() && 4760 "Incorrect element count in vector concatenation!"); 4761 4762 if (Ops.size() == 1) 4763 return Ops[0]; 4764 4765 // Concat of UNDEFs is UNDEF. 4766 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4767 return DAG.getUNDEF(VT); 4768 4769 // Scan the operands and look for extract operations from a single source 4770 // that correspond to insertion at the same location via this concatenation: 4771 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4772 SDValue IdentitySrc; 4773 bool IsIdentity = true; 4774 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4775 SDValue Op = Ops[i]; 4776 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4777 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4778 Op.getOperand(0).getValueType() != VT || 4779 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4780 Op.getConstantOperandVal(1) != IdentityIndex) { 4781 IsIdentity = false; 4782 break; 4783 } 4784 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4785 "Unexpected identity source vector for concat of extracts"); 4786 IdentitySrc = Op.getOperand(0); 4787 } 4788 if (IsIdentity) { 4789 assert(IdentitySrc && "Failed to set source vector of extracts"); 4790 return IdentitySrc; 4791 } 4792 4793 // The code below this point is only designed to work for fixed width 4794 // vectors, so we bail out for now. 4795 if (VT.isScalableVector()) 4796 return SDValue(); 4797 4798 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4799 // simplified to one big BUILD_VECTOR. 4800 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4801 EVT SVT = VT.getScalarType(); 4802 SmallVector<SDValue, 16> Elts; 4803 for (SDValue Op : Ops) { 4804 EVT OpVT = Op.getValueType(); 4805 if (Op.isUndef()) 4806 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4807 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4808 Elts.append(Op->op_begin(), Op->op_end()); 4809 else 4810 return SDValue(); 4811 } 4812 4813 // BUILD_VECTOR requires all inputs to be of the same type, find the 4814 // maximum type and extend them all. 4815 for (SDValue Op : Elts) 4816 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4817 4818 if (SVT.bitsGT(VT.getScalarType())) { 4819 for (SDValue &Op : Elts) { 4820 if (Op.isUndef()) 4821 Op = DAG.getUNDEF(SVT); 4822 else 4823 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4824 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4825 : DAG.getSExtOrTrunc(Op, DL, SVT); 4826 } 4827 } 4828 4829 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4830 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4831 return V; 4832 } 4833 4834 /// Gets or creates the specified node. 4835 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4836 FoldingSetNodeID ID; 4837 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4838 void *IP = nullptr; 4839 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4840 return SDValue(E, 0); 4841 4842 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4843 getVTList(VT)); 4844 CSEMap.InsertNode(N, IP); 4845 4846 InsertNode(N); 4847 SDValue V = SDValue(N, 0); 4848 NewSDValueDbgMsg(V, "Creating new node: ", this); 4849 return V; 4850 } 4851 4852 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4853 SDValue Operand) { 4854 SDNodeFlags Flags; 4855 if (Inserter) 4856 Flags = Inserter->getFlags(); 4857 return getNode(Opcode, DL, VT, Operand, Flags); 4858 } 4859 4860 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4861 SDValue Operand, const SDNodeFlags Flags) { 4862 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4863 "Operand is DELETED_NODE!"); 4864 // Constant fold unary operations with an integer constant operand. Even 4865 // opaque constant will be folded, because the folding of unary operations 4866 // doesn't create new constants with different values. Nevertheless, the 4867 // opaque flag is preserved during folding to prevent future folding with 4868 // other constants. 4869 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4870 const APInt &Val = C->getAPIntValue(); 4871 switch (Opcode) { 4872 default: break; 4873 case ISD::SIGN_EXTEND: 4874 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4875 C->isTargetOpcode(), C->isOpaque()); 4876 case ISD::TRUNCATE: 4877 if (C->isOpaque()) 4878 break; 4879 LLVM_FALLTHROUGH; 4880 case ISD::ZERO_EXTEND: 4881 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4882 C->isTargetOpcode(), C->isOpaque()); 4883 case ISD::ANY_EXTEND: 4884 // Some targets like RISCV prefer to sign extend some types. 4885 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4886 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4887 C->isTargetOpcode(), C->isOpaque()); 4888 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4889 C->isTargetOpcode(), C->isOpaque()); 4890 case ISD::UINT_TO_FP: 4891 case ISD::SINT_TO_FP: { 4892 APFloat apf(EVTToAPFloatSemantics(VT), 4893 APInt::getZero(VT.getSizeInBits())); 4894 (void)apf.convertFromAPInt(Val, 4895 Opcode==ISD::SINT_TO_FP, 4896 APFloat::rmNearestTiesToEven); 4897 return getConstantFP(apf, DL, VT); 4898 } 4899 case ISD::BITCAST: 4900 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4901 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4902 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4903 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4904 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4905 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4906 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4907 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4908 break; 4909 case ISD::ABS: 4910 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4911 C->isOpaque()); 4912 case ISD::BITREVERSE: 4913 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4914 C->isOpaque()); 4915 case ISD::BSWAP: 4916 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4917 C->isOpaque()); 4918 case ISD::CTPOP: 4919 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4920 C->isOpaque()); 4921 case ISD::CTLZ: 4922 case ISD::CTLZ_ZERO_UNDEF: 4923 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4924 C->isOpaque()); 4925 case ISD::CTTZ: 4926 case ISD::CTTZ_ZERO_UNDEF: 4927 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4928 C->isOpaque()); 4929 case ISD::FP16_TO_FP: { 4930 bool Ignored; 4931 APFloat FPV(APFloat::IEEEhalf(), 4932 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4933 4934 // This can return overflow, underflow, or inexact; we don't care. 4935 // FIXME need to be more flexible about rounding mode. 4936 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4937 APFloat::rmNearestTiesToEven, &Ignored); 4938 return getConstantFP(FPV, DL, VT); 4939 } 4940 case ISD::STEP_VECTOR: { 4941 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4942 return V; 4943 break; 4944 } 4945 } 4946 } 4947 4948 // Constant fold unary operations with a floating point constant operand. 4949 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4950 APFloat V = C->getValueAPF(); // make copy 4951 switch (Opcode) { 4952 case ISD::FNEG: 4953 V.changeSign(); 4954 return getConstantFP(V, DL, VT); 4955 case ISD::FABS: 4956 V.clearSign(); 4957 return getConstantFP(V, DL, VT); 4958 case ISD::FCEIL: { 4959 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4960 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4961 return getConstantFP(V, DL, VT); 4962 break; 4963 } 4964 case ISD::FTRUNC: { 4965 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4966 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4967 return getConstantFP(V, DL, VT); 4968 break; 4969 } 4970 case ISD::FFLOOR: { 4971 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4972 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4973 return getConstantFP(V, DL, VT); 4974 break; 4975 } 4976 case ISD::FP_EXTEND: { 4977 bool ignored; 4978 // This can return overflow, underflow, or inexact; we don't care. 4979 // FIXME need to be more flexible about rounding mode. 4980 (void)V.convert(EVTToAPFloatSemantics(VT), 4981 APFloat::rmNearestTiesToEven, &ignored); 4982 return getConstantFP(V, DL, VT); 4983 } 4984 case ISD::FP_TO_SINT: 4985 case ISD::FP_TO_UINT: { 4986 bool ignored; 4987 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4988 // FIXME need to be more flexible about rounding mode. 4989 APFloat::opStatus s = 4990 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4991 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4992 break; 4993 return getConstant(IntVal, DL, VT); 4994 } 4995 case ISD::BITCAST: 4996 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4997 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4998 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4999 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5000 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 5001 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5002 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 5003 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5004 break; 5005 case ISD::FP_TO_FP16: { 5006 bool Ignored; 5007 // This can return overflow, underflow, or inexact; we don't care. 5008 // FIXME need to be more flexible about rounding mode. 5009 (void)V.convert(APFloat::IEEEhalf(), 5010 APFloat::rmNearestTiesToEven, &Ignored); 5011 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5012 } 5013 } 5014 } 5015 5016 // Constant fold unary operations with a vector integer or float operand. 5017 switch (Opcode) { 5018 default: 5019 // FIXME: Entirely reasonable to perform folding of other unary 5020 // operations here as the need arises. 5021 break; 5022 case ISD::FNEG: 5023 case ISD::FABS: 5024 case ISD::FCEIL: 5025 case ISD::FTRUNC: 5026 case ISD::FFLOOR: 5027 case ISD::FP_EXTEND: 5028 case ISD::FP_TO_SINT: 5029 case ISD::FP_TO_UINT: 5030 case ISD::TRUNCATE: 5031 case ISD::ANY_EXTEND: 5032 case ISD::ZERO_EXTEND: 5033 case ISD::SIGN_EXTEND: 5034 case ISD::UINT_TO_FP: 5035 case ISD::SINT_TO_FP: 5036 case ISD::ABS: 5037 case ISD::BITREVERSE: 5038 case ISD::BSWAP: 5039 case ISD::CTLZ: 5040 case ISD::CTLZ_ZERO_UNDEF: 5041 case ISD::CTTZ: 5042 case ISD::CTTZ_ZERO_UNDEF: 5043 case ISD::CTPOP: { 5044 SDValue Ops = {Operand}; 5045 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5046 return Fold; 5047 } 5048 } 5049 5050 unsigned OpOpcode = Operand.getNode()->getOpcode(); 5051 switch (Opcode) { 5052 case ISD::STEP_VECTOR: 5053 assert(VT.isScalableVector() && 5054 "STEP_VECTOR can only be used with scalable types"); 5055 assert(OpOpcode == ISD::TargetConstant && 5056 VT.getVectorElementType() == Operand.getValueType() && 5057 "Unexpected step operand"); 5058 break; 5059 case ISD::FREEZE: 5060 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5061 if (isGuaranteedNotToBeUndefOrPoison(Operand)) 5062 return Operand; 5063 break; 5064 case ISD::TokenFactor: 5065 case ISD::MERGE_VALUES: 5066 case ISD::CONCAT_VECTORS: 5067 return Operand; // Factor, merge or concat of one node? No need. 5068 case ISD::BUILD_VECTOR: { 5069 // Attempt to simplify BUILD_VECTOR. 5070 SDValue Ops[] = {Operand}; 5071 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5072 return V; 5073 break; 5074 } 5075 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5076 case ISD::FP_EXTEND: 5077 assert(VT.isFloatingPoint() && 5078 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 5079 if (Operand.getValueType() == VT) return Operand; // noop conversion. 5080 assert((!VT.isVector() || 5081 VT.getVectorElementCount() == 5082 Operand.getValueType().getVectorElementCount()) && 5083 "Vector element count mismatch!"); 5084 assert(Operand.getValueType().bitsLT(VT) && 5085 "Invalid fpext node, dst < src!"); 5086 if (Operand.isUndef()) 5087 return getUNDEF(VT); 5088 break; 5089 case ISD::FP_TO_SINT: 5090 case ISD::FP_TO_UINT: 5091 if (Operand.isUndef()) 5092 return getUNDEF(VT); 5093 break; 5094 case ISD::SINT_TO_FP: 5095 case ISD::UINT_TO_FP: 5096 // [us]itofp(undef) = 0, because the result value is bounded. 5097 if (Operand.isUndef()) 5098 return getConstantFP(0.0, DL, VT); 5099 break; 5100 case ISD::SIGN_EXTEND: 5101 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5102 "Invalid SIGN_EXTEND!"); 5103 assert(VT.isVector() == Operand.getValueType().isVector() && 5104 "SIGN_EXTEND result type type should be vector iff the operand " 5105 "type is vector!"); 5106 if (Operand.getValueType() == VT) return Operand; // noop extension 5107 assert((!VT.isVector() || 5108 VT.getVectorElementCount() == 5109 Operand.getValueType().getVectorElementCount()) && 5110 "Vector element count mismatch!"); 5111 assert(Operand.getValueType().bitsLT(VT) && 5112 "Invalid sext node, dst < src!"); 5113 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5114 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5115 if (OpOpcode == ISD::UNDEF) 5116 // sext(undef) = 0, because the top bits will all be the same. 5117 return getConstant(0, DL, VT); 5118 break; 5119 case ISD::ZERO_EXTEND: 5120 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5121 "Invalid ZERO_EXTEND!"); 5122 assert(VT.isVector() == Operand.getValueType().isVector() && 5123 "ZERO_EXTEND result type type should be vector iff the operand " 5124 "type is vector!"); 5125 if (Operand.getValueType() == VT) return Operand; // noop extension 5126 assert((!VT.isVector() || 5127 VT.getVectorElementCount() == 5128 Operand.getValueType().getVectorElementCount()) && 5129 "Vector element count mismatch!"); 5130 assert(Operand.getValueType().bitsLT(VT) && 5131 "Invalid zext node, dst < src!"); 5132 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5133 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5134 if (OpOpcode == ISD::UNDEF) 5135 // zext(undef) = 0, because the top bits will be zero. 5136 return getConstant(0, DL, VT); 5137 break; 5138 case ISD::ANY_EXTEND: 5139 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5140 "Invalid ANY_EXTEND!"); 5141 assert(VT.isVector() == Operand.getValueType().isVector() && 5142 "ANY_EXTEND result type type should be vector iff the operand " 5143 "type is vector!"); 5144 if (Operand.getValueType() == VT) return Operand; // noop extension 5145 assert((!VT.isVector() || 5146 VT.getVectorElementCount() == 5147 Operand.getValueType().getVectorElementCount()) && 5148 "Vector element count mismatch!"); 5149 assert(Operand.getValueType().bitsLT(VT) && 5150 "Invalid anyext node, dst < src!"); 5151 5152 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5153 OpOpcode == ISD::ANY_EXTEND) 5154 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5155 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5156 if (OpOpcode == ISD::UNDEF) 5157 return getUNDEF(VT); 5158 5159 // (ext (trunc x)) -> x 5160 if (OpOpcode == ISD::TRUNCATE) { 5161 SDValue OpOp = Operand.getOperand(0); 5162 if (OpOp.getValueType() == VT) { 5163 transferDbgValues(Operand, OpOp); 5164 return OpOp; 5165 } 5166 } 5167 break; 5168 case ISD::TRUNCATE: 5169 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5170 "Invalid TRUNCATE!"); 5171 assert(VT.isVector() == Operand.getValueType().isVector() && 5172 "TRUNCATE result type type should be vector iff the operand " 5173 "type is vector!"); 5174 if (Operand.getValueType() == VT) return Operand; // noop truncate 5175 assert((!VT.isVector() || 5176 VT.getVectorElementCount() == 5177 Operand.getValueType().getVectorElementCount()) && 5178 "Vector element count mismatch!"); 5179 assert(Operand.getValueType().bitsGT(VT) && 5180 "Invalid truncate node, src < dst!"); 5181 if (OpOpcode == ISD::TRUNCATE) 5182 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5183 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5184 OpOpcode == ISD::ANY_EXTEND) { 5185 // If the source is smaller than the dest, we still need an extend. 5186 if (Operand.getOperand(0).getValueType().getScalarType() 5187 .bitsLT(VT.getScalarType())) 5188 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5189 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5190 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5191 return Operand.getOperand(0); 5192 } 5193 if (OpOpcode == ISD::UNDEF) 5194 return getUNDEF(VT); 5195 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5196 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5197 break; 5198 case ISD::ANY_EXTEND_VECTOR_INREG: 5199 case ISD::ZERO_EXTEND_VECTOR_INREG: 5200 case ISD::SIGN_EXTEND_VECTOR_INREG: 5201 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5202 assert(Operand.getValueType().bitsLE(VT) && 5203 "The input must be the same size or smaller than the result."); 5204 assert(VT.getVectorMinNumElements() < 5205 Operand.getValueType().getVectorMinNumElements() && 5206 "The destination vector type must have fewer lanes than the input."); 5207 break; 5208 case ISD::ABS: 5209 assert(VT.isInteger() && VT == Operand.getValueType() && 5210 "Invalid ABS!"); 5211 if (OpOpcode == ISD::UNDEF) 5212 return getUNDEF(VT); 5213 break; 5214 case ISD::BSWAP: 5215 assert(VT.isInteger() && VT == Operand.getValueType() && 5216 "Invalid BSWAP!"); 5217 assert((VT.getScalarSizeInBits() % 16 == 0) && 5218 "BSWAP types must be a multiple of 16 bits!"); 5219 if (OpOpcode == ISD::UNDEF) 5220 return getUNDEF(VT); 5221 // bswap(bswap(X)) -> X. 5222 if (OpOpcode == ISD::BSWAP) 5223 return Operand.getOperand(0); 5224 break; 5225 case ISD::BITREVERSE: 5226 assert(VT.isInteger() && VT == Operand.getValueType() && 5227 "Invalid BITREVERSE!"); 5228 if (OpOpcode == ISD::UNDEF) 5229 return getUNDEF(VT); 5230 break; 5231 case ISD::BITCAST: 5232 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5233 "Cannot BITCAST between types of different sizes!"); 5234 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5235 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5236 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5237 if (OpOpcode == ISD::UNDEF) 5238 return getUNDEF(VT); 5239 break; 5240 case ISD::SCALAR_TO_VECTOR: 5241 assert(VT.isVector() && !Operand.getValueType().isVector() && 5242 (VT.getVectorElementType() == Operand.getValueType() || 5243 (VT.getVectorElementType().isInteger() && 5244 Operand.getValueType().isInteger() && 5245 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5246 "Illegal SCALAR_TO_VECTOR node!"); 5247 if (OpOpcode == ISD::UNDEF) 5248 return getUNDEF(VT); 5249 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5250 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5251 isa<ConstantSDNode>(Operand.getOperand(1)) && 5252 Operand.getConstantOperandVal(1) == 0 && 5253 Operand.getOperand(0).getValueType() == VT) 5254 return Operand.getOperand(0); 5255 break; 5256 case ISD::FNEG: 5257 // Negation of an unknown bag of bits is still completely undefined. 5258 if (OpOpcode == ISD::UNDEF) 5259 return getUNDEF(VT); 5260 5261 if (OpOpcode == ISD::FNEG) // --X -> X 5262 return Operand.getOperand(0); 5263 break; 5264 case ISD::FABS: 5265 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5266 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5267 break; 5268 case ISD::VSCALE: 5269 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5270 break; 5271 case ISD::CTPOP: 5272 if (Operand.getValueType().getScalarType() == MVT::i1) 5273 return Operand; 5274 break; 5275 case ISD::CTLZ: 5276 case ISD::CTTZ: 5277 if (Operand.getValueType().getScalarType() == MVT::i1) 5278 return getNOT(DL, Operand, Operand.getValueType()); 5279 break; 5280 case ISD::VECREDUCE_SMIN: 5281 case ISD::VECREDUCE_UMAX: 5282 if (Operand.getValueType().getScalarType() == MVT::i1) 5283 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5284 break; 5285 case ISD::VECREDUCE_SMAX: 5286 case ISD::VECREDUCE_UMIN: 5287 if (Operand.getValueType().getScalarType() == MVT::i1) 5288 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5289 break; 5290 } 5291 5292 SDNode *N; 5293 SDVTList VTs = getVTList(VT); 5294 SDValue Ops[] = {Operand}; 5295 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5296 FoldingSetNodeID ID; 5297 AddNodeIDNode(ID, Opcode, VTs, Ops); 5298 void *IP = nullptr; 5299 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5300 E->intersectFlagsWith(Flags); 5301 return SDValue(E, 0); 5302 } 5303 5304 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5305 N->setFlags(Flags); 5306 createOperands(N, Ops); 5307 CSEMap.InsertNode(N, IP); 5308 } else { 5309 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5310 createOperands(N, Ops); 5311 } 5312 5313 InsertNode(N); 5314 SDValue V = SDValue(N, 0); 5315 NewSDValueDbgMsg(V, "Creating new node: ", this); 5316 return V; 5317 } 5318 5319 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5320 const APInt &C2) { 5321 switch (Opcode) { 5322 case ISD::ADD: return C1 + C2; 5323 case ISD::SUB: return C1 - C2; 5324 case ISD::MUL: return C1 * C2; 5325 case ISD::AND: return C1 & C2; 5326 case ISD::OR: return C1 | C2; 5327 case ISD::XOR: return C1 ^ C2; 5328 case ISD::SHL: return C1 << C2; 5329 case ISD::SRL: return C1.lshr(C2); 5330 case ISD::SRA: return C1.ashr(C2); 5331 case ISD::ROTL: return C1.rotl(C2); 5332 case ISD::ROTR: return C1.rotr(C2); 5333 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5334 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5335 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5336 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5337 case ISD::SADDSAT: return C1.sadd_sat(C2); 5338 case ISD::UADDSAT: return C1.uadd_sat(C2); 5339 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5340 case ISD::USUBSAT: return C1.usub_sat(C2); 5341 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5342 case ISD::USHLSAT: return C1.ushl_sat(C2); 5343 case ISD::UDIV: 5344 if (!C2.getBoolValue()) 5345 break; 5346 return C1.udiv(C2); 5347 case ISD::UREM: 5348 if (!C2.getBoolValue()) 5349 break; 5350 return C1.urem(C2); 5351 case ISD::SDIV: 5352 if (!C2.getBoolValue()) 5353 break; 5354 return C1.sdiv(C2); 5355 case ISD::SREM: 5356 if (!C2.getBoolValue()) 5357 break; 5358 return C1.srem(C2); 5359 case ISD::MULHS: { 5360 unsigned FullWidth = C1.getBitWidth() * 2; 5361 APInt C1Ext = C1.sext(FullWidth); 5362 APInt C2Ext = C2.sext(FullWidth); 5363 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5364 } 5365 case ISD::MULHU: { 5366 unsigned FullWidth = C1.getBitWidth() * 2; 5367 APInt C1Ext = C1.zext(FullWidth); 5368 APInt C2Ext = C2.zext(FullWidth); 5369 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5370 } 5371 case ISD::AVGFLOORS: { 5372 unsigned FullWidth = C1.getBitWidth() + 1; 5373 APInt C1Ext = C1.sext(FullWidth); 5374 APInt C2Ext = C2.sext(FullWidth); 5375 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5376 } 5377 case ISD::AVGFLOORU: { 5378 unsigned FullWidth = C1.getBitWidth() + 1; 5379 APInt C1Ext = C1.zext(FullWidth); 5380 APInt C2Ext = C2.zext(FullWidth); 5381 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5382 } 5383 case ISD::AVGCEILS: { 5384 unsigned FullWidth = C1.getBitWidth() + 1; 5385 APInt C1Ext = C1.sext(FullWidth); 5386 APInt C2Ext = C2.sext(FullWidth); 5387 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5388 } 5389 case ISD::AVGCEILU: { 5390 unsigned FullWidth = C1.getBitWidth() + 1; 5391 APInt C1Ext = C1.zext(FullWidth); 5392 APInt C2Ext = C2.zext(FullWidth); 5393 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5394 } 5395 } 5396 return llvm::None; 5397 } 5398 5399 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5400 const GlobalAddressSDNode *GA, 5401 const SDNode *N2) { 5402 if (GA->getOpcode() != ISD::GlobalAddress) 5403 return SDValue(); 5404 if (!TLI->isOffsetFoldingLegal(GA)) 5405 return SDValue(); 5406 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5407 if (!C2) 5408 return SDValue(); 5409 int64_t Offset = C2->getSExtValue(); 5410 switch (Opcode) { 5411 case ISD::ADD: break; 5412 case ISD::SUB: Offset = -uint64_t(Offset); break; 5413 default: return SDValue(); 5414 } 5415 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5416 GA->getOffset() + uint64_t(Offset)); 5417 } 5418 5419 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5420 switch (Opcode) { 5421 case ISD::SDIV: 5422 case ISD::UDIV: 5423 case ISD::SREM: 5424 case ISD::UREM: { 5425 // If a divisor is zero/undef or any element of a divisor vector is 5426 // zero/undef, the whole op is undef. 5427 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5428 SDValue Divisor = Ops[1]; 5429 if (Divisor.isUndef() || isNullConstant(Divisor)) 5430 return true; 5431 5432 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5433 llvm::any_of(Divisor->op_values(), 5434 [](SDValue V) { return V.isUndef() || 5435 isNullConstant(V); }); 5436 // TODO: Handle signed overflow. 5437 } 5438 // TODO: Handle oversized shifts. 5439 default: 5440 return false; 5441 } 5442 } 5443 5444 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5445 EVT VT, ArrayRef<SDValue> Ops) { 5446 // If the opcode is a target-specific ISD node, there's nothing we can 5447 // do here and the operand rules may not line up with the below, so 5448 // bail early. 5449 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5450 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5451 // foldCONCAT_VECTORS in getNode before this is called. 5452 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5453 return SDValue(); 5454 5455 unsigned NumOps = Ops.size(); 5456 if (NumOps == 0) 5457 return SDValue(); 5458 5459 if (isUndef(Opcode, Ops)) 5460 return getUNDEF(VT); 5461 5462 // Handle binops special cases. 5463 if (NumOps == 2) { 5464 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5465 return CFP; 5466 5467 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5468 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5469 if (C1->isOpaque() || C2->isOpaque()) 5470 return SDValue(); 5471 5472 Optional<APInt> FoldAttempt = 5473 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5474 if (!FoldAttempt) 5475 return SDValue(); 5476 5477 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5478 assert((!Folded || !VT.isVector()) && 5479 "Can't fold vectors ops with scalar operands"); 5480 return Folded; 5481 } 5482 } 5483 5484 // fold (add Sym, c) -> Sym+c 5485 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5486 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5487 if (TLI->isCommutativeBinOp(Opcode)) 5488 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5489 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5490 } 5491 5492 // This is for vector folding only from here on. 5493 if (!VT.isVector()) 5494 return SDValue(); 5495 5496 ElementCount NumElts = VT.getVectorElementCount(); 5497 5498 // See if we can fold through bitcasted integer ops. 5499 // TODO: Can we handle undef elements? 5500 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5501 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5502 Ops[0].getOpcode() == ISD::BITCAST && 5503 Ops[1].getOpcode() == ISD::BITCAST) { 5504 SDValue N1 = peekThroughBitcasts(Ops[0]); 5505 SDValue N2 = peekThroughBitcasts(Ops[1]); 5506 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5507 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5508 EVT BVVT = N1.getValueType(); 5509 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5510 bool IsLE = getDataLayout().isLittleEndian(); 5511 unsigned EltBits = VT.getScalarSizeInBits(); 5512 SmallVector<APInt> RawBits1, RawBits2; 5513 BitVector UndefElts1, UndefElts2; 5514 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5515 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5516 UndefElts1.none() && UndefElts2.none()) { 5517 SmallVector<APInt> RawBits; 5518 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5519 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5520 if (!Fold) 5521 break; 5522 RawBits.push_back(Fold.getValue()); 5523 } 5524 if (RawBits.size() == NumElts.getFixedValue()) { 5525 // We have constant folded, but we need to cast this again back to 5526 // the original (possibly legalized) type. 5527 SmallVector<APInt> DstBits; 5528 BitVector DstUndefs; 5529 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5530 DstBits, RawBits, DstUndefs, 5531 BitVector(RawBits.size(), false)); 5532 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5533 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5534 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5535 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5536 if (DstUndefs[I]) 5537 continue; 5538 Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT); 5539 } 5540 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5541 } 5542 } 5543 } 5544 } 5545 5546 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5547 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5548 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5549 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5550 APInt RHSVal; 5551 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5552 APInt NewStep = Opcode == ISD::MUL 5553 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5554 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5555 return getStepVector(DL, VT, NewStep); 5556 } 5557 } 5558 5559 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5560 return !Op.getValueType().isVector() || 5561 Op.getValueType().getVectorElementCount() == NumElts; 5562 }; 5563 5564 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5565 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5566 Op.getOpcode() == ISD::BUILD_VECTOR || 5567 Op.getOpcode() == ISD::SPLAT_VECTOR; 5568 }; 5569 5570 // All operands must be vector types with the same number of elements as 5571 // the result type and must be either UNDEF or a build/splat vector 5572 // or UNDEF scalars. 5573 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5574 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5575 return SDValue(); 5576 5577 // If we are comparing vectors, then the result needs to be a i1 boolean 5578 // that is then sign-extended back to the legal result type. 5579 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5580 5581 // Find legal integer scalar type for constant promotion and 5582 // ensure that its scalar size is at least as large as source. 5583 EVT LegalSVT = VT.getScalarType(); 5584 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5585 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5586 if (LegalSVT.bitsLT(VT.getScalarType())) 5587 return SDValue(); 5588 } 5589 5590 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5591 // only have one operand to check. For fixed-length vector types we may have 5592 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5593 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5594 5595 // Constant fold each scalar lane separately. 5596 SmallVector<SDValue, 4> ScalarResults; 5597 for (unsigned I = 0; I != NumVectorElts; I++) { 5598 SmallVector<SDValue, 4> ScalarOps; 5599 for (SDValue Op : Ops) { 5600 EVT InSVT = Op.getValueType().getScalarType(); 5601 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5602 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5603 if (Op.isUndef()) 5604 ScalarOps.push_back(getUNDEF(InSVT)); 5605 else 5606 ScalarOps.push_back(Op); 5607 continue; 5608 } 5609 5610 SDValue ScalarOp = 5611 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5612 EVT ScalarVT = ScalarOp.getValueType(); 5613 5614 // Build vector (integer) scalar operands may need implicit 5615 // truncation - do this before constant folding. 5616 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 5617 // Don't create illegally-typed nodes unless they're constants or undef 5618 // - if we fail to constant fold we can't guarantee the (dead) nodes 5619 // we're creating will be cleaned up before being visited for 5620 // legalization. 5621 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 5622 !isa<ConstantSDNode>(ScalarOp) && 5623 TLI->getTypeAction(*getContext(), InSVT) != 5624 TargetLowering::TypeLegal) 5625 return SDValue(); 5626 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5627 } 5628 5629 ScalarOps.push_back(ScalarOp); 5630 } 5631 5632 // Constant fold the scalar operands. 5633 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5634 5635 // Legalize the (integer) scalar constant if necessary. 5636 if (LegalSVT != SVT) 5637 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5638 5639 // Scalar folding only succeeded if the result is a constant or UNDEF. 5640 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5641 ScalarResult.getOpcode() != ISD::ConstantFP) 5642 return SDValue(); 5643 ScalarResults.push_back(ScalarResult); 5644 } 5645 5646 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5647 : getBuildVector(VT, DL, ScalarResults); 5648 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5649 return V; 5650 } 5651 5652 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5653 EVT VT, SDValue N1, SDValue N2) { 5654 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5655 // should. That will require dealing with a potentially non-default 5656 // rounding mode, checking the "opStatus" return value from the APFloat 5657 // math calculations, and possibly other variations. 5658 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5659 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5660 if (N1CFP && N2CFP) { 5661 APFloat C1 = N1CFP->getValueAPF(); // make copy 5662 const APFloat &C2 = N2CFP->getValueAPF(); 5663 switch (Opcode) { 5664 case ISD::FADD: 5665 C1.add(C2, APFloat::rmNearestTiesToEven); 5666 return getConstantFP(C1, DL, VT); 5667 case ISD::FSUB: 5668 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5669 return getConstantFP(C1, DL, VT); 5670 case ISD::FMUL: 5671 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5672 return getConstantFP(C1, DL, VT); 5673 case ISD::FDIV: 5674 C1.divide(C2, APFloat::rmNearestTiesToEven); 5675 return getConstantFP(C1, DL, VT); 5676 case ISD::FREM: 5677 C1.mod(C2); 5678 return getConstantFP(C1, DL, VT); 5679 case ISD::FCOPYSIGN: 5680 C1.copySign(C2); 5681 return getConstantFP(C1, DL, VT); 5682 case ISD::FMINNUM: 5683 return getConstantFP(minnum(C1, C2), DL, VT); 5684 case ISD::FMAXNUM: 5685 return getConstantFP(maxnum(C1, C2), DL, VT); 5686 case ISD::FMINIMUM: 5687 return getConstantFP(minimum(C1, C2), DL, VT); 5688 case ISD::FMAXIMUM: 5689 return getConstantFP(maximum(C1, C2), DL, VT); 5690 default: break; 5691 } 5692 } 5693 if (N1CFP && Opcode == ISD::FP_ROUND) { 5694 APFloat C1 = N1CFP->getValueAPF(); // make copy 5695 bool Unused; 5696 // This can return overflow, underflow, or inexact; we don't care. 5697 // FIXME need to be more flexible about rounding mode. 5698 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5699 &Unused); 5700 return getConstantFP(C1, DL, VT); 5701 } 5702 5703 switch (Opcode) { 5704 case ISD::FSUB: 5705 // -0.0 - undef --> undef (consistent with "fneg undef") 5706 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5707 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5708 return getUNDEF(VT); 5709 LLVM_FALLTHROUGH; 5710 5711 case ISD::FADD: 5712 case ISD::FMUL: 5713 case ISD::FDIV: 5714 case ISD::FREM: 5715 // If both operands are undef, the result is undef. If 1 operand is undef, 5716 // the result is NaN. This should match the behavior of the IR optimizer. 5717 if (N1.isUndef() && N2.isUndef()) 5718 return getUNDEF(VT); 5719 if (N1.isUndef() || N2.isUndef()) 5720 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5721 } 5722 return SDValue(); 5723 } 5724 5725 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5726 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5727 5728 // There's no need to assert on a byte-aligned pointer. All pointers are at 5729 // least byte aligned. 5730 if (A == Align(1)) 5731 return Val; 5732 5733 FoldingSetNodeID ID; 5734 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5735 ID.AddInteger(A.value()); 5736 5737 void *IP = nullptr; 5738 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5739 return SDValue(E, 0); 5740 5741 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5742 Val.getValueType(), A); 5743 createOperands(N, {Val}); 5744 5745 CSEMap.InsertNode(N, IP); 5746 InsertNode(N); 5747 5748 SDValue V(N, 0); 5749 NewSDValueDbgMsg(V, "Creating new node: ", this); 5750 return V; 5751 } 5752 5753 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5754 SDValue N1, SDValue N2) { 5755 SDNodeFlags Flags; 5756 if (Inserter) 5757 Flags = Inserter->getFlags(); 5758 return getNode(Opcode, DL, VT, N1, N2, Flags); 5759 } 5760 5761 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5762 SDValue &N2) const { 5763 if (!TLI->isCommutativeBinOp(Opcode)) 5764 return; 5765 5766 // Canonicalize: 5767 // binop(const, nonconst) -> binop(nonconst, const) 5768 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5769 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5770 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5771 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5772 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5773 std::swap(N1, N2); 5774 5775 // Canonicalize: 5776 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5777 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5778 N2.getOpcode() == ISD::STEP_VECTOR) 5779 std::swap(N1, N2); 5780 } 5781 5782 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5783 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5784 assert(N1.getOpcode() != ISD::DELETED_NODE && 5785 N2.getOpcode() != ISD::DELETED_NODE && 5786 "Operand is DELETED_NODE!"); 5787 5788 canonicalizeCommutativeBinop(Opcode, N1, N2); 5789 5790 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5791 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5792 5793 // Don't allow undefs in vector splats - we might be returning N2 when folding 5794 // to zero etc. 5795 ConstantSDNode *N2CV = 5796 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5797 5798 switch (Opcode) { 5799 default: break; 5800 case ISD::TokenFactor: 5801 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5802 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5803 // Fold trivial token factors. 5804 if (N1.getOpcode() == ISD::EntryToken) return N2; 5805 if (N2.getOpcode() == ISD::EntryToken) return N1; 5806 if (N1 == N2) return N1; 5807 break; 5808 case ISD::BUILD_VECTOR: { 5809 // Attempt to simplify BUILD_VECTOR. 5810 SDValue Ops[] = {N1, N2}; 5811 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5812 return V; 5813 break; 5814 } 5815 case ISD::CONCAT_VECTORS: { 5816 SDValue Ops[] = {N1, N2}; 5817 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5818 return V; 5819 break; 5820 } 5821 case ISD::AND: 5822 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5823 assert(N1.getValueType() == N2.getValueType() && 5824 N1.getValueType() == VT && "Binary operator types must match!"); 5825 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5826 // worth handling here. 5827 if (N2CV && N2CV->isZero()) 5828 return N2; 5829 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5830 return N1; 5831 break; 5832 case ISD::OR: 5833 case ISD::XOR: 5834 case ISD::ADD: 5835 case ISD::SUB: 5836 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5837 assert(N1.getValueType() == N2.getValueType() && 5838 N1.getValueType() == VT && "Binary operator types must match!"); 5839 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5840 // it's worth handling here. 5841 if (N2CV && N2CV->isZero()) 5842 return N1; 5843 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5844 VT.getVectorElementType() == MVT::i1) 5845 return getNode(ISD::XOR, DL, VT, N1, N2); 5846 break; 5847 case ISD::MUL: 5848 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5849 assert(N1.getValueType() == N2.getValueType() && 5850 N1.getValueType() == VT && "Binary operator types must match!"); 5851 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5852 return getNode(ISD::AND, DL, VT, N1, N2); 5853 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5854 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5855 const APInt &N2CImm = N2C->getAPIntValue(); 5856 return getVScale(DL, VT, MulImm * N2CImm); 5857 } 5858 break; 5859 case ISD::UDIV: 5860 case ISD::UREM: 5861 case ISD::MULHU: 5862 case ISD::MULHS: 5863 case ISD::SDIV: 5864 case ISD::SREM: 5865 case ISD::SADDSAT: 5866 case ISD::SSUBSAT: 5867 case ISD::UADDSAT: 5868 case ISD::USUBSAT: 5869 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5870 assert(N1.getValueType() == N2.getValueType() && 5871 N1.getValueType() == VT && "Binary operator types must match!"); 5872 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5873 // fold (add_sat x, y) -> (or x, y) for bool types. 5874 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5875 return getNode(ISD::OR, DL, VT, N1, N2); 5876 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5877 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5878 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5879 } 5880 break; 5881 case ISD::SMIN: 5882 case ISD::UMAX: 5883 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5884 assert(N1.getValueType() == N2.getValueType() && 5885 N1.getValueType() == VT && "Binary operator types must match!"); 5886 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5887 return getNode(ISD::OR, DL, VT, N1, N2); 5888 break; 5889 case ISD::SMAX: 5890 case ISD::UMIN: 5891 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5892 assert(N1.getValueType() == N2.getValueType() && 5893 N1.getValueType() == VT && "Binary operator types must match!"); 5894 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5895 return getNode(ISD::AND, DL, VT, N1, N2); 5896 break; 5897 case ISD::FADD: 5898 case ISD::FSUB: 5899 case ISD::FMUL: 5900 case ISD::FDIV: 5901 case ISD::FREM: 5902 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5903 assert(N1.getValueType() == N2.getValueType() && 5904 N1.getValueType() == VT && "Binary operator types must match!"); 5905 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5906 return V; 5907 break; 5908 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5909 assert(N1.getValueType() == VT && 5910 N1.getValueType().isFloatingPoint() && 5911 N2.getValueType().isFloatingPoint() && 5912 "Invalid FCOPYSIGN!"); 5913 break; 5914 case ISD::SHL: 5915 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5916 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5917 const APInt &ShiftImm = N2C->getAPIntValue(); 5918 return getVScale(DL, VT, MulImm << ShiftImm); 5919 } 5920 LLVM_FALLTHROUGH; 5921 case ISD::SRA: 5922 case ISD::SRL: 5923 if (SDValue V = simplifyShift(N1, N2)) 5924 return V; 5925 LLVM_FALLTHROUGH; 5926 case ISD::ROTL: 5927 case ISD::ROTR: 5928 assert(VT == N1.getValueType() && 5929 "Shift operators return type must be the same as their first arg"); 5930 assert(VT.isInteger() && N2.getValueType().isInteger() && 5931 "Shifts only work on integers"); 5932 assert((!VT.isVector() || VT == N2.getValueType()) && 5933 "Vector shift amounts must be in the same as their first arg"); 5934 // Verify that the shift amount VT is big enough to hold valid shift 5935 // amounts. This catches things like trying to shift an i1024 value by an 5936 // i8, which is easy to fall into in generic code that uses 5937 // TLI.getShiftAmount(). 5938 assert(N2.getValueType().getScalarSizeInBits() >= 5939 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5940 "Invalid use of small shift amount with oversized value!"); 5941 5942 // Always fold shifts of i1 values so the code generator doesn't need to 5943 // handle them. Since we know the size of the shift has to be less than the 5944 // size of the value, the shift/rotate count is guaranteed to be zero. 5945 if (VT == MVT::i1) 5946 return N1; 5947 if (N2CV && N2CV->isZero()) 5948 return N1; 5949 break; 5950 case ISD::FP_ROUND: 5951 assert(VT.isFloatingPoint() && 5952 N1.getValueType().isFloatingPoint() && 5953 VT.bitsLE(N1.getValueType()) && 5954 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5955 "Invalid FP_ROUND!"); 5956 if (N1.getValueType() == VT) return N1; // noop conversion. 5957 break; 5958 case ISD::AssertSext: 5959 case ISD::AssertZext: { 5960 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5961 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5962 assert(VT.isInteger() && EVT.isInteger() && 5963 "Cannot *_EXTEND_INREG FP types"); 5964 assert(!EVT.isVector() && 5965 "AssertSExt/AssertZExt type should be the vector element type " 5966 "rather than the vector type!"); 5967 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5968 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5969 break; 5970 } 5971 case ISD::SIGN_EXTEND_INREG: { 5972 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5973 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5974 assert(VT.isInteger() && EVT.isInteger() && 5975 "Cannot *_EXTEND_INREG FP types"); 5976 assert(EVT.isVector() == VT.isVector() && 5977 "SIGN_EXTEND_INREG type should be vector iff the operand " 5978 "type is vector!"); 5979 assert((!EVT.isVector() || 5980 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5981 "Vector element counts must match in SIGN_EXTEND_INREG"); 5982 assert(EVT.bitsLE(VT) && "Not extending!"); 5983 if (EVT == VT) return N1; // Not actually extending 5984 5985 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5986 unsigned FromBits = EVT.getScalarSizeInBits(); 5987 Val <<= Val.getBitWidth() - FromBits; 5988 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5989 return getConstant(Val, DL, ConstantVT); 5990 }; 5991 5992 if (N1C) { 5993 const APInt &Val = N1C->getAPIntValue(); 5994 return SignExtendInReg(Val, VT); 5995 } 5996 5997 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5998 SmallVector<SDValue, 8> Ops; 5999 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 6000 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6001 SDValue Op = N1.getOperand(i); 6002 if (Op.isUndef()) { 6003 Ops.push_back(getUNDEF(OpVT)); 6004 continue; 6005 } 6006 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6007 APInt Val = C->getAPIntValue(); 6008 Ops.push_back(SignExtendInReg(Val, OpVT)); 6009 } 6010 return getBuildVector(VT, DL, Ops); 6011 } 6012 break; 6013 } 6014 case ISD::FP_TO_SINT_SAT: 6015 case ISD::FP_TO_UINT_SAT: { 6016 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6017 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6018 assert(N1.getValueType().isVector() == VT.isVector() && 6019 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6020 "vector!"); 6021 assert((!VT.isVector() || VT.getVectorNumElements() == 6022 N1.getValueType().getVectorNumElements()) && 6023 "Vector element counts must match in FP_TO_*INT_SAT"); 6024 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6025 "Type to saturate to must be a scalar."); 6026 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6027 "Not extending!"); 6028 break; 6029 } 6030 case ISD::EXTRACT_VECTOR_ELT: 6031 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6032 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6033 element type of the vector."); 6034 6035 // Extract from an undefined value or using an undefined index is undefined. 6036 if (N1.isUndef() || N2.isUndef()) 6037 return getUNDEF(VT); 6038 6039 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6040 // vectors. For scalable vectors we will provide appropriate support for 6041 // dealing with arbitrary indices. 6042 if (N2C && N1.getValueType().isFixedLengthVector() && 6043 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6044 return getUNDEF(VT); 6045 6046 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6047 // expanding copies of large vectors from registers. This only works for 6048 // fixed length vectors, since we need to know the exact number of 6049 // elements. 6050 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6051 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6052 unsigned Factor = 6053 N1.getOperand(0).getValueType().getVectorNumElements(); 6054 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6055 N1.getOperand(N2C->getZExtValue() / Factor), 6056 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6057 } 6058 6059 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6060 // lowering is expanding large vector constants. 6061 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6062 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6063 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6064 N1.getValueType().isFixedLengthVector()) && 6065 "BUILD_VECTOR used for scalable vectors"); 6066 unsigned Index = 6067 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6068 SDValue Elt = N1.getOperand(Index); 6069 6070 if (VT != Elt.getValueType()) 6071 // If the vector element type is not legal, the BUILD_VECTOR operands 6072 // are promoted and implicitly truncated, and the result implicitly 6073 // extended. Make that explicit here. 6074 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6075 6076 return Elt; 6077 } 6078 6079 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6080 // operations are lowered to scalars. 6081 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6082 // If the indices are the same, return the inserted element else 6083 // if the indices are known different, extract the element from 6084 // the original vector. 6085 SDValue N1Op2 = N1.getOperand(2); 6086 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6087 6088 if (N1Op2C && N2C) { 6089 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6090 if (VT == N1.getOperand(1).getValueType()) 6091 return N1.getOperand(1); 6092 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6093 } 6094 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6095 } 6096 } 6097 6098 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6099 // when vector types are scalarized and v1iX is legal. 6100 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6101 // Here we are completely ignoring the extract element index (N2), 6102 // which is fine for fixed width vectors, since any index other than 0 6103 // is undefined anyway. However, this cannot be ignored for scalable 6104 // vectors - in theory we could support this, but we don't want to do this 6105 // without a profitability check. 6106 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6107 N1.getValueType().isFixedLengthVector() && 6108 N1.getValueType().getVectorNumElements() == 1) { 6109 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6110 N1.getOperand(1)); 6111 } 6112 break; 6113 case ISD::EXTRACT_ELEMENT: 6114 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6115 assert(!N1.getValueType().isVector() && !VT.isVector() && 6116 (N1.getValueType().isInteger() == VT.isInteger()) && 6117 N1.getValueType() != VT && 6118 "Wrong types for EXTRACT_ELEMENT!"); 6119 6120 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6121 // 64-bit integers into 32-bit parts. Instead of building the extract of 6122 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6123 if (N1.getOpcode() == ISD::BUILD_PAIR) 6124 return N1.getOperand(N2C->getZExtValue()); 6125 6126 // EXTRACT_ELEMENT of a constant int is also very common. 6127 if (N1C) { 6128 unsigned ElementSize = VT.getSizeInBits(); 6129 unsigned Shift = ElementSize * N2C->getZExtValue(); 6130 const APInt &Val = N1C->getAPIntValue(); 6131 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6132 } 6133 break; 6134 case ISD::EXTRACT_SUBVECTOR: { 6135 EVT N1VT = N1.getValueType(); 6136 assert(VT.isVector() && N1VT.isVector() && 6137 "Extract subvector VTs must be vectors!"); 6138 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6139 "Extract subvector VTs must have the same element type!"); 6140 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6141 "Cannot extract a scalable vector from a fixed length vector!"); 6142 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6143 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6144 "Extract subvector must be from larger vector to smaller vector!"); 6145 assert(N2C && "Extract subvector index must be a constant"); 6146 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6147 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6148 N1VT.getVectorMinNumElements()) && 6149 "Extract subvector overflow!"); 6150 assert(N2C->getAPIntValue().getBitWidth() == 6151 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6152 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6153 6154 // Trivial extraction. 6155 if (VT == N1VT) 6156 return N1; 6157 6158 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6159 if (N1.isUndef()) 6160 return getUNDEF(VT); 6161 6162 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6163 // the concat have the same type as the extract. 6164 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6165 VT == N1.getOperand(0).getValueType()) { 6166 unsigned Factor = VT.getVectorMinNumElements(); 6167 return N1.getOperand(N2C->getZExtValue() / Factor); 6168 } 6169 6170 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6171 // during shuffle legalization. 6172 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6173 VT == N1.getOperand(1).getValueType()) 6174 return N1.getOperand(1); 6175 break; 6176 } 6177 } 6178 6179 // Perform trivial constant folding. 6180 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6181 return SV; 6182 6183 // Canonicalize an UNDEF to the RHS, even over a constant. 6184 if (N1.isUndef()) { 6185 if (TLI->isCommutativeBinOp(Opcode)) { 6186 std::swap(N1, N2); 6187 } else { 6188 switch (Opcode) { 6189 case ISD::SIGN_EXTEND_INREG: 6190 case ISD::SUB: 6191 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6192 case ISD::UDIV: 6193 case ISD::SDIV: 6194 case ISD::UREM: 6195 case ISD::SREM: 6196 case ISD::SSUBSAT: 6197 case ISD::USUBSAT: 6198 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6199 } 6200 } 6201 } 6202 6203 // Fold a bunch of operators when the RHS is undef. 6204 if (N2.isUndef()) { 6205 switch (Opcode) { 6206 case ISD::XOR: 6207 if (N1.isUndef()) 6208 // Handle undef ^ undef -> 0 special case. This is a common 6209 // idiom (misuse). 6210 return getConstant(0, DL, VT); 6211 LLVM_FALLTHROUGH; 6212 case ISD::ADD: 6213 case ISD::SUB: 6214 case ISD::UDIV: 6215 case ISD::SDIV: 6216 case ISD::UREM: 6217 case ISD::SREM: 6218 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6219 case ISD::MUL: 6220 case ISD::AND: 6221 case ISD::SSUBSAT: 6222 case ISD::USUBSAT: 6223 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6224 case ISD::OR: 6225 case ISD::SADDSAT: 6226 case ISD::UADDSAT: 6227 return getAllOnesConstant(DL, VT); 6228 } 6229 } 6230 6231 // Memoize this node if possible. 6232 SDNode *N; 6233 SDVTList VTs = getVTList(VT); 6234 SDValue Ops[] = {N1, N2}; 6235 if (VT != MVT::Glue) { 6236 FoldingSetNodeID ID; 6237 AddNodeIDNode(ID, Opcode, VTs, Ops); 6238 void *IP = nullptr; 6239 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6240 E->intersectFlagsWith(Flags); 6241 return SDValue(E, 0); 6242 } 6243 6244 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6245 N->setFlags(Flags); 6246 createOperands(N, Ops); 6247 CSEMap.InsertNode(N, IP); 6248 } else { 6249 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6250 createOperands(N, Ops); 6251 } 6252 6253 InsertNode(N); 6254 SDValue V = SDValue(N, 0); 6255 NewSDValueDbgMsg(V, "Creating new node: ", this); 6256 return V; 6257 } 6258 6259 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6260 SDValue N1, SDValue N2, SDValue N3) { 6261 SDNodeFlags Flags; 6262 if (Inserter) 6263 Flags = Inserter->getFlags(); 6264 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6265 } 6266 6267 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6268 SDValue N1, SDValue N2, SDValue N3, 6269 const SDNodeFlags Flags) { 6270 assert(N1.getOpcode() != ISD::DELETED_NODE && 6271 N2.getOpcode() != ISD::DELETED_NODE && 6272 N3.getOpcode() != ISD::DELETED_NODE && 6273 "Operand is DELETED_NODE!"); 6274 // Perform various simplifications. 6275 switch (Opcode) { 6276 case ISD::FMA: { 6277 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6278 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6279 N3.getValueType() == VT && "FMA types must match!"); 6280 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6281 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6282 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6283 if (N1CFP && N2CFP && N3CFP) { 6284 APFloat V1 = N1CFP->getValueAPF(); 6285 const APFloat &V2 = N2CFP->getValueAPF(); 6286 const APFloat &V3 = N3CFP->getValueAPF(); 6287 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6288 return getConstantFP(V1, DL, VT); 6289 } 6290 break; 6291 } 6292 case ISD::BUILD_VECTOR: { 6293 // Attempt to simplify BUILD_VECTOR. 6294 SDValue Ops[] = {N1, N2, N3}; 6295 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6296 return V; 6297 break; 6298 } 6299 case ISD::CONCAT_VECTORS: { 6300 SDValue Ops[] = {N1, N2, N3}; 6301 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6302 return V; 6303 break; 6304 } 6305 case ISD::SETCC: { 6306 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6307 assert(N1.getValueType() == N2.getValueType() && 6308 "SETCC operands must have the same type!"); 6309 assert(VT.isVector() == N1.getValueType().isVector() && 6310 "SETCC type should be vector iff the operand type is vector!"); 6311 assert((!VT.isVector() || VT.getVectorElementCount() == 6312 N1.getValueType().getVectorElementCount()) && 6313 "SETCC vector element counts must match!"); 6314 // Use FoldSetCC to simplify SETCC's. 6315 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6316 return V; 6317 // Vector constant folding. 6318 SDValue Ops[] = {N1, N2, N3}; 6319 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6320 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6321 return V; 6322 } 6323 break; 6324 } 6325 case ISD::SELECT: 6326 case ISD::VSELECT: 6327 if (SDValue V = simplifySelect(N1, N2, N3)) 6328 return V; 6329 break; 6330 case ISD::VECTOR_SHUFFLE: 6331 llvm_unreachable("should use getVectorShuffle constructor!"); 6332 case ISD::VECTOR_SPLICE: { 6333 if (cast<ConstantSDNode>(N3)->isNullValue()) 6334 return N1; 6335 break; 6336 } 6337 case ISD::INSERT_VECTOR_ELT: { 6338 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6339 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6340 // for scalable vectors where we will generate appropriate code to 6341 // deal with out-of-bounds cases correctly. 6342 if (N3C && N1.getValueType().isFixedLengthVector() && 6343 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6344 return getUNDEF(VT); 6345 6346 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6347 if (N3.isUndef()) 6348 return getUNDEF(VT); 6349 6350 // If the inserted element is an UNDEF, just use the input vector. 6351 if (N2.isUndef()) 6352 return N1; 6353 6354 break; 6355 } 6356 case ISD::INSERT_SUBVECTOR: { 6357 // Inserting undef into undef is still undef. 6358 if (N1.isUndef() && N2.isUndef()) 6359 return getUNDEF(VT); 6360 6361 EVT N2VT = N2.getValueType(); 6362 assert(VT == N1.getValueType() && 6363 "Dest and insert subvector source types must match!"); 6364 assert(VT.isVector() && N2VT.isVector() && 6365 "Insert subvector VTs must be vectors!"); 6366 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6367 "Cannot insert a scalable vector into a fixed length vector!"); 6368 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6369 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6370 "Insert subvector must be from smaller vector to larger vector!"); 6371 assert(isa<ConstantSDNode>(N3) && 6372 "Insert subvector index must be constant"); 6373 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6374 (N2VT.getVectorMinNumElements() + 6375 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6376 VT.getVectorMinNumElements()) && 6377 "Insert subvector overflow!"); 6378 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6379 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6380 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6381 6382 // Trivial insertion. 6383 if (VT == N2VT) 6384 return N2; 6385 6386 // If this is an insert of an extracted vector into an undef vector, we 6387 // can just use the input to the extract. 6388 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6389 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6390 return N2.getOperand(0); 6391 break; 6392 } 6393 case ISD::BITCAST: 6394 // Fold bit_convert nodes from a type to themselves. 6395 if (N1.getValueType() == VT) 6396 return N1; 6397 break; 6398 } 6399 6400 // Memoize node if it doesn't produce a flag. 6401 SDNode *N; 6402 SDVTList VTs = getVTList(VT); 6403 SDValue Ops[] = {N1, N2, N3}; 6404 if (VT != MVT::Glue) { 6405 FoldingSetNodeID ID; 6406 AddNodeIDNode(ID, Opcode, VTs, Ops); 6407 void *IP = nullptr; 6408 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6409 E->intersectFlagsWith(Flags); 6410 return SDValue(E, 0); 6411 } 6412 6413 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6414 N->setFlags(Flags); 6415 createOperands(N, Ops); 6416 CSEMap.InsertNode(N, IP); 6417 } else { 6418 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6419 createOperands(N, Ops); 6420 } 6421 6422 InsertNode(N); 6423 SDValue V = SDValue(N, 0); 6424 NewSDValueDbgMsg(V, "Creating new node: ", this); 6425 return V; 6426 } 6427 6428 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6429 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6430 SDValue Ops[] = { N1, N2, N3, N4 }; 6431 return getNode(Opcode, DL, VT, Ops); 6432 } 6433 6434 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6435 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6436 SDValue N5) { 6437 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6438 return getNode(Opcode, DL, VT, Ops); 6439 } 6440 6441 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6442 /// the incoming stack arguments to be loaded from the stack. 6443 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6444 SmallVector<SDValue, 8> ArgChains; 6445 6446 // Include the original chain at the beginning of the list. When this is 6447 // used by target LowerCall hooks, this helps legalize find the 6448 // CALLSEQ_BEGIN node. 6449 ArgChains.push_back(Chain); 6450 6451 // Add a chain value for each stack argument. 6452 for (SDNode *U : getEntryNode().getNode()->uses()) 6453 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6454 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6455 if (FI->getIndex() < 0) 6456 ArgChains.push_back(SDValue(L, 1)); 6457 6458 // Build a tokenfactor for all the chains. 6459 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6460 } 6461 6462 /// getMemsetValue - Vectorized representation of the memset value 6463 /// operand. 6464 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6465 const SDLoc &dl) { 6466 assert(!Value.isUndef()); 6467 6468 unsigned NumBits = VT.getScalarSizeInBits(); 6469 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6470 assert(C->getAPIntValue().getBitWidth() == 8); 6471 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6472 if (VT.isInteger()) { 6473 bool IsOpaque = VT.getSizeInBits() > 64 || 6474 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6475 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6476 } 6477 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6478 VT); 6479 } 6480 6481 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6482 EVT IntVT = VT.getScalarType(); 6483 if (!IntVT.isInteger()) 6484 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6485 6486 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6487 if (NumBits > 8) { 6488 // Use a multiplication with 0x010101... to extend the input to the 6489 // required length. 6490 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6491 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6492 DAG.getConstant(Magic, dl, IntVT)); 6493 } 6494 6495 if (VT != Value.getValueType() && !VT.isInteger()) 6496 Value = DAG.getBitcast(VT.getScalarType(), Value); 6497 if (VT != Value.getValueType()) 6498 Value = DAG.getSplatBuildVector(VT, dl, Value); 6499 6500 return Value; 6501 } 6502 6503 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6504 /// used when a memcpy is turned into a memset when the source is a constant 6505 /// string ptr. 6506 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6507 const TargetLowering &TLI, 6508 const ConstantDataArraySlice &Slice) { 6509 // Handle vector with all elements zero. 6510 if (Slice.Array == nullptr) { 6511 if (VT.isInteger()) 6512 return DAG.getConstant(0, dl, VT); 6513 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6514 return DAG.getConstantFP(0.0, dl, VT); 6515 if (VT.isVector()) { 6516 unsigned NumElts = VT.getVectorNumElements(); 6517 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6518 return DAG.getNode(ISD::BITCAST, dl, VT, 6519 DAG.getConstant(0, dl, 6520 EVT::getVectorVT(*DAG.getContext(), 6521 EltVT, NumElts))); 6522 } 6523 llvm_unreachable("Expected type!"); 6524 } 6525 6526 assert(!VT.isVector() && "Can't handle vector type here!"); 6527 unsigned NumVTBits = VT.getSizeInBits(); 6528 unsigned NumVTBytes = NumVTBits / 8; 6529 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6530 6531 APInt Val(NumVTBits, 0); 6532 if (DAG.getDataLayout().isLittleEndian()) { 6533 for (unsigned i = 0; i != NumBytes; ++i) 6534 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6535 } else { 6536 for (unsigned i = 0; i != NumBytes; ++i) 6537 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6538 } 6539 6540 // If the "cost" of materializing the integer immediate is less than the cost 6541 // of a load, then it is cost effective to turn the load into the immediate. 6542 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6543 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6544 return DAG.getConstant(Val, dl, VT); 6545 return SDValue(); 6546 } 6547 6548 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6549 const SDLoc &DL, 6550 const SDNodeFlags Flags) { 6551 EVT VT = Base.getValueType(); 6552 SDValue Index; 6553 6554 if (Offset.isScalable()) 6555 Index = getVScale(DL, Base.getValueType(), 6556 APInt(Base.getValueSizeInBits().getFixedSize(), 6557 Offset.getKnownMinSize())); 6558 else 6559 Index = getConstant(Offset.getFixedSize(), DL, VT); 6560 6561 return getMemBasePlusOffset(Base, Index, DL, Flags); 6562 } 6563 6564 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6565 const SDLoc &DL, 6566 const SDNodeFlags Flags) { 6567 assert(Offset.getValueType().isInteger()); 6568 EVT BasePtrVT = Ptr.getValueType(); 6569 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6570 } 6571 6572 /// Returns true if memcpy source is constant data. 6573 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6574 uint64_t SrcDelta = 0; 6575 GlobalAddressSDNode *G = nullptr; 6576 if (Src.getOpcode() == ISD::GlobalAddress) 6577 G = cast<GlobalAddressSDNode>(Src); 6578 else if (Src.getOpcode() == ISD::ADD && 6579 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6580 Src.getOperand(1).getOpcode() == ISD::Constant) { 6581 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6582 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6583 } 6584 if (!G) 6585 return false; 6586 6587 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6588 SrcDelta + G->getOffset()); 6589 } 6590 6591 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6592 SelectionDAG &DAG) { 6593 // On Darwin, -Os means optimize for size without hurting performance, so 6594 // only really optimize for size when -Oz (MinSize) is used. 6595 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6596 return MF.getFunction().hasMinSize(); 6597 return DAG.shouldOptForSize(); 6598 } 6599 6600 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6601 SmallVector<SDValue, 32> &OutChains, unsigned From, 6602 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6603 SmallVector<SDValue, 16> &OutStoreChains) { 6604 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6605 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6606 SmallVector<SDValue, 16> GluedLoadChains; 6607 for (unsigned i = From; i < To; ++i) { 6608 OutChains.push_back(OutLoadChains[i]); 6609 GluedLoadChains.push_back(OutLoadChains[i]); 6610 } 6611 6612 // Chain for all loads. 6613 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6614 GluedLoadChains); 6615 6616 for (unsigned i = From; i < To; ++i) { 6617 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6618 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6619 ST->getBasePtr(), ST->getMemoryVT(), 6620 ST->getMemOperand()); 6621 OutChains.push_back(NewStore); 6622 } 6623 } 6624 6625 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6626 SDValue Chain, SDValue Dst, SDValue Src, 6627 uint64_t Size, Align Alignment, 6628 bool isVol, bool AlwaysInline, 6629 MachinePointerInfo DstPtrInfo, 6630 MachinePointerInfo SrcPtrInfo, 6631 const AAMDNodes &AAInfo) { 6632 // Turn a memcpy of undef to nop. 6633 // FIXME: We need to honor volatile even is Src is undef. 6634 if (Src.isUndef()) 6635 return Chain; 6636 6637 // Expand memcpy to a series of load and store ops if the size operand falls 6638 // below a certain threshold. 6639 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6640 // rather than maybe a humongous number of loads and stores. 6641 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6642 const DataLayout &DL = DAG.getDataLayout(); 6643 LLVMContext &C = *DAG.getContext(); 6644 std::vector<EVT> MemOps; 6645 bool DstAlignCanChange = false; 6646 MachineFunction &MF = DAG.getMachineFunction(); 6647 MachineFrameInfo &MFI = MF.getFrameInfo(); 6648 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6649 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6650 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6651 DstAlignCanChange = true; 6652 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6653 if (!SrcAlign || Alignment > *SrcAlign) 6654 SrcAlign = Alignment; 6655 assert(SrcAlign && "SrcAlign must be set"); 6656 ConstantDataArraySlice Slice; 6657 // If marked as volatile, perform a copy even when marked as constant. 6658 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6659 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6660 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6661 const MemOp Op = isZeroConstant 6662 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6663 /*IsZeroMemset*/ true, isVol) 6664 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6665 *SrcAlign, isVol, CopyFromConstant); 6666 if (!TLI.findOptimalMemOpLowering( 6667 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6668 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6669 return SDValue(); 6670 6671 if (DstAlignCanChange) { 6672 Type *Ty = MemOps[0].getTypeForEVT(C); 6673 Align NewAlign = DL.getABITypeAlign(Ty); 6674 6675 // Don't promote to an alignment that would require dynamic stack 6676 // realignment. 6677 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6678 if (!TRI->hasStackRealignment(MF)) 6679 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6680 NewAlign = NewAlign / 2; 6681 6682 if (NewAlign > Alignment) { 6683 // Give the stack frame object a larger alignment if needed. 6684 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6685 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6686 Alignment = NewAlign; 6687 } 6688 } 6689 6690 // Prepare AAInfo for loads/stores after lowering this memcpy. 6691 AAMDNodes NewAAInfo = AAInfo; 6692 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6693 6694 MachineMemOperand::Flags MMOFlags = 6695 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6696 SmallVector<SDValue, 16> OutLoadChains; 6697 SmallVector<SDValue, 16> OutStoreChains; 6698 SmallVector<SDValue, 32> OutChains; 6699 unsigned NumMemOps = MemOps.size(); 6700 uint64_t SrcOff = 0, DstOff = 0; 6701 for (unsigned i = 0; i != NumMemOps; ++i) { 6702 EVT VT = MemOps[i]; 6703 unsigned VTSize = VT.getSizeInBits() / 8; 6704 SDValue Value, Store; 6705 6706 if (VTSize > Size) { 6707 // Issuing an unaligned load / store pair that overlaps with the previous 6708 // pair. Adjust the offset accordingly. 6709 assert(i == NumMemOps-1 && i != 0); 6710 SrcOff -= VTSize - Size; 6711 DstOff -= VTSize - Size; 6712 } 6713 6714 if (CopyFromConstant && 6715 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6716 // It's unlikely a store of a vector immediate can be done in a single 6717 // instruction. It would require a load from a constantpool first. 6718 // We only handle zero vectors here. 6719 // FIXME: Handle other cases where store of vector immediate is done in 6720 // a single instruction. 6721 ConstantDataArraySlice SubSlice; 6722 if (SrcOff < Slice.Length) { 6723 SubSlice = Slice; 6724 SubSlice.move(SrcOff); 6725 } else { 6726 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6727 SubSlice.Array = nullptr; 6728 SubSlice.Offset = 0; 6729 SubSlice.Length = VTSize; 6730 } 6731 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6732 if (Value.getNode()) { 6733 Store = DAG.getStore( 6734 Chain, dl, Value, 6735 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6736 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6737 OutChains.push_back(Store); 6738 } 6739 } 6740 6741 if (!Store.getNode()) { 6742 // The type might not be legal for the target. This should only happen 6743 // if the type is smaller than a legal type, as on PPC, so the right 6744 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6745 // to Load/Store if NVT==VT. 6746 // FIXME does the case above also need this? 6747 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6748 assert(NVT.bitsGE(VT)); 6749 6750 bool isDereferenceable = 6751 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6752 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6753 if (isDereferenceable) 6754 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6755 6756 Value = DAG.getExtLoad( 6757 ISD::EXTLOAD, dl, NVT, Chain, 6758 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6759 SrcPtrInfo.getWithOffset(SrcOff), VT, 6760 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6761 OutLoadChains.push_back(Value.getValue(1)); 6762 6763 Store = DAG.getTruncStore( 6764 Chain, dl, Value, 6765 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6766 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6767 OutStoreChains.push_back(Store); 6768 } 6769 SrcOff += VTSize; 6770 DstOff += VTSize; 6771 Size -= VTSize; 6772 } 6773 6774 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6775 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6776 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6777 6778 if (NumLdStInMemcpy) { 6779 // It may be that memcpy might be converted to memset if it's memcpy 6780 // of constants. In such a case, we won't have loads and stores, but 6781 // just stores. In the absence of loads, there is nothing to gang up. 6782 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6783 // If target does not care, just leave as it. 6784 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6785 OutChains.push_back(OutLoadChains[i]); 6786 OutChains.push_back(OutStoreChains[i]); 6787 } 6788 } else { 6789 // Ld/St less than/equal limit set by target. 6790 if (NumLdStInMemcpy <= GluedLdStLimit) { 6791 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6792 NumLdStInMemcpy, OutLoadChains, 6793 OutStoreChains); 6794 } else { 6795 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6796 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6797 unsigned GlueIter = 0; 6798 6799 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6800 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6801 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6802 6803 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6804 OutLoadChains, OutStoreChains); 6805 GlueIter += GluedLdStLimit; 6806 } 6807 6808 // Residual ld/st. 6809 if (RemainingLdStInMemcpy) { 6810 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6811 RemainingLdStInMemcpy, OutLoadChains, 6812 OutStoreChains); 6813 } 6814 } 6815 } 6816 } 6817 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6818 } 6819 6820 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6821 SDValue Chain, SDValue Dst, SDValue Src, 6822 uint64_t Size, Align Alignment, 6823 bool isVol, bool AlwaysInline, 6824 MachinePointerInfo DstPtrInfo, 6825 MachinePointerInfo SrcPtrInfo, 6826 const AAMDNodes &AAInfo) { 6827 // Turn a memmove of undef to nop. 6828 // FIXME: We need to honor volatile even is Src is undef. 6829 if (Src.isUndef()) 6830 return Chain; 6831 6832 // Expand memmove to a series of load and store ops if the size operand falls 6833 // below a certain threshold. 6834 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6835 const DataLayout &DL = DAG.getDataLayout(); 6836 LLVMContext &C = *DAG.getContext(); 6837 std::vector<EVT> MemOps; 6838 bool DstAlignCanChange = false; 6839 MachineFunction &MF = DAG.getMachineFunction(); 6840 MachineFrameInfo &MFI = MF.getFrameInfo(); 6841 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6842 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6843 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6844 DstAlignCanChange = true; 6845 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6846 if (!SrcAlign || Alignment > *SrcAlign) 6847 SrcAlign = Alignment; 6848 assert(SrcAlign && "SrcAlign must be set"); 6849 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6850 if (!TLI.findOptimalMemOpLowering( 6851 MemOps, Limit, 6852 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6853 /*IsVolatile*/ true), 6854 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6855 MF.getFunction().getAttributes())) 6856 return SDValue(); 6857 6858 if (DstAlignCanChange) { 6859 Type *Ty = MemOps[0].getTypeForEVT(C); 6860 Align NewAlign = DL.getABITypeAlign(Ty); 6861 if (NewAlign > Alignment) { 6862 // Give the stack frame object a larger alignment if needed. 6863 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6864 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6865 Alignment = NewAlign; 6866 } 6867 } 6868 6869 // Prepare AAInfo for loads/stores after lowering this memmove. 6870 AAMDNodes NewAAInfo = AAInfo; 6871 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6872 6873 MachineMemOperand::Flags MMOFlags = 6874 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6875 uint64_t SrcOff = 0, DstOff = 0; 6876 SmallVector<SDValue, 8> LoadValues; 6877 SmallVector<SDValue, 8> LoadChains; 6878 SmallVector<SDValue, 8> OutChains; 6879 unsigned NumMemOps = MemOps.size(); 6880 for (unsigned i = 0; i < NumMemOps; i++) { 6881 EVT VT = MemOps[i]; 6882 unsigned VTSize = VT.getSizeInBits() / 8; 6883 SDValue Value; 6884 6885 bool isDereferenceable = 6886 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6887 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6888 if (isDereferenceable) 6889 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6890 6891 Value = DAG.getLoad( 6892 VT, dl, Chain, 6893 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6894 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6895 LoadValues.push_back(Value); 6896 LoadChains.push_back(Value.getValue(1)); 6897 SrcOff += VTSize; 6898 } 6899 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6900 OutChains.clear(); 6901 for (unsigned i = 0; i < NumMemOps; i++) { 6902 EVT VT = MemOps[i]; 6903 unsigned VTSize = VT.getSizeInBits() / 8; 6904 SDValue Store; 6905 6906 Store = DAG.getStore( 6907 Chain, dl, LoadValues[i], 6908 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6909 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6910 OutChains.push_back(Store); 6911 DstOff += VTSize; 6912 } 6913 6914 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6915 } 6916 6917 /// Lower the call to 'memset' intrinsic function into a series of store 6918 /// operations. 6919 /// 6920 /// \param DAG Selection DAG where lowered code is placed. 6921 /// \param dl Link to corresponding IR location. 6922 /// \param Chain Control flow dependency. 6923 /// \param Dst Pointer to destination memory location. 6924 /// \param Src Value of byte to write into the memory. 6925 /// \param Size Number of bytes to write. 6926 /// \param Alignment Alignment of the destination in bytes. 6927 /// \param isVol True if destination is volatile. 6928 /// \param DstPtrInfo IR information on the memory pointer. 6929 /// \returns New head in the control flow, if lowering was successful, empty 6930 /// SDValue otherwise. 6931 /// 6932 /// The function tries to replace 'llvm.memset' intrinsic with several store 6933 /// operations and value calculation code. This is usually profitable for small 6934 /// memory size. 6935 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6936 SDValue Chain, SDValue Dst, SDValue Src, 6937 uint64_t Size, Align Alignment, bool isVol, 6938 MachinePointerInfo DstPtrInfo, 6939 const AAMDNodes &AAInfo) { 6940 // Turn a memset of undef to nop. 6941 // FIXME: We need to honor volatile even is Src is undef. 6942 if (Src.isUndef()) 6943 return Chain; 6944 6945 // Expand memset to a series of load/store ops if the size operand 6946 // falls below a certain threshold. 6947 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6948 std::vector<EVT> MemOps; 6949 bool DstAlignCanChange = false; 6950 MachineFunction &MF = DAG.getMachineFunction(); 6951 MachineFrameInfo &MFI = MF.getFrameInfo(); 6952 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6953 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6954 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6955 DstAlignCanChange = true; 6956 bool IsZeroVal = 6957 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6958 if (!TLI.findOptimalMemOpLowering( 6959 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6960 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6961 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6962 return SDValue(); 6963 6964 if (DstAlignCanChange) { 6965 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6966 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6967 if (NewAlign > Alignment) { 6968 // Give the stack frame object a larger alignment if needed. 6969 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6970 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6971 Alignment = NewAlign; 6972 } 6973 } 6974 6975 SmallVector<SDValue, 8> OutChains; 6976 uint64_t DstOff = 0; 6977 unsigned NumMemOps = MemOps.size(); 6978 6979 // Find the largest store and generate the bit pattern for it. 6980 EVT LargestVT = MemOps[0]; 6981 for (unsigned i = 1; i < NumMemOps; i++) 6982 if (MemOps[i].bitsGT(LargestVT)) 6983 LargestVT = MemOps[i]; 6984 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6985 6986 // Prepare AAInfo for loads/stores after lowering this memset. 6987 AAMDNodes NewAAInfo = AAInfo; 6988 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6989 6990 for (unsigned i = 0; i < NumMemOps; i++) { 6991 EVT VT = MemOps[i]; 6992 unsigned VTSize = VT.getSizeInBits() / 8; 6993 if (VTSize > Size) { 6994 // Issuing an unaligned load / store pair that overlaps with the previous 6995 // pair. Adjust the offset accordingly. 6996 assert(i == NumMemOps-1 && i != 0); 6997 DstOff -= VTSize - Size; 6998 } 6999 7000 // If this store is smaller than the largest store see whether we can get 7001 // the smaller value for free with a truncate. 7002 SDValue Value = MemSetValue; 7003 if (VT.bitsLT(LargestVT)) { 7004 if (!LargestVT.isVector() && !VT.isVector() && 7005 TLI.isTruncateFree(LargestVT, VT)) 7006 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7007 else 7008 Value = getMemsetValue(Src, VT, DAG, dl); 7009 } 7010 assert(Value.getValueType() == VT && "Value with wrong type."); 7011 SDValue Store = DAG.getStore( 7012 Chain, dl, Value, 7013 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7014 DstPtrInfo.getWithOffset(DstOff), Alignment, 7015 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7016 NewAAInfo); 7017 OutChains.push_back(Store); 7018 DstOff += VT.getSizeInBits() / 8; 7019 Size -= VTSize; 7020 } 7021 7022 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7023 } 7024 7025 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7026 unsigned AS) { 7027 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7028 // pointer operands can be losslessly bitcasted to pointers of address space 0 7029 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7030 report_fatal_error("cannot lower memory intrinsic in address space " + 7031 Twine(AS)); 7032 } 7033 } 7034 7035 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7036 SDValue Src, SDValue Size, Align Alignment, 7037 bool isVol, bool AlwaysInline, bool isTailCall, 7038 MachinePointerInfo DstPtrInfo, 7039 MachinePointerInfo SrcPtrInfo, 7040 const AAMDNodes &AAInfo) { 7041 // Check to see if we should lower the memcpy to loads and stores first. 7042 // For cases within the target-specified limits, this is the best choice. 7043 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7044 if (ConstantSize) { 7045 // Memcpy with size zero? Just return the original chain. 7046 if (ConstantSize->isZero()) 7047 return Chain; 7048 7049 SDValue Result = getMemcpyLoadsAndStores( 7050 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7051 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7052 if (Result.getNode()) 7053 return Result; 7054 } 7055 7056 // Then check to see if we should lower the memcpy with target-specific 7057 // code. If the target chooses to do this, this is the next best. 7058 if (TSI) { 7059 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7060 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7061 DstPtrInfo, SrcPtrInfo); 7062 if (Result.getNode()) 7063 return Result; 7064 } 7065 7066 // If we really need inline code and the target declined to provide it, 7067 // use a (potentially long) sequence of loads and stores. 7068 if (AlwaysInline) { 7069 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7070 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 7071 ConstantSize->getZExtValue(), Alignment, 7072 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 7073 } 7074 7075 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7076 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7077 7078 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7079 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7080 // respect volatile, so they may do things like read or write memory 7081 // beyond the given memory regions. But fixing this isn't easy, and most 7082 // people don't care. 7083 7084 // Emit a library call. 7085 TargetLowering::ArgListTy Args; 7086 TargetLowering::ArgListEntry Entry; 7087 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7088 Entry.Node = Dst; Args.push_back(Entry); 7089 Entry.Node = Src; Args.push_back(Entry); 7090 7091 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7092 Entry.Node = Size; Args.push_back(Entry); 7093 // FIXME: pass in SDLoc 7094 TargetLowering::CallLoweringInfo CLI(*this); 7095 CLI.setDebugLoc(dl) 7096 .setChain(Chain) 7097 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7098 Dst.getValueType().getTypeForEVT(*getContext()), 7099 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7100 TLI->getPointerTy(getDataLayout())), 7101 std::move(Args)) 7102 .setDiscardResult() 7103 .setTailCall(isTailCall); 7104 7105 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7106 return CallResult.second; 7107 } 7108 7109 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7110 SDValue Dst, unsigned DstAlign, 7111 SDValue Src, unsigned SrcAlign, 7112 SDValue Size, Type *SizeTy, 7113 unsigned ElemSz, bool isTailCall, 7114 MachinePointerInfo DstPtrInfo, 7115 MachinePointerInfo SrcPtrInfo) { 7116 // Emit a library call. 7117 TargetLowering::ArgListTy Args; 7118 TargetLowering::ArgListEntry Entry; 7119 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7120 Entry.Node = Dst; 7121 Args.push_back(Entry); 7122 7123 Entry.Node = Src; 7124 Args.push_back(Entry); 7125 7126 Entry.Ty = SizeTy; 7127 Entry.Node = Size; 7128 Args.push_back(Entry); 7129 7130 RTLIB::Libcall LibraryCall = 7131 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7132 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7133 report_fatal_error("Unsupported element size"); 7134 7135 TargetLowering::CallLoweringInfo CLI(*this); 7136 CLI.setDebugLoc(dl) 7137 .setChain(Chain) 7138 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7139 Type::getVoidTy(*getContext()), 7140 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7141 TLI->getPointerTy(getDataLayout())), 7142 std::move(Args)) 7143 .setDiscardResult() 7144 .setTailCall(isTailCall); 7145 7146 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7147 return CallResult.second; 7148 } 7149 7150 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7151 SDValue Src, SDValue Size, Align Alignment, 7152 bool isVol, bool isTailCall, 7153 MachinePointerInfo DstPtrInfo, 7154 MachinePointerInfo SrcPtrInfo, 7155 const AAMDNodes &AAInfo) { 7156 // Check to see if we should lower the memmove to loads and stores first. 7157 // For cases within the target-specified limits, this is the best choice. 7158 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7159 if (ConstantSize) { 7160 // Memmove with size zero? Just return the original chain. 7161 if (ConstantSize->isZero()) 7162 return Chain; 7163 7164 SDValue Result = getMemmoveLoadsAndStores( 7165 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7166 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7167 if (Result.getNode()) 7168 return Result; 7169 } 7170 7171 // Then check to see if we should lower the memmove with target-specific 7172 // code. If the target chooses to do this, this is the next best. 7173 if (TSI) { 7174 SDValue Result = 7175 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7176 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7177 if (Result.getNode()) 7178 return Result; 7179 } 7180 7181 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7182 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7183 7184 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7185 // not be safe. See memcpy above for more details. 7186 7187 // Emit a library call. 7188 TargetLowering::ArgListTy Args; 7189 TargetLowering::ArgListEntry Entry; 7190 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7191 Entry.Node = Dst; Args.push_back(Entry); 7192 Entry.Node = Src; Args.push_back(Entry); 7193 7194 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7195 Entry.Node = Size; Args.push_back(Entry); 7196 // FIXME: pass in SDLoc 7197 TargetLowering::CallLoweringInfo CLI(*this); 7198 CLI.setDebugLoc(dl) 7199 .setChain(Chain) 7200 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7201 Dst.getValueType().getTypeForEVT(*getContext()), 7202 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7203 TLI->getPointerTy(getDataLayout())), 7204 std::move(Args)) 7205 .setDiscardResult() 7206 .setTailCall(isTailCall); 7207 7208 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7209 return CallResult.second; 7210 } 7211 7212 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7213 SDValue Dst, unsigned DstAlign, 7214 SDValue Src, unsigned SrcAlign, 7215 SDValue Size, Type *SizeTy, 7216 unsigned ElemSz, bool isTailCall, 7217 MachinePointerInfo DstPtrInfo, 7218 MachinePointerInfo SrcPtrInfo) { 7219 // Emit a library call. 7220 TargetLowering::ArgListTy Args; 7221 TargetLowering::ArgListEntry Entry; 7222 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7223 Entry.Node = Dst; 7224 Args.push_back(Entry); 7225 7226 Entry.Node = Src; 7227 Args.push_back(Entry); 7228 7229 Entry.Ty = SizeTy; 7230 Entry.Node = Size; 7231 Args.push_back(Entry); 7232 7233 RTLIB::Libcall LibraryCall = 7234 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7235 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7236 report_fatal_error("Unsupported element size"); 7237 7238 TargetLowering::CallLoweringInfo CLI(*this); 7239 CLI.setDebugLoc(dl) 7240 .setChain(Chain) 7241 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7242 Type::getVoidTy(*getContext()), 7243 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7244 TLI->getPointerTy(getDataLayout())), 7245 std::move(Args)) 7246 .setDiscardResult() 7247 .setTailCall(isTailCall); 7248 7249 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7250 return CallResult.second; 7251 } 7252 7253 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7254 SDValue Src, SDValue Size, Align Alignment, 7255 bool isVol, bool isTailCall, 7256 MachinePointerInfo DstPtrInfo, 7257 const AAMDNodes &AAInfo) { 7258 // Check to see if we should lower the memset to stores first. 7259 // For cases within the target-specified limits, this is the best choice. 7260 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7261 if (ConstantSize) { 7262 // Memset with size zero? Just return the original chain. 7263 if (ConstantSize->isZero()) 7264 return Chain; 7265 7266 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7267 ConstantSize->getZExtValue(), Alignment, 7268 isVol, DstPtrInfo, AAInfo); 7269 7270 if (Result.getNode()) 7271 return Result; 7272 } 7273 7274 // Then check to see if we should lower the memset with target-specific 7275 // code. If the target chooses to do this, this is the next best. 7276 if (TSI) { 7277 SDValue Result = TSI->EmitTargetCodeForMemset( 7278 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7279 if (Result.getNode()) 7280 return Result; 7281 } 7282 7283 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7284 7285 // Emit a library call. 7286 TargetLowering::ArgListTy Args; 7287 TargetLowering::ArgListEntry Entry; 7288 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7289 Args.push_back(Entry); 7290 Entry.Node = Src; 7291 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7292 Args.push_back(Entry); 7293 Entry.Node = Size; 7294 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7295 Args.push_back(Entry); 7296 7297 // FIXME: pass in SDLoc 7298 TargetLowering::CallLoweringInfo CLI(*this); 7299 CLI.setDebugLoc(dl) 7300 .setChain(Chain) 7301 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7302 Dst.getValueType().getTypeForEVT(*getContext()), 7303 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7304 TLI->getPointerTy(getDataLayout())), 7305 std::move(Args)) 7306 .setDiscardResult() 7307 .setTailCall(isTailCall); 7308 7309 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7310 return CallResult.second; 7311 } 7312 7313 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7314 SDValue Dst, unsigned DstAlign, 7315 SDValue Value, SDValue Size, Type *SizeTy, 7316 unsigned ElemSz, bool isTailCall, 7317 MachinePointerInfo DstPtrInfo) { 7318 // Emit a library call. 7319 TargetLowering::ArgListTy Args; 7320 TargetLowering::ArgListEntry Entry; 7321 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7322 Entry.Node = Dst; 7323 Args.push_back(Entry); 7324 7325 Entry.Ty = Type::getInt8Ty(*getContext()); 7326 Entry.Node = Value; 7327 Args.push_back(Entry); 7328 7329 Entry.Ty = SizeTy; 7330 Entry.Node = Size; 7331 Args.push_back(Entry); 7332 7333 RTLIB::Libcall LibraryCall = 7334 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7335 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7336 report_fatal_error("Unsupported element size"); 7337 7338 TargetLowering::CallLoweringInfo CLI(*this); 7339 CLI.setDebugLoc(dl) 7340 .setChain(Chain) 7341 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7342 Type::getVoidTy(*getContext()), 7343 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7344 TLI->getPointerTy(getDataLayout())), 7345 std::move(Args)) 7346 .setDiscardResult() 7347 .setTailCall(isTailCall); 7348 7349 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7350 return CallResult.second; 7351 } 7352 7353 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7354 SDVTList VTList, ArrayRef<SDValue> Ops, 7355 MachineMemOperand *MMO) { 7356 FoldingSetNodeID ID; 7357 ID.AddInteger(MemVT.getRawBits()); 7358 AddNodeIDNode(ID, Opcode, VTList, Ops); 7359 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7360 ID.AddInteger(MMO->getFlags()); 7361 void* IP = nullptr; 7362 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7363 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7364 return SDValue(E, 0); 7365 } 7366 7367 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7368 VTList, MemVT, MMO); 7369 createOperands(N, Ops); 7370 7371 CSEMap.InsertNode(N, IP); 7372 InsertNode(N); 7373 return SDValue(N, 0); 7374 } 7375 7376 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7377 EVT MemVT, SDVTList VTs, SDValue Chain, 7378 SDValue Ptr, SDValue Cmp, SDValue Swp, 7379 MachineMemOperand *MMO) { 7380 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7381 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7382 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7383 7384 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7385 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7386 } 7387 7388 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7389 SDValue Chain, SDValue Ptr, SDValue Val, 7390 MachineMemOperand *MMO) { 7391 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7392 Opcode == ISD::ATOMIC_LOAD_SUB || 7393 Opcode == ISD::ATOMIC_LOAD_AND || 7394 Opcode == ISD::ATOMIC_LOAD_CLR || 7395 Opcode == ISD::ATOMIC_LOAD_OR || 7396 Opcode == ISD::ATOMIC_LOAD_XOR || 7397 Opcode == ISD::ATOMIC_LOAD_NAND || 7398 Opcode == ISD::ATOMIC_LOAD_MIN || 7399 Opcode == ISD::ATOMIC_LOAD_MAX || 7400 Opcode == ISD::ATOMIC_LOAD_UMIN || 7401 Opcode == ISD::ATOMIC_LOAD_UMAX || 7402 Opcode == ISD::ATOMIC_LOAD_FADD || 7403 Opcode == ISD::ATOMIC_LOAD_FSUB || 7404 Opcode == ISD::ATOMIC_SWAP || 7405 Opcode == ISD::ATOMIC_STORE) && 7406 "Invalid Atomic Op"); 7407 7408 EVT VT = Val.getValueType(); 7409 7410 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7411 getVTList(VT, MVT::Other); 7412 SDValue Ops[] = {Chain, Ptr, Val}; 7413 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7414 } 7415 7416 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7417 EVT VT, SDValue Chain, SDValue Ptr, 7418 MachineMemOperand *MMO) { 7419 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7420 7421 SDVTList VTs = getVTList(VT, MVT::Other); 7422 SDValue Ops[] = {Chain, Ptr}; 7423 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7424 } 7425 7426 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7427 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7428 if (Ops.size() == 1) 7429 return Ops[0]; 7430 7431 SmallVector<EVT, 4> VTs; 7432 VTs.reserve(Ops.size()); 7433 for (const SDValue &Op : Ops) 7434 VTs.push_back(Op.getValueType()); 7435 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7436 } 7437 7438 SDValue SelectionDAG::getMemIntrinsicNode( 7439 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7440 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7441 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7442 if (!Size && MemVT.isScalableVector()) 7443 Size = MemoryLocation::UnknownSize; 7444 else if (!Size) 7445 Size = MemVT.getStoreSize(); 7446 7447 MachineFunction &MF = getMachineFunction(); 7448 MachineMemOperand *MMO = 7449 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7450 7451 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7452 } 7453 7454 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7455 SDVTList VTList, 7456 ArrayRef<SDValue> Ops, EVT MemVT, 7457 MachineMemOperand *MMO) { 7458 assert((Opcode == ISD::INTRINSIC_VOID || 7459 Opcode == ISD::INTRINSIC_W_CHAIN || 7460 Opcode == ISD::PREFETCH || 7461 ((int)Opcode <= std::numeric_limits<int>::max() && 7462 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7463 "Opcode is not a memory-accessing opcode!"); 7464 7465 // Memoize the node unless it returns a flag. 7466 MemIntrinsicSDNode *N; 7467 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7468 FoldingSetNodeID ID; 7469 AddNodeIDNode(ID, Opcode, VTList, Ops); 7470 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7471 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7472 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7473 ID.AddInteger(MMO->getFlags()); 7474 void *IP = nullptr; 7475 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7476 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7477 return SDValue(E, 0); 7478 } 7479 7480 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7481 VTList, MemVT, MMO); 7482 createOperands(N, Ops); 7483 7484 CSEMap.InsertNode(N, IP); 7485 } else { 7486 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7487 VTList, MemVT, MMO); 7488 createOperands(N, Ops); 7489 } 7490 InsertNode(N); 7491 SDValue V(N, 0); 7492 NewSDValueDbgMsg(V, "Creating new node: ", this); 7493 return V; 7494 } 7495 7496 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7497 SDValue Chain, int FrameIndex, 7498 int64_t Size, int64_t Offset) { 7499 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7500 const auto VTs = getVTList(MVT::Other); 7501 SDValue Ops[2] = { 7502 Chain, 7503 getFrameIndex(FrameIndex, 7504 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7505 true)}; 7506 7507 FoldingSetNodeID ID; 7508 AddNodeIDNode(ID, Opcode, VTs, Ops); 7509 ID.AddInteger(FrameIndex); 7510 ID.AddInteger(Size); 7511 ID.AddInteger(Offset); 7512 void *IP = nullptr; 7513 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7514 return SDValue(E, 0); 7515 7516 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7517 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7518 createOperands(N, Ops); 7519 CSEMap.InsertNode(N, IP); 7520 InsertNode(N); 7521 SDValue V(N, 0); 7522 NewSDValueDbgMsg(V, "Creating new node: ", this); 7523 return V; 7524 } 7525 7526 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7527 uint64_t Guid, uint64_t Index, 7528 uint32_t Attr) { 7529 const unsigned Opcode = ISD::PSEUDO_PROBE; 7530 const auto VTs = getVTList(MVT::Other); 7531 SDValue Ops[] = {Chain}; 7532 FoldingSetNodeID ID; 7533 AddNodeIDNode(ID, Opcode, VTs, Ops); 7534 ID.AddInteger(Guid); 7535 ID.AddInteger(Index); 7536 void *IP = nullptr; 7537 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7538 return SDValue(E, 0); 7539 7540 auto *N = newSDNode<PseudoProbeSDNode>( 7541 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7542 createOperands(N, Ops); 7543 CSEMap.InsertNode(N, IP); 7544 InsertNode(N); 7545 SDValue V(N, 0); 7546 NewSDValueDbgMsg(V, "Creating new node: ", this); 7547 return V; 7548 } 7549 7550 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7551 /// MachinePointerInfo record from it. This is particularly useful because the 7552 /// code generator has many cases where it doesn't bother passing in a 7553 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7554 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7555 SelectionDAG &DAG, SDValue Ptr, 7556 int64_t Offset = 0) { 7557 // If this is FI+Offset, we can model it. 7558 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7559 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7560 FI->getIndex(), Offset); 7561 7562 // If this is (FI+Offset1)+Offset2, we can model it. 7563 if (Ptr.getOpcode() != ISD::ADD || 7564 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7565 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7566 return Info; 7567 7568 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7569 return MachinePointerInfo::getFixedStack( 7570 DAG.getMachineFunction(), FI, 7571 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7572 } 7573 7574 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7575 /// MachinePointerInfo record from it. This is particularly useful because the 7576 /// code generator has many cases where it doesn't bother passing in a 7577 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7578 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7579 SelectionDAG &DAG, SDValue Ptr, 7580 SDValue OffsetOp) { 7581 // If the 'Offset' value isn't a constant, we can't handle this. 7582 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7583 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7584 if (OffsetOp.isUndef()) 7585 return InferPointerInfo(Info, DAG, Ptr); 7586 return Info; 7587 } 7588 7589 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7590 EVT VT, const SDLoc &dl, SDValue Chain, 7591 SDValue Ptr, SDValue Offset, 7592 MachinePointerInfo PtrInfo, EVT MemVT, 7593 Align Alignment, 7594 MachineMemOperand::Flags MMOFlags, 7595 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7596 assert(Chain.getValueType() == MVT::Other && 7597 "Invalid chain type"); 7598 7599 MMOFlags |= MachineMemOperand::MOLoad; 7600 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7601 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7602 // clients. 7603 if (PtrInfo.V.isNull()) 7604 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7605 7606 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7607 MachineFunction &MF = getMachineFunction(); 7608 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7609 Alignment, AAInfo, Ranges); 7610 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7611 } 7612 7613 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7614 EVT VT, const SDLoc &dl, SDValue Chain, 7615 SDValue Ptr, SDValue Offset, EVT MemVT, 7616 MachineMemOperand *MMO) { 7617 if (VT == MemVT) { 7618 ExtType = ISD::NON_EXTLOAD; 7619 } else if (ExtType == ISD::NON_EXTLOAD) { 7620 assert(VT == MemVT && "Non-extending load from different memory type!"); 7621 } else { 7622 // Extending load. 7623 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7624 "Should only be an extending load, not truncating!"); 7625 assert(VT.isInteger() == MemVT.isInteger() && 7626 "Cannot convert from FP to Int or Int -> FP!"); 7627 assert(VT.isVector() == MemVT.isVector() && 7628 "Cannot use an ext load to convert to or from a vector!"); 7629 assert((!VT.isVector() || 7630 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7631 "Cannot use an ext load to change the number of vector elements!"); 7632 } 7633 7634 bool Indexed = AM != ISD::UNINDEXED; 7635 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7636 7637 SDVTList VTs = Indexed ? 7638 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7639 SDValue Ops[] = { Chain, Ptr, Offset }; 7640 FoldingSetNodeID ID; 7641 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7642 ID.AddInteger(MemVT.getRawBits()); 7643 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7644 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7645 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7646 ID.AddInteger(MMO->getFlags()); 7647 void *IP = nullptr; 7648 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7649 cast<LoadSDNode>(E)->refineAlignment(MMO); 7650 return SDValue(E, 0); 7651 } 7652 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7653 ExtType, MemVT, MMO); 7654 createOperands(N, Ops); 7655 7656 CSEMap.InsertNode(N, IP); 7657 InsertNode(N); 7658 SDValue V(N, 0); 7659 NewSDValueDbgMsg(V, "Creating new node: ", this); 7660 return V; 7661 } 7662 7663 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7664 SDValue Ptr, MachinePointerInfo PtrInfo, 7665 MaybeAlign Alignment, 7666 MachineMemOperand::Flags MMOFlags, 7667 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7668 SDValue Undef = getUNDEF(Ptr.getValueType()); 7669 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7670 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7671 } 7672 7673 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7674 SDValue Ptr, MachineMemOperand *MMO) { 7675 SDValue Undef = getUNDEF(Ptr.getValueType()); 7676 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7677 VT, MMO); 7678 } 7679 7680 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7681 EVT VT, SDValue Chain, SDValue Ptr, 7682 MachinePointerInfo PtrInfo, EVT MemVT, 7683 MaybeAlign Alignment, 7684 MachineMemOperand::Flags MMOFlags, 7685 const AAMDNodes &AAInfo) { 7686 SDValue Undef = getUNDEF(Ptr.getValueType()); 7687 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7688 MemVT, Alignment, MMOFlags, AAInfo); 7689 } 7690 7691 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7692 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7693 MachineMemOperand *MMO) { 7694 SDValue Undef = getUNDEF(Ptr.getValueType()); 7695 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7696 MemVT, MMO); 7697 } 7698 7699 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7700 SDValue Base, SDValue Offset, 7701 ISD::MemIndexedMode AM) { 7702 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7703 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7704 // Don't propagate the invariant or dereferenceable flags. 7705 auto MMOFlags = 7706 LD->getMemOperand()->getFlags() & 7707 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7708 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7709 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7710 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7711 } 7712 7713 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7714 SDValue Ptr, MachinePointerInfo PtrInfo, 7715 Align Alignment, 7716 MachineMemOperand::Flags MMOFlags, 7717 const AAMDNodes &AAInfo) { 7718 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7719 7720 MMOFlags |= MachineMemOperand::MOStore; 7721 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7722 7723 if (PtrInfo.V.isNull()) 7724 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7725 7726 MachineFunction &MF = getMachineFunction(); 7727 uint64_t Size = 7728 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7729 MachineMemOperand *MMO = 7730 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7731 return getStore(Chain, dl, Val, Ptr, MMO); 7732 } 7733 7734 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7735 SDValue Ptr, MachineMemOperand *MMO) { 7736 assert(Chain.getValueType() == MVT::Other && 7737 "Invalid chain type"); 7738 EVT VT = Val.getValueType(); 7739 SDVTList VTs = getVTList(MVT::Other); 7740 SDValue Undef = getUNDEF(Ptr.getValueType()); 7741 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7742 FoldingSetNodeID ID; 7743 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7744 ID.AddInteger(VT.getRawBits()); 7745 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7746 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7747 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7748 ID.AddInteger(MMO->getFlags()); 7749 void *IP = nullptr; 7750 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7751 cast<StoreSDNode>(E)->refineAlignment(MMO); 7752 return SDValue(E, 0); 7753 } 7754 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7755 ISD::UNINDEXED, false, VT, MMO); 7756 createOperands(N, Ops); 7757 7758 CSEMap.InsertNode(N, IP); 7759 InsertNode(N); 7760 SDValue V(N, 0); 7761 NewSDValueDbgMsg(V, "Creating new node: ", this); 7762 return V; 7763 } 7764 7765 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7766 SDValue Ptr, MachinePointerInfo PtrInfo, 7767 EVT SVT, Align Alignment, 7768 MachineMemOperand::Flags MMOFlags, 7769 const AAMDNodes &AAInfo) { 7770 assert(Chain.getValueType() == MVT::Other && 7771 "Invalid chain type"); 7772 7773 MMOFlags |= MachineMemOperand::MOStore; 7774 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7775 7776 if (PtrInfo.V.isNull()) 7777 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7778 7779 MachineFunction &MF = getMachineFunction(); 7780 MachineMemOperand *MMO = MF.getMachineMemOperand( 7781 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7782 Alignment, AAInfo); 7783 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7784 } 7785 7786 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7787 SDValue Ptr, EVT SVT, 7788 MachineMemOperand *MMO) { 7789 EVT VT = Val.getValueType(); 7790 7791 assert(Chain.getValueType() == MVT::Other && 7792 "Invalid chain type"); 7793 if (VT == SVT) 7794 return getStore(Chain, dl, Val, Ptr, MMO); 7795 7796 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7797 "Should only be a truncating store, not extending!"); 7798 assert(VT.isInteger() == SVT.isInteger() && 7799 "Can't do FP-INT conversion!"); 7800 assert(VT.isVector() == SVT.isVector() && 7801 "Cannot use trunc store to convert to or from a vector!"); 7802 assert((!VT.isVector() || 7803 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7804 "Cannot use trunc store to change the number of vector elements!"); 7805 7806 SDVTList VTs = getVTList(MVT::Other); 7807 SDValue Undef = getUNDEF(Ptr.getValueType()); 7808 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7809 FoldingSetNodeID ID; 7810 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7811 ID.AddInteger(SVT.getRawBits()); 7812 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7813 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7814 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7815 ID.AddInteger(MMO->getFlags()); 7816 void *IP = nullptr; 7817 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7818 cast<StoreSDNode>(E)->refineAlignment(MMO); 7819 return SDValue(E, 0); 7820 } 7821 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7822 ISD::UNINDEXED, true, SVT, MMO); 7823 createOperands(N, Ops); 7824 7825 CSEMap.InsertNode(N, IP); 7826 InsertNode(N); 7827 SDValue V(N, 0); 7828 NewSDValueDbgMsg(V, "Creating new node: ", this); 7829 return V; 7830 } 7831 7832 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7833 SDValue Base, SDValue Offset, 7834 ISD::MemIndexedMode AM) { 7835 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7836 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7837 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7838 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7839 FoldingSetNodeID ID; 7840 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7841 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7842 ID.AddInteger(ST->getRawSubclassData()); 7843 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7844 ID.AddInteger(ST->getMemOperand()->getFlags()); 7845 void *IP = nullptr; 7846 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7847 return SDValue(E, 0); 7848 7849 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7850 ST->isTruncatingStore(), ST->getMemoryVT(), 7851 ST->getMemOperand()); 7852 createOperands(N, Ops); 7853 7854 CSEMap.InsertNode(N, IP); 7855 InsertNode(N); 7856 SDValue V(N, 0); 7857 NewSDValueDbgMsg(V, "Creating new node: ", this); 7858 return V; 7859 } 7860 7861 SDValue SelectionDAG::getLoadVP( 7862 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7863 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7864 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7865 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7866 const MDNode *Ranges, bool IsExpanding) { 7867 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7868 7869 MMOFlags |= MachineMemOperand::MOLoad; 7870 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7871 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7872 // clients. 7873 if (PtrInfo.V.isNull()) 7874 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7875 7876 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7877 MachineFunction &MF = getMachineFunction(); 7878 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7879 Alignment, AAInfo, Ranges); 7880 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7881 MMO, IsExpanding); 7882 } 7883 7884 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7885 ISD::LoadExtType ExtType, EVT VT, 7886 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7887 SDValue Offset, SDValue Mask, SDValue EVL, 7888 EVT MemVT, MachineMemOperand *MMO, 7889 bool IsExpanding) { 7890 bool Indexed = AM != ISD::UNINDEXED; 7891 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7892 7893 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7894 : getVTList(VT, MVT::Other); 7895 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7896 FoldingSetNodeID ID; 7897 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7898 ID.AddInteger(VT.getRawBits()); 7899 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7900 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7901 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7902 ID.AddInteger(MMO->getFlags()); 7903 void *IP = nullptr; 7904 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7905 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7906 return SDValue(E, 0); 7907 } 7908 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7909 ExtType, IsExpanding, MemVT, MMO); 7910 createOperands(N, Ops); 7911 7912 CSEMap.InsertNode(N, IP); 7913 InsertNode(N); 7914 SDValue V(N, 0); 7915 NewSDValueDbgMsg(V, "Creating new node: ", this); 7916 return V; 7917 } 7918 7919 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7920 SDValue Ptr, SDValue Mask, SDValue EVL, 7921 MachinePointerInfo PtrInfo, 7922 MaybeAlign Alignment, 7923 MachineMemOperand::Flags MMOFlags, 7924 const AAMDNodes &AAInfo, const MDNode *Ranges, 7925 bool IsExpanding) { 7926 SDValue Undef = getUNDEF(Ptr.getValueType()); 7927 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7928 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7929 IsExpanding); 7930 } 7931 7932 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7933 SDValue Ptr, SDValue Mask, SDValue EVL, 7934 MachineMemOperand *MMO, bool IsExpanding) { 7935 SDValue Undef = getUNDEF(Ptr.getValueType()); 7936 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7937 Mask, EVL, VT, MMO, IsExpanding); 7938 } 7939 7940 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7941 EVT VT, SDValue Chain, SDValue Ptr, 7942 SDValue Mask, SDValue EVL, 7943 MachinePointerInfo PtrInfo, EVT MemVT, 7944 MaybeAlign Alignment, 7945 MachineMemOperand::Flags MMOFlags, 7946 const AAMDNodes &AAInfo, bool IsExpanding) { 7947 SDValue Undef = getUNDEF(Ptr.getValueType()); 7948 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7949 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7950 IsExpanding); 7951 } 7952 7953 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7954 EVT VT, SDValue Chain, SDValue Ptr, 7955 SDValue Mask, SDValue EVL, EVT MemVT, 7956 MachineMemOperand *MMO, bool IsExpanding) { 7957 SDValue Undef = getUNDEF(Ptr.getValueType()); 7958 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7959 EVL, MemVT, MMO, IsExpanding); 7960 } 7961 7962 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7963 SDValue Base, SDValue Offset, 7964 ISD::MemIndexedMode AM) { 7965 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7966 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7967 // Don't propagate the invariant or dereferenceable flags. 7968 auto MMOFlags = 7969 LD->getMemOperand()->getFlags() & 7970 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7971 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7972 LD->getChain(), Base, Offset, LD->getMask(), 7973 LD->getVectorLength(), LD->getPointerInfo(), 7974 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7975 nullptr, LD->isExpandingLoad()); 7976 } 7977 7978 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7979 SDValue Ptr, SDValue Offset, SDValue Mask, 7980 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 7981 ISD::MemIndexedMode AM, bool IsTruncating, 7982 bool IsCompressing) { 7983 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7984 bool Indexed = AM != ISD::UNINDEXED; 7985 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 7986 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 7987 : getVTList(MVT::Other); 7988 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 7989 FoldingSetNodeID ID; 7990 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7991 ID.AddInteger(MemVT.getRawBits()); 7992 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7993 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7994 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7995 ID.AddInteger(MMO->getFlags()); 7996 void *IP = nullptr; 7997 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7998 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7999 return SDValue(E, 0); 8000 } 8001 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8002 IsTruncating, IsCompressing, MemVT, MMO); 8003 createOperands(N, Ops); 8004 8005 CSEMap.InsertNode(N, IP); 8006 InsertNode(N); 8007 SDValue V(N, 0); 8008 NewSDValueDbgMsg(V, "Creating new node: ", this); 8009 return V; 8010 } 8011 8012 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8013 SDValue Val, SDValue Ptr, SDValue Mask, 8014 SDValue EVL, MachinePointerInfo PtrInfo, 8015 EVT SVT, Align Alignment, 8016 MachineMemOperand::Flags MMOFlags, 8017 const AAMDNodes &AAInfo, 8018 bool IsCompressing) { 8019 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8020 8021 MMOFlags |= MachineMemOperand::MOStore; 8022 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8023 8024 if (PtrInfo.V.isNull()) 8025 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8026 8027 MachineFunction &MF = getMachineFunction(); 8028 MachineMemOperand *MMO = MF.getMachineMemOperand( 8029 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8030 Alignment, AAInfo); 8031 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8032 IsCompressing); 8033 } 8034 8035 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8036 SDValue Val, SDValue Ptr, SDValue Mask, 8037 SDValue EVL, EVT SVT, 8038 MachineMemOperand *MMO, 8039 bool IsCompressing) { 8040 EVT VT = Val.getValueType(); 8041 8042 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8043 if (VT == SVT) 8044 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8045 EVL, VT, MMO, ISD::UNINDEXED, 8046 /*IsTruncating*/ false, IsCompressing); 8047 8048 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8049 "Should only be a truncating store, not extending!"); 8050 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8051 assert(VT.isVector() == SVT.isVector() && 8052 "Cannot use trunc store to convert to or from a vector!"); 8053 assert((!VT.isVector() || 8054 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8055 "Cannot use trunc store to change the number of vector elements!"); 8056 8057 SDVTList VTs = getVTList(MVT::Other); 8058 SDValue Undef = getUNDEF(Ptr.getValueType()); 8059 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8060 FoldingSetNodeID ID; 8061 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8062 ID.AddInteger(SVT.getRawBits()); 8063 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8064 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8065 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8066 ID.AddInteger(MMO->getFlags()); 8067 void *IP = nullptr; 8068 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8069 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8070 return SDValue(E, 0); 8071 } 8072 auto *N = 8073 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8074 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8075 createOperands(N, Ops); 8076 8077 CSEMap.InsertNode(N, IP); 8078 InsertNode(N); 8079 SDValue V(N, 0); 8080 NewSDValueDbgMsg(V, "Creating new node: ", this); 8081 return V; 8082 } 8083 8084 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8085 SDValue Base, SDValue Offset, 8086 ISD::MemIndexedMode AM) { 8087 auto *ST = cast<VPStoreSDNode>(OrigStore); 8088 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8089 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8090 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8091 Offset, ST->getMask(), ST->getVectorLength()}; 8092 FoldingSetNodeID ID; 8093 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8094 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8095 ID.AddInteger(ST->getRawSubclassData()); 8096 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8097 ID.AddInteger(ST->getMemOperand()->getFlags()); 8098 void *IP = nullptr; 8099 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8100 return SDValue(E, 0); 8101 8102 auto *N = newSDNode<VPStoreSDNode>( 8103 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8104 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8105 createOperands(N, Ops); 8106 8107 CSEMap.InsertNode(N, IP); 8108 InsertNode(N); 8109 SDValue V(N, 0); 8110 NewSDValueDbgMsg(V, "Creating new node: ", this); 8111 return V; 8112 } 8113 8114 SDValue SelectionDAG::getStridedLoadVP( 8115 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8116 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8117 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8118 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8119 const MDNode *Ranges, bool IsExpanding) { 8120 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8121 8122 MMOFlags |= MachineMemOperand::MOLoad; 8123 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8124 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8125 // clients. 8126 if (PtrInfo.V.isNull()) 8127 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8128 8129 uint64_t Size = MemoryLocation::UnknownSize; 8130 MachineFunction &MF = getMachineFunction(); 8131 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8132 Alignment, AAInfo, Ranges); 8133 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8134 EVL, MemVT, MMO, IsExpanding); 8135 } 8136 8137 SDValue SelectionDAG::getStridedLoadVP( 8138 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8139 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8140 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8141 bool Indexed = AM != ISD::UNINDEXED; 8142 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8143 8144 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8145 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8146 : getVTList(VT, MVT::Other); 8147 FoldingSetNodeID ID; 8148 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8149 ID.AddInteger(VT.getRawBits()); 8150 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8151 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8152 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8153 8154 void *IP = nullptr; 8155 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8156 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8157 return SDValue(E, 0); 8158 } 8159 8160 auto *N = 8161 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8162 ExtType, IsExpanding, MemVT, MMO); 8163 createOperands(N, Ops); 8164 CSEMap.InsertNode(N, IP); 8165 InsertNode(N); 8166 SDValue V(N, 0); 8167 NewSDValueDbgMsg(V, "Creating new node: ", this); 8168 return V; 8169 } 8170 8171 SDValue SelectionDAG::getStridedLoadVP( 8172 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8173 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8174 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8175 const MDNode *Ranges, bool IsExpanding) { 8176 SDValue Undef = getUNDEF(Ptr.getValueType()); 8177 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8178 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8179 MMOFlags, AAInfo, Ranges, IsExpanding); 8180 } 8181 8182 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8183 SDValue Ptr, SDValue Stride, 8184 SDValue Mask, SDValue EVL, 8185 MachineMemOperand *MMO, 8186 bool IsExpanding) { 8187 SDValue Undef = getUNDEF(Ptr.getValueType()); 8188 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8189 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8190 } 8191 8192 SDValue SelectionDAG::getExtStridedLoadVP( 8193 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8194 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8195 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8196 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8197 bool IsExpanding) { 8198 SDValue Undef = getUNDEF(Ptr.getValueType()); 8199 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8200 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8201 MMOFlags, AAInfo, nullptr, IsExpanding); 8202 } 8203 8204 SDValue SelectionDAG::getExtStridedLoadVP( 8205 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8206 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8207 MachineMemOperand *MMO, bool IsExpanding) { 8208 SDValue Undef = getUNDEF(Ptr.getValueType()); 8209 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8210 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8211 } 8212 8213 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8214 SDValue Base, SDValue Offset, 8215 ISD::MemIndexedMode AM) { 8216 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8217 assert(SLD->getOffset().isUndef() && 8218 "Strided load is already a indexed load!"); 8219 // Don't propagate the invariant or dereferenceable flags. 8220 auto MMOFlags = 8221 SLD->getMemOperand()->getFlags() & 8222 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8223 return getStridedLoadVP( 8224 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8225 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8226 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8227 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8228 } 8229 8230 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8231 SDValue Val, SDValue Ptr, 8232 SDValue Offset, SDValue Stride, 8233 SDValue Mask, SDValue EVL, EVT MemVT, 8234 MachineMemOperand *MMO, 8235 ISD::MemIndexedMode AM, 8236 bool IsTruncating, bool IsCompressing) { 8237 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8238 bool Indexed = AM != ISD::UNINDEXED; 8239 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8240 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8241 : getVTList(MVT::Other); 8242 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8243 FoldingSetNodeID ID; 8244 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8245 ID.AddInteger(MemVT.getRawBits()); 8246 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8247 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8248 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8249 void *IP = nullptr; 8250 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8251 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8252 return SDValue(E, 0); 8253 } 8254 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8255 VTs, AM, IsTruncating, 8256 IsCompressing, MemVT, MMO); 8257 createOperands(N, Ops); 8258 8259 CSEMap.InsertNode(N, IP); 8260 InsertNode(N); 8261 SDValue V(N, 0); 8262 NewSDValueDbgMsg(V, "Creating new node: ", this); 8263 return V; 8264 } 8265 8266 SDValue SelectionDAG::getTruncStridedStoreVP( 8267 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8268 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8269 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8270 bool IsCompressing) { 8271 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8272 8273 MMOFlags |= MachineMemOperand::MOStore; 8274 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8275 8276 if (PtrInfo.V.isNull()) 8277 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8278 8279 MachineFunction &MF = getMachineFunction(); 8280 MachineMemOperand *MMO = MF.getMachineMemOperand( 8281 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8282 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8283 MMO, IsCompressing); 8284 } 8285 8286 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8287 SDValue Val, SDValue Ptr, 8288 SDValue Stride, SDValue Mask, 8289 SDValue EVL, EVT SVT, 8290 MachineMemOperand *MMO, 8291 bool IsCompressing) { 8292 EVT VT = Val.getValueType(); 8293 8294 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8295 if (VT == SVT) 8296 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8297 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8298 /*IsTruncating*/ false, IsCompressing); 8299 8300 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8301 "Should only be a truncating store, not extending!"); 8302 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8303 assert(VT.isVector() == SVT.isVector() && 8304 "Cannot use trunc store to convert to or from a vector!"); 8305 assert((!VT.isVector() || 8306 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8307 "Cannot use trunc store to change the number of vector elements!"); 8308 8309 SDVTList VTs = getVTList(MVT::Other); 8310 SDValue Undef = getUNDEF(Ptr.getValueType()); 8311 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8312 FoldingSetNodeID ID; 8313 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8314 ID.AddInteger(SVT.getRawBits()); 8315 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8316 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8317 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8318 void *IP = nullptr; 8319 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8320 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8321 return SDValue(E, 0); 8322 } 8323 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8324 VTs, ISD::UNINDEXED, true, 8325 IsCompressing, SVT, MMO); 8326 createOperands(N, Ops); 8327 8328 CSEMap.InsertNode(N, IP); 8329 InsertNode(N); 8330 SDValue V(N, 0); 8331 NewSDValueDbgMsg(V, "Creating new node: ", this); 8332 return V; 8333 } 8334 8335 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 8336 const SDLoc &DL, SDValue Base, 8337 SDValue Offset, 8338 ISD::MemIndexedMode AM) { 8339 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 8340 assert(SST->getOffset().isUndef() && 8341 "Strided store is already an indexed store!"); 8342 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8343 SDValue Ops[] = { 8344 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 8345 SST->getMask(), SST->getVectorLength()}; 8346 FoldingSetNodeID ID; 8347 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8348 ID.AddInteger(SST->getMemoryVT().getRawBits()); 8349 ID.AddInteger(SST->getRawSubclassData()); 8350 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 8351 void *IP = nullptr; 8352 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8353 return SDValue(E, 0); 8354 8355 auto *N = newSDNode<VPStridedStoreSDNode>( 8356 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 8357 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 8358 createOperands(N, Ops); 8359 8360 CSEMap.InsertNode(N, IP); 8361 InsertNode(N); 8362 SDValue V(N, 0); 8363 NewSDValueDbgMsg(V, "Creating new node: ", this); 8364 return V; 8365 } 8366 8367 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8368 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8369 ISD::MemIndexType IndexType) { 8370 assert(Ops.size() == 6 && "Incompatible number of operands"); 8371 8372 FoldingSetNodeID ID; 8373 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8374 ID.AddInteger(VT.getRawBits()); 8375 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8376 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8377 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8378 ID.AddInteger(MMO->getFlags()); 8379 void *IP = nullptr; 8380 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8381 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8382 return SDValue(E, 0); 8383 } 8384 8385 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8386 VT, MMO, IndexType); 8387 createOperands(N, Ops); 8388 8389 assert(N->getMask().getValueType().getVectorElementCount() == 8390 N->getValueType(0).getVectorElementCount() && 8391 "Vector width mismatch between mask and data"); 8392 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8393 N->getValueType(0).getVectorElementCount().isScalable() && 8394 "Scalable flags of index and data do not match"); 8395 assert(ElementCount::isKnownGE( 8396 N->getIndex().getValueType().getVectorElementCount(), 8397 N->getValueType(0).getVectorElementCount()) && 8398 "Vector width mismatch between index and data"); 8399 assert(isa<ConstantSDNode>(N->getScale()) && 8400 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8401 "Scale should be a constant power of 2"); 8402 8403 CSEMap.InsertNode(N, IP); 8404 InsertNode(N); 8405 SDValue V(N, 0); 8406 NewSDValueDbgMsg(V, "Creating new node: ", this); 8407 return V; 8408 } 8409 8410 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8411 ArrayRef<SDValue> Ops, 8412 MachineMemOperand *MMO, 8413 ISD::MemIndexType IndexType) { 8414 assert(Ops.size() == 7 && "Incompatible number of operands"); 8415 8416 FoldingSetNodeID ID; 8417 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8418 ID.AddInteger(VT.getRawBits()); 8419 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8420 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8421 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8422 ID.AddInteger(MMO->getFlags()); 8423 void *IP = nullptr; 8424 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8425 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8426 return SDValue(E, 0); 8427 } 8428 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8429 VT, MMO, IndexType); 8430 createOperands(N, Ops); 8431 8432 assert(N->getMask().getValueType().getVectorElementCount() == 8433 N->getValue().getValueType().getVectorElementCount() && 8434 "Vector width mismatch between mask and data"); 8435 assert( 8436 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8437 N->getValue().getValueType().getVectorElementCount().isScalable() && 8438 "Scalable flags of index and data do not match"); 8439 assert(ElementCount::isKnownGE( 8440 N->getIndex().getValueType().getVectorElementCount(), 8441 N->getValue().getValueType().getVectorElementCount()) && 8442 "Vector width mismatch between index and data"); 8443 assert(isa<ConstantSDNode>(N->getScale()) && 8444 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8445 "Scale should be a constant power of 2"); 8446 8447 CSEMap.InsertNode(N, IP); 8448 InsertNode(N); 8449 SDValue V(N, 0); 8450 NewSDValueDbgMsg(V, "Creating new node: ", this); 8451 return V; 8452 } 8453 8454 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8455 SDValue Base, SDValue Offset, SDValue Mask, 8456 SDValue PassThru, EVT MemVT, 8457 MachineMemOperand *MMO, 8458 ISD::MemIndexedMode AM, 8459 ISD::LoadExtType ExtTy, bool isExpanding) { 8460 bool Indexed = AM != ISD::UNINDEXED; 8461 assert((Indexed || Offset.isUndef()) && 8462 "Unindexed masked load with an offset!"); 8463 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8464 : getVTList(VT, MVT::Other); 8465 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8466 FoldingSetNodeID ID; 8467 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8468 ID.AddInteger(MemVT.getRawBits()); 8469 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8470 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8471 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8472 ID.AddInteger(MMO->getFlags()); 8473 void *IP = nullptr; 8474 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8475 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8476 return SDValue(E, 0); 8477 } 8478 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8479 AM, ExtTy, isExpanding, MemVT, MMO); 8480 createOperands(N, Ops); 8481 8482 CSEMap.InsertNode(N, IP); 8483 InsertNode(N); 8484 SDValue V(N, 0); 8485 NewSDValueDbgMsg(V, "Creating new node: ", this); 8486 return V; 8487 } 8488 8489 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8490 SDValue Base, SDValue Offset, 8491 ISD::MemIndexedMode AM) { 8492 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8493 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8494 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8495 Offset, LD->getMask(), LD->getPassThru(), 8496 LD->getMemoryVT(), LD->getMemOperand(), AM, 8497 LD->getExtensionType(), LD->isExpandingLoad()); 8498 } 8499 8500 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8501 SDValue Val, SDValue Base, SDValue Offset, 8502 SDValue Mask, EVT MemVT, 8503 MachineMemOperand *MMO, 8504 ISD::MemIndexedMode AM, bool IsTruncating, 8505 bool IsCompressing) { 8506 assert(Chain.getValueType() == MVT::Other && 8507 "Invalid chain type"); 8508 bool Indexed = AM != ISD::UNINDEXED; 8509 assert((Indexed || Offset.isUndef()) && 8510 "Unindexed masked store with an offset!"); 8511 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8512 : getVTList(MVT::Other); 8513 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8514 FoldingSetNodeID ID; 8515 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8516 ID.AddInteger(MemVT.getRawBits()); 8517 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8518 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8519 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8520 ID.AddInteger(MMO->getFlags()); 8521 void *IP = nullptr; 8522 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8523 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8524 return SDValue(E, 0); 8525 } 8526 auto *N = 8527 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8528 IsTruncating, IsCompressing, MemVT, MMO); 8529 createOperands(N, Ops); 8530 8531 CSEMap.InsertNode(N, IP); 8532 InsertNode(N); 8533 SDValue V(N, 0); 8534 NewSDValueDbgMsg(V, "Creating new node: ", this); 8535 return V; 8536 } 8537 8538 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8539 SDValue Base, SDValue Offset, 8540 ISD::MemIndexedMode AM) { 8541 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8542 assert(ST->getOffset().isUndef() && 8543 "Masked store is already a indexed store!"); 8544 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8545 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8546 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8547 } 8548 8549 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8550 ArrayRef<SDValue> Ops, 8551 MachineMemOperand *MMO, 8552 ISD::MemIndexType IndexType, 8553 ISD::LoadExtType ExtTy) { 8554 assert(Ops.size() == 6 && "Incompatible number of operands"); 8555 8556 FoldingSetNodeID ID; 8557 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8558 ID.AddInteger(MemVT.getRawBits()); 8559 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8560 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8561 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8562 ID.AddInteger(MMO->getFlags()); 8563 void *IP = nullptr; 8564 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8565 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8566 return SDValue(E, 0); 8567 } 8568 8569 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8570 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8571 VTs, MemVT, MMO, IndexType, ExtTy); 8572 createOperands(N, Ops); 8573 8574 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8575 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8576 assert(N->getMask().getValueType().getVectorElementCount() == 8577 N->getValueType(0).getVectorElementCount() && 8578 "Vector width mismatch between mask and data"); 8579 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8580 N->getValueType(0).getVectorElementCount().isScalable() && 8581 "Scalable flags of index and data do not match"); 8582 assert(ElementCount::isKnownGE( 8583 N->getIndex().getValueType().getVectorElementCount(), 8584 N->getValueType(0).getVectorElementCount()) && 8585 "Vector width mismatch between index and data"); 8586 assert(isa<ConstantSDNode>(N->getScale()) && 8587 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8588 "Scale should be a constant power of 2"); 8589 8590 CSEMap.InsertNode(N, IP); 8591 InsertNode(N); 8592 SDValue V(N, 0); 8593 NewSDValueDbgMsg(V, "Creating new node: ", this); 8594 return V; 8595 } 8596 8597 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8598 ArrayRef<SDValue> Ops, 8599 MachineMemOperand *MMO, 8600 ISD::MemIndexType IndexType, 8601 bool IsTrunc) { 8602 assert(Ops.size() == 6 && "Incompatible number of operands"); 8603 8604 FoldingSetNodeID ID; 8605 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8606 ID.AddInteger(MemVT.getRawBits()); 8607 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8608 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8609 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8610 ID.AddInteger(MMO->getFlags()); 8611 void *IP = nullptr; 8612 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8613 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8614 return SDValue(E, 0); 8615 } 8616 8617 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8618 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8619 VTs, MemVT, MMO, IndexType, IsTrunc); 8620 createOperands(N, Ops); 8621 8622 assert(N->getMask().getValueType().getVectorElementCount() == 8623 N->getValue().getValueType().getVectorElementCount() && 8624 "Vector width mismatch between mask and data"); 8625 assert( 8626 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8627 N->getValue().getValueType().getVectorElementCount().isScalable() && 8628 "Scalable flags of index and data do not match"); 8629 assert(ElementCount::isKnownGE( 8630 N->getIndex().getValueType().getVectorElementCount(), 8631 N->getValue().getValueType().getVectorElementCount()) && 8632 "Vector width mismatch between index and data"); 8633 assert(isa<ConstantSDNode>(N->getScale()) && 8634 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8635 "Scale should be a constant power of 2"); 8636 8637 CSEMap.InsertNode(N, IP); 8638 InsertNode(N); 8639 SDValue V(N, 0); 8640 NewSDValueDbgMsg(V, "Creating new node: ", this); 8641 return V; 8642 } 8643 8644 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8645 // select undef, T, F --> T (if T is a constant), otherwise F 8646 // select, ?, undef, F --> F 8647 // select, ?, T, undef --> T 8648 if (Cond.isUndef()) 8649 return isConstantValueOfAnyType(T) ? T : F; 8650 if (T.isUndef()) 8651 return F; 8652 if (F.isUndef()) 8653 return T; 8654 8655 // select true, T, F --> T 8656 // select false, T, F --> F 8657 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8658 return CondC->isZero() ? F : T; 8659 8660 // TODO: This should simplify VSELECT with constant condition using something 8661 // like this (but check boolean contents to be complete?): 8662 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8663 // return T; 8664 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8665 // return F; 8666 8667 // select ?, T, T --> T 8668 if (T == F) 8669 return T; 8670 8671 return SDValue(); 8672 } 8673 8674 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8675 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8676 if (X.isUndef()) 8677 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8678 // shift X, undef --> undef (because it may shift by the bitwidth) 8679 if (Y.isUndef()) 8680 return getUNDEF(X.getValueType()); 8681 8682 // shift 0, Y --> 0 8683 // shift X, 0 --> X 8684 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8685 return X; 8686 8687 // shift X, C >= bitwidth(X) --> undef 8688 // All vector elements must be too big (or undef) to avoid partial undefs. 8689 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8690 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8691 }; 8692 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8693 return getUNDEF(X.getValueType()); 8694 8695 return SDValue(); 8696 } 8697 8698 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8699 SDNodeFlags Flags) { 8700 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8701 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8702 // operation is poison. That result can be relaxed to undef. 8703 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8704 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8705 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8706 (YC && YC->getValueAPF().isNaN()); 8707 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8708 (YC && YC->getValueAPF().isInfinity()); 8709 8710 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8711 return getUNDEF(X.getValueType()); 8712 8713 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8714 return getUNDEF(X.getValueType()); 8715 8716 if (!YC) 8717 return SDValue(); 8718 8719 // X + -0.0 --> X 8720 if (Opcode == ISD::FADD) 8721 if (YC->getValueAPF().isNegZero()) 8722 return X; 8723 8724 // X - +0.0 --> X 8725 if (Opcode == ISD::FSUB) 8726 if (YC->getValueAPF().isPosZero()) 8727 return X; 8728 8729 // X * 1.0 --> X 8730 // X / 1.0 --> X 8731 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8732 if (YC->getValueAPF().isExactlyValue(1.0)) 8733 return X; 8734 8735 // X * 0.0 --> 0.0 8736 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8737 if (YC->getValueAPF().isZero()) 8738 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8739 8740 return SDValue(); 8741 } 8742 8743 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8744 SDValue Ptr, SDValue SV, unsigned Align) { 8745 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8746 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8747 } 8748 8749 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8750 ArrayRef<SDUse> Ops) { 8751 switch (Ops.size()) { 8752 case 0: return getNode(Opcode, DL, VT); 8753 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8754 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8755 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8756 default: break; 8757 } 8758 8759 // Copy from an SDUse array into an SDValue array for use with 8760 // the regular getNode logic. 8761 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8762 return getNode(Opcode, DL, VT, NewOps); 8763 } 8764 8765 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8766 ArrayRef<SDValue> Ops) { 8767 SDNodeFlags Flags; 8768 if (Inserter) 8769 Flags = Inserter->getFlags(); 8770 return getNode(Opcode, DL, VT, Ops, Flags); 8771 } 8772 8773 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8774 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8775 unsigned NumOps = Ops.size(); 8776 switch (NumOps) { 8777 case 0: return getNode(Opcode, DL, VT); 8778 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8779 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8780 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8781 default: break; 8782 } 8783 8784 #ifndef NDEBUG 8785 for (auto &Op : Ops) 8786 assert(Op.getOpcode() != ISD::DELETED_NODE && 8787 "Operand is DELETED_NODE!"); 8788 #endif 8789 8790 switch (Opcode) { 8791 default: break; 8792 case ISD::BUILD_VECTOR: 8793 // Attempt to simplify BUILD_VECTOR. 8794 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8795 return V; 8796 break; 8797 case ISD::CONCAT_VECTORS: 8798 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8799 return V; 8800 break; 8801 case ISD::SELECT_CC: 8802 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8803 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8804 "LHS and RHS of condition must have same type!"); 8805 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8806 "True and False arms of SelectCC must have same type!"); 8807 assert(Ops[2].getValueType() == VT && 8808 "select_cc node must be of same type as true and false value!"); 8809 break; 8810 case ISD::BR_CC: 8811 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8812 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8813 "LHS/RHS of comparison should match types!"); 8814 break; 8815 } 8816 8817 // Memoize nodes. 8818 SDNode *N; 8819 SDVTList VTs = getVTList(VT); 8820 8821 if (VT != MVT::Glue) { 8822 FoldingSetNodeID ID; 8823 AddNodeIDNode(ID, Opcode, VTs, Ops); 8824 void *IP = nullptr; 8825 8826 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8827 return SDValue(E, 0); 8828 8829 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8830 createOperands(N, Ops); 8831 8832 CSEMap.InsertNode(N, IP); 8833 } else { 8834 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8835 createOperands(N, Ops); 8836 } 8837 8838 N->setFlags(Flags); 8839 InsertNode(N); 8840 SDValue V(N, 0); 8841 NewSDValueDbgMsg(V, "Creating new node: ", this); 8842 return V; 8843 } 8844 8845 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8846 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8847 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8848 } 8849 8850 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8851 ArrayRef<SDValue> Ops) { 8852 SDNodeFlags Flags; 8853 if (Inserter) 8854 Flags = Inserter->getFlags(); 8855 return getNode(Opcode, DL, VTList, Ops, Flags); 8856 } 8857 8858 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8859 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8860 if (VTList.NumVTs == 1) 8861 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8862 8863 #ifndef NDEBUG 8864 for (auto &Op : Ops) 8865 assert(Op.getOpcode() != ISD::DELETED_NODE && 8866 "Operand is DELETED_NODE!"); 8867 #endif 8868 8869 switch (Opcode) { 8870 case ISD::STRICT_FP_EXTEND: 8871 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8872 "Invalid STRICT_FP_EXTEND!"); 8873 assert(VTList.VTs[0].isFloatingPoint() && 8874 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8875 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8876 "STRICT_FP_EXTEND result type should be vector iff the operand " 8877 "type is vector!"); 8878 assert((!VTList.VTs[0].isVector() || 8879 VTList.VTs[0].getVectorNumElements() == 8880 Ops[1].getValueType().getVectorNumElements()) && 8881 "Vector element count mismatch!"); 8882 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8883 "Invalid fpext node, dst <= src!"); 8884 break; 8885 case ISD::STRICT_FP_ROUND: 8886 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8887 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8888 "STRICT_FP_ROUND result type should be vector iff the operand " 8889 "type is vector!"); 8890 assert((!VTList.VTs[0].isVector() || 8891 VTList.VTs[0].getVectorNumElements() == 8892 Ops[1].getValueType().getVectorNumElements()) && 8893 "Vector element count mismatch!"); 8894 assert(VTList.VTs[0].isFloatingPoint() && 8895 Ops[1].getValueType().isFloatingPoint() && 8896 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8897 isa<ConstantSDNode>(Ops[2]) && 8898 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8899 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8900 "Invalid STRICT_FP_ROUND!"); 8901 break; 8902 #if 0 8903 // FIXME: figure out how to safely handle things like 8904 // int foo(int x) { return 1 << (x & 255); } 8905 // int bar() { return foo(256); } 8906 case ISD::SRA_PARTS: 8907 case ISD::SRL_PARTS: 8908 case ISD::SHL_PARTS: 8909 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8910 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8911 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8912 else if (N3.getOpcode() == ISD::AND) 8913 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8914 // If the and is only masking out bits that cannot effect the shift, 8915 // eliminate the and. 8916 unsigned NumBits = VT.getScalarSizeInBits()*2; 8917 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8918 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8919 } 8920 break; 8921 #endif 8922 } 8923 8924 // Memoize the node unless it returns a flag. 8925 SDNode *N; 8926 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8927 FoldingSetNodeID ID; 8928 AddNodeIDNode(ID, Opcode, VTList, Ops); 8929 void *IP = nullptr; 8930 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8931 return SDValue(E, 0); 8932 8933 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8934 createOperands(N, Ops); 8935 CSEMap.InsertNode(N, IP); 8936 } else { 8937 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8938 createOperands(N, Ops); 8939 } 8940 8941 N->setFlags(Flags); 8942 InsertNode(N); 8943 SDValue V(N, 0); 8944 NewSDValueDbgMsg(V, "Creating new node: ", this); 8945 return V; 8946 } 8947 8948 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8949 SDVTList VTList) { 8950 return getNode(Opcode, DL, VTList, None); 8951 } 8952 8953 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8954 SDValue N1) { 8955 SDValue Ops[] = { N1 }; 8956 return getNode(Opcode, DL, VTList, Ops); 8957 } 8958 8959 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8960 SDValue N1, SDValue N2) { 8961 SDValue Ops[] = { N1, N2 }; 8962 return getNode(Opcode, DL, VTList, Ops); 8963 } 8964 8965 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8966 SDValue N1, SDValue N2, SDValue N3) { 8967 SDValue Ops[] = { N1, N2, N3 }; 8968 return getNode(Opcode, DL, VTList, Ops); 8969 } 8970 8971 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8972 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8973 SDValue Ops[] = { N1, N2, N3, N4 }; 8974 return getNode(Opcode, DL, VTList, Ops); 8975 } 8976 8977 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8978 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8979 SDValue N5) { 8980 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8981 return getNode(Opcode, DL, VTList, Ops); 8982 } 8983 8984 SDVTList SelectionDAG::getVTList(EVT VT) { 8985 return makeVTList(SDNode::getValueTypeList(VT), 1); 8986 } 8987 8988 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8989 FoldingSetNodeID ID; 8990 ID.AddInteger(2U); 8991 ID.AddInteger(VT1.getRawBits()); 8992 ID.AddInteger(VT2.getRawBits()); 8993 8994 void *IP = nullptr; 8995 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8996 if (!Result) { 8997 EVT *Array = Allocator.Allocate<EVT>(2); 8998 Array[0] = VT1; 8999 Array[1] = VT2; 9000 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 9001 VTListMap.InsertNode(Result, IP); 9002 } 9003 return Result->getSDVTList(); 9004 } 9005 9006 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 9007 FoldingSetNodeID ID; 9008 ID.AddInteger(3U); 9009 ID.AddInteger(VT1.getRawBits()); 9010 ID.AddInteger(VT2.getRawBits()); 9011 ID.AddInteger(VT3.getRawBits()); 9012 9013 void *IP = nullptr; 9014 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9015 if (!Result) { 9016 EVT *Array = Allocator.Allocate<EVT>(3); 9017 Array[0] = VT1; 9018 Array[1] = VT2; 9019 Array[2] = VT3; 9020 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9021 VTListMap.InsertNode(Result, IP); 9022 } 9023 return Result->getSDVTList(); 9024 } 9025 9026 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9027 FoldingSetNodeID ID; 9028 ID.AddInteger(4U); 9029 ID.AddInteger(VT1.getRawBits()); 9030 ID.AddInteger(VT2.getRawBits()); 9031 ID.AddInteger(VT3.getRawBits()); 9032 ID.AddInteger(VT4.getRawBits()); 9033 9034 void *IP = nullptr; 9035 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9036 if (!Result) { 9037 EVT *Array = Allocator.Allocate<EVT>(4); 9038 Array[0] = VT1; 9039 Array[1] = VT2; 9040 Array[2] = VT3; 9041 Array[3] = VT4; 9042 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9043 VTListMap.InsertNode(Result, IP); 9044 } 9045 return Result->getSDVTList(); 9046 } 9047 9048 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9049 unsigned NumVTs = VTs.size(); 9050 FoldingSetNodeID ID; 9051 ID.AddInteger(NumVTs); 9052 for (unsigned index = 0; index < NumVTs; index++) { 9053 ID.AddInteger(VTs[index].getRawBits()); 9054 } 9055 9056 void *IP = nullptr; 9057 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9058 if (!Result) { 9059 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9060 llvm::copy(VTs, Array); 9061 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9062 VTListMap.InsertNode(Result, IP); 9063 } 9064 return Result->getSDVTList(); 9065 } 9066 9067 9068 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9069 /// specified operands. If the resultant node already exists in the DAG, 9070 /// this does not modify the specified node, instead it returns the node that 9071 /// already exists. If the resultant node does not exist in the DAG, the 9072 /// input node is returned. As a degenerate case, if you specify the same 9073 /// input operands as the node already has, the input node is returned. 9074 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9075 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9076 9077 // Check to see if there is no change. 9078 if (Op == N->getOperand(0)) return N; 9079 9080 // See if the modified node already exists. 9081 void *InsertPos = nullptr; 9082 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9083 return Existing; 9084 9085 // Nope it doesn't. Remove the node from its current place in the maps. 9086 if (InsertPos) 9087 if (!RemoveNodeFromCSEMaps(N)) 9088 InsertPos = nullptr; 9089 9090 // Now we update the operands. 9091 N->OperandList[0].set(Op); 9092 9093 updateDivergence(N); 9094 // If this gets put into a CSE map, add it. 9095 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9096 return N; 9097 } 9098 9099 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9100 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9101 9102 // Check to see if there is no change. 9103 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9104 return N; // No operands changed, just return the input node. 9105 9106 // See if the modified node already exists. 9107 void *InsertPos = nullptr; 9108 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9109 return Existing; 9110 9111 // Nope it doesn't. Remove the node from its current place in the maps. 9112 if (InsertPos) 9113 if (!RemoveNodeFromCSEMaps(N)) 9114 InsertPos = nullptr; 9115 9116 // Now we update the operands. 9117 if (N->OperandList[0] != Op1) 9118 N->OperandList[0].set(Op1); 9119 if (N->OperandList[1] != Op2) 9120 N->OperandList[1].set(Op2); 9121 9122 updateDivergence(N); 9123 // If this gets put into a CSE map, add it. 9124 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9125 return N; 9126 } 9127 9128 SDNode *SelectionDAG:: 9129 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9130 SDValue Ops[] = { Op1, Op2, Op3 }; 9131 return UpdateNodeOperands(N, Ops); 9132 } 9133 9134 SDNode *SelectionDAG:: 9135 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9136 SDValue Op3, SDValue Op4) { 9137 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9138 return UpdateNodeOperands(N, Ops); 9139 } 9140 9141 SDNode *SelectionDAG:: 9142 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9143 SDValue Op3, SDValue Op4, SDValue Op5) { 9144 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9145 return UpdateNodeOperands(N, Ops); 9146 } 9147 9148 SDNode *SelectionDAG:: 9149 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9150 unsigned NumOps = Ops.size(); 9151 assert(N->getNumOperands() == NumOps && 9152 "Update with wrong number of operands"); 9153 9154 // If no operands changed just return the input node. 9155 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9156 return N; 9157 9158 // See if the modified node already exists. 9159 void *InsertPos = nullptr; 9160 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9161 return Existing; 9162 9163 // Nope it doesn't. Remove the node from its current place in the maps. 9164 if (InsertPos) 9165 if (!RemoveNodeFromCSEMaps(N)) 9166 InsertPos = nullptr; 9167 9168 // Now we update the operands. 9169 for (unsigned i = 0; i != NumOps; ++i) 9170 if (N->OperandList[i] != Ops[i]) 9171 N->OperandList[i].set(Ops[i]); 9172 9173 updateDivergence(N); 9174 // If this gets put into a CSE map, add it. 9175 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9176 return N; 9177 } 9178 9179 /// DropOperands - Release the operands and set this node to have 9180 /// zero operands. 9181 void SDNode::DropOperands() { 9182 // Unlike the code in MorphNodeTo that does this, we don't need to 9183 // watch for dead nodes here. 9184 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9185 SDUse &Use = *I++; 9186 Use.set(SDValue()); 9187 } 9188 } 9189 9190 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9191 ArrayRef<MachineMemOperand *> NewMemRefs) { 9192 if (NewMemRefs.empty()) { 9193 N->clearMemRefs(); 9194 return; 9195 } 9196 9197 // Check if we can avoid allocating by storing a single reference directly. 9198 if (NewMemRefs.size() == 1) { 9199 N->MemRefs = NewMemRefs[0]; 9200 N->NumMemRefs = 1; 9201 return; 9202 } 9203 9204 MachineMemOperand **MemRefsBuffer = 9205 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 9206 llvm::copy(NewMemRefs, MemRefsBuffer); 9207 N->MemRefs = MemRefsBuffer; 9208 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 9209 } 9210 9211 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 9212 /// machine opcode. 9213 /// 9214 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9215 EVT VT) { 9216 SDVTList VTs = getVTList(VT); 9217 return SelectNodeTo(N, MachineOpc, VTs, None); 9218 } 9219 9220 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9221 EVT VT, SDValue Op1) { 9222 SDVTList VTs = getVTList(VT); 9223 SDValue Ops[] = { Op1 }; 9224 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9225 } 9226 9227 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9228 EVT VT, SDValue Op1, 9229 SDValue Op2) { 9230 SDVTList VTs = getVTList(VT); 9231 SDValue Ops[] = { Op1, Op2 }; 9232 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9233 } 9234 9235 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9236 EVT VT, SDValue Op1, 9237 SDValue Op2, SDValue Op3) { 9238 SDVTList VTs = getVTList(VT); 9239 SDValue Ops[] = { Op1, Op2, Op3 }; 9240 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9241 } 9242 9243 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9244 EVT VT, ArrayRef<SDValue> Ops) { 9245 SDVTList VTs = getVTList(VT); 9246 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9247 } 9248 9249 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9250 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 9251 SDVTList VTs = getVTList(VT1, VT2); 9252 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9253 } 9254 9255 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9256 EVT VT1, EVT VT2) { 9257 SDVTList VTs = getVTList(VT1, VT2); 9258 return SelectNodeTo(N, MachineOpc, VTs, None); 9259 } 9260 9261 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9262 EVT VT1, EVT VT2, EVT VT3, 9263 ArrayRef<SDValue> Ops) { 9264 SDVTList VTs = getVTList(VT1, VT2, VT3); 9265 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9266 } 9267 9268 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9269 EVT VT1, EVT VT2, 9270 SDValue Op1, SDValue Op2) { 9271 SDVTList VTs = getVTList(VT1, VT2); 9272 SDValue Ops[] = { Op1, Op2 }; 9273 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9274 } 9275 9276 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9277 SDVTList VTs,ArrayRef<SDValue> Ops) { 9278 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 9279 // Reset the NodeID to -1. 9280 New->setNodeId(-1); 9281 if (New != N) { 9282 ReplaceAllUsesWith(N, New); 9283 RemoveDeadNode(N); 9284 } 9285 return New; 9286 } 9287 9288 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 9289 /// the line number information on the merged node since it is not possible to 9290 /// preserve the information that operation is associated with multiple lines. 9291 /// This will make the debugger working better at -O0, were there is a higher 9292 /// probability having other instructions associated with that line. 9293 /// 9294 /// For IROrder, we keep the smaller of the two 9295 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 9296 DebugLoc NLoc = N->getDebugLoc(); 9297 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 9298 N->setDebugLoc(DebugLoc()); 9299 } 9300 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 9301 N->setIROrder(Order); 9302 return N; 9303 } 9304 9305 /// MorphNodeTo - This *mutates* the specified node to have the specified 9306 /// return type, opcode, and operands. 9307 /// 9308 /// Note that MorphNodeTo returns the resultant node. If there is already a 9309 /// node of the specified opcode and operands, it returns that node instead of 9310 /// the current one. Note that the SDLoc need not be the same. 9311 /// 9312 /// Using MorphNodeTo is faster than creating a new node and swapping it in 9313 /// with ReplaceAllUsesWith both because it often avoids allocating a new 9314 /// node, and because it doesn't require CSE recalculation for any of 9315 /// the node's users. 9316 /// 9317 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 9318 /// As a consequence it isn't appropriate to use from within the DAG combiner or 9319 /// the legalizer which maintain worklists that would need to be updated when 9320 /// deleting things. 9321 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 9322 SDVTList VTs, ArrayRef<SDValue> Ops) { 9323 // If an identical node already exists, use it. 9324 void *IP = nullptr; 9325 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 9326 FoldingSetNodeID ID; 9327 AddNodeIDNode(ID, Opc, VTs, Ops); 9328 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 9329 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 9330 } 9331 9332 if (!RemoveNodeFromCSEMaps(N)) 9333 IP = nullptr; 9334 9335 // Start the morphing. 9336 N->NodeType = Opc; 9337 N->ValueList = VTs.VTs; 9338 N->NumValues = VTs.NumVTs; 9339 9340 // Clear the operands list, updating used nodes to remove this from their 9341 // use list. Keep track of any operands that become dead as a result. 9342 SmallPtrSet<SDNode*, 16> DeadNodeSet; 9343 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 9344 SDUse &Use = *I++; 9345 SDNode *Used = Use.getNode(); 9346 Use.set(SDValue()); 9347 if (Used->use_empty()) 9348 DeadNodeSet.insert(Used); 9349 } 9350 9351 // For MachineNode, initialize the memory references information. 9352 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 9353 MN->clearMemRefs(); 9354 9355 // Swap for an appropriately sized array from the recycler. 9356 removeOperands(N); 9357 createOperands(N, Ops); 9358 9359 // Delete any nodes that are still dead after adding the uses for the 9360 // new operands. 9361 if (!DeadNodeSet.empty()) { 9362 SmallVector<SDNode *, 16> DeadNodes; 9363 for (SDNode *N : DeadNodeSet) 9364 if (N->use_empty()) 9365 DeadNodes.push_back(N); 9366 RemoveDeadNodes(DeadNodes); 9367 } 9368 9369 if (IP) 9370 CSEMap.InsertNode(N, IP); // Memoize the new node. 9371 return N; 9372 } 9373 9374 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9375 unsigned OrigOpc = Node->getOpcode(); 9376 unsigned NewOpc; 9377 switch (OrigOpc) { 9378 default: 9379 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9380 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9381 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9382 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9383 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9384 #include "llvm/IR/ConstrainedOps.def" 9385 } 9386 9387 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9388 9389 // We're taking this node out of the chain, so we need to re-link things. 9390 SDValue InputChain = Node->getOperand(0); 9391 SDValue OutputChain = SDValue(Node, 1); 9392 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9393 9394 SmallVector<SDValue, 3> Ops; 9395 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9396 Ops.push_back(Node->getOperand(i)); 9397 9398 SDVTList VTs = getVTList(Node->getValueType(0)); 9399 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9400 9401 // MorphNodeTo can operate in two ways: if an existing node with the 9402 // specified operands exists, it can just return it. Otherwise, it 9403 // updates the node in place to have the requested operands. 9404 if (Res == Node) { 9405 // If we updated the node in place, reset the node ID. To the isel, 9406 // this should be just like a newly allocated machine node. 9407 Res->setNodeId(-1); 9408 } else { 9409 ReplaceAllUsesWith(Node, Res); 9410 RemoveDeadNode(Node); 9411 } 9412 9413 return Res; 9414 } 9415 9416 /// getMachineNode - These are used for target selectors to create a new node 9417 /// with specified return type(s), MachineInstr opcode, and operands. 9418 /// 9419 /// Note that getMachineNode returns the resultant node. If there is already a 9420 /// node of the specified opcode and operands, it returns that node instead of 9421 /// the current one. 9422 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9423 EVT VT) { 9424 SDVTList VTs = getVTList(VT); 9425 return getMachineNode(Opcode, dl, VTs, None); 9426 } 9427 9428 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9429 EVT VT, SDValue Op1) { 9430 SDVTList VTs = getVTList(VT); 9431 SDValue Ops[] = { Op1 }; 9432 return getMachineNode(Opcode, dl, VTs, Ops); 9433 } 9434 9435 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9436 EVT VT, SDValue Op1, SDValue Op2) { 9437 SDVTList VTs = getVTList(VT); 9438 SDValue Ops[] = { Op1, Op2 }; 9439 return getMachineNode(Opcode, dl, VTs, Ops); 9440 } 9441 9442 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9443 EVT VT, SDValue Op1, SDValue Op2, 9444 SDValue Op3) { 9445 SDVTList VTs = getVTList(VT); 9446 SDValue Ops[] = { Op1, Op2, Op3 }; 9447 return getMachineNode(Opcode, dl, VTs, Ops); 9448 } 9449 9450 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9451 EVT VT, ArrayRef<SDValue> Ops) { 9452 SDVTList VTs = getVTList(VT); 9453 return getMachineNode(Opcode, dl, VTs, Ops); 9454 } 9455 9456 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9457 EVT VT1, EVT VT2, SDValue Op1, 9458 SDValue Op2) { 9459 SDVTList VTs = getVTList(VT1, VT2); 9460 SDValue Ops[] = { Op1, Op2 }; 9461 return getMachineNode(Opcode, dl, VTs, Ops); 9462 } 9463 9464 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9465 EVT VT1, EVT VT2, SDValue Op1, 9466 SDValue Op2, SDValue Op3) { 9467 SDVTList VTs = getVTList(VT1, VT2); 9468 SDValue Ops[] = { Op1, Op2, Op3 }; 9469 return getMachineNode(Opcode, dl, VTs, Ops); 9470 } 9471 9472 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9473 EVT VT1, EVT VT2, 9474 ArrayRef<SDValue> Ops) { 9475 SDVTList VTs = getVTList(VT1, VT2); 9476 return getMachineNode(Opcode, dl, VTs, Ops); 9477 } 9478 9479 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9480 EVT VT1, EVT VT2, EVT VT3, 9481 SDValue Op1, SDValue Op2) { 9482 SDVTList VTs = getVTList(VT1, VT2, VT3); 9483 SDValue Ops[] = { Op1, Op2 }; 9484 return getMachineNode(Opcode, dl, VTs, Ops); 9485 } 9486 9487 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9488 EVT VT1, EVT VT2, EVT VT3, 9489 SDValue Op1, SDValue Op2, 9490 SDValue Op3) { 9491 SDVTList VTs = getVTList(VT1, VT2, VT3); 9492 SDValue Ops[] = { Op1, Op2, Op3 }; 9493 return getMachineNode(Opcode, dl, VTs, Ops); 9494 } 9495 9496 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9497 EVT VT1, EVT VT2, EVT VT3, 9498 ArrayRef<SDValue> Ops) { 9499 SDVTList VTs = getVTList(VT1, VT2, VT3); 9500 return getMachineNode(Opcode, dl, VTs, Ops); 9501 } 9502 9503 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9504 ArrayRef<EVT> ResultTys, 9505 ArrayRef<SDValue> Ops) { 9506 SDVTList VTs = getVTList(ResultTys); 9507 return getMachineNode(Opcode, dl, VTs, Ops); 9508 } 9509 9510 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9511 SDVTList VTs, 9512 ArrayRef<SDValue> Ops) { 9513 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9514 MachineSDNode *N; 9515 void *IP = nullptr; 9516 9517 if (DoCSE) { 9518 FoldingSetNodeID ID; 9519 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9520 IP = nullptr; 9521 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9522 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9523 } 9524 } 9525 9526 // Allocate a new MachineSDNode. 9527 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9528 createOperands(N, Ops); 9529 9530 if (DoCSE) 9531 CSEMap.InsertNode(N, IP); 9532 9533 InsertNode(N); 9534 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9535 return N; 9536 } 9537 9538 /// getTargetExtractSubreg - A convenience function for creating 9539 /// TargetOpcode::EXTRACT_SUBREG nodes. 9540 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9541 SDValue Operand) { 9542 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9543 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9544 VT, Operand, SRIdxVal); 9545 return SDValue(Subreg, 0); 9546 } 9547 9548 /// getTargetInsertSubreg - A convenience function for creating 9549 /// TargetOpcode::INSERT_SUBREG nodes. 9550 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9551 SDValue Operand, SDValue Subreg) { 9552 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9553 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9554 VT, Operand, Subreg, SRIdxVal); 9555 return SDValue(Result, 0); 9556 } 9557 9558 /// getNodeIfExists - Get the specified node if it's already available, or 9559 /// else return NULL. 9560 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9561 ArrayRef<SDValue> Ops) { 9562 SDNodeFlags Flags; 9563 if (Inserter) 9564 Flags = Inserter->getFlags(); 9565 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9566 } 9567 9568 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9569 ArrayRef<SDValue> Ops, 9570 const SDNodeFlags Flags) { 9571 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9572 FoldingSetNodeID ID; 9573 AddNodeIDNode(ID, Opcode, VTList, Ops); 9574 void *IP = nullptr; 9575 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9576 E->intersectFlagsWith(Flags); 9577 return E; 9578 } 9579 } 9580 return nullptr; 9581 } 9582 9583 /// doesNodeExist - Check if a node exists without modifying its flags. 9584 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9585 ArrayRef<SDValue> Ops) { 9586 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9587 FoldingSetNodeID ID; 9588 AddNodeIDNode(ID, Opcode, VTList, Ops); 9589 void *IP = nullptr; 9590 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9591 return true; 9592 } 9593 return false; 9594 } 9595 9596 /// getDbgValue - Creates a SDDbgValue node. 9597 /// 9598 /// SDNode 9599 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9600 SDNode *N, unsigned R, bool IsIndirect, 9601 const DebugLoc &DL, unsigned O) { 9602 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9603 "Expected inlined-at fields to agree"); 9604 return new (DbgInfo->getAlloc()) 9605 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9606 {}, IsIndirect, DL, O, 9607 /*IsVariadic=*/false); 9608 } 9609 9610 /// Constant 9611 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9612 DIExpression *Expr, 9613 const Value *C, 9614 const DebugLoc &DL, unsigned O) { 9615 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9616 "Expected inlined-at fields to agree"); 9617 return new (DbgInfo->getAlloc()) 9618 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9619 /*IsIndirect=*/false, DL, O, 9620 /*IsVariadic=*/false); 9621 } 9622 9623 /// FrameIndex 9624 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9625 DIExpression *Expr, unsigned FI, 9626 bool IsIndirect, 9627 const DebugLoc &DL, 9628 unsigned O) { 9629 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9630 "Expected inlined-at fields to agree"); 9631 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9632 } 9633 9634 /// FrameIndex with dependencies 9635 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9636 DIExpression *Expr, unsigned FI, 9637 ArrayRef<SDNode *> Dependencies, 9638 bool IsIndirect, 9639 const DebugLoc &DL, 9640 unsigned O) { 9641 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9642 "Expected inlined-at fields to agree"); 9643 return new (DbgInfo->getAlloc()) 9644 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9645 Dependencies, IsIndirect, DL, O, 9646 /*IsVariadic=*/false); 9647 } 9648 9649 /// VReg 9650 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9651 unsigned VReg, bool IsIndirect, 9652 const DebugLoc &DL, unsigned O) { 9653 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9654 "Expected inlined-at fields to agree"); 9655 return new (DbgInfo->getAlloc()) 9656 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9657 {}, IsIndirect, DL, O, 9658 /*IsVariadic=*/false); 9659 } 9660 9661 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9662 ArrayRef<SDDbgOperand> Locs, 9663 ArrayRef<SDNode *> Dependencies, 9664 bool IsIndirect, const DebugLoc &DL, 9665 unsigned O, bool IsVariadic) { 9666 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9667 "Expected inlined-at fields to agree"); 9668 return new (DbgInfo->getAlloc()) 9669 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9670 DL, O, IsVariadic); 9671 } 9672 9673 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9674 unsigned OffsetInBits, unsigned SizeInBits, 9675 bool InvalidateDbg) { 9676 SDNode *FromNode = From.getNode(); 9677 SDNode *ToNode = To.getNode(); 9678 assert(FromNode && ToNode && "Can't modify dbg values"); 9679 9680 // PR35338 9681 // TODO: assert(From != To && "Redundant dbg value transfer"); 9682 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9683 if (From == To || FromNode == ToNode) 9684 return; 9685 9686 if (!FromNode->getHasDebugValue()) 9687 return; 9688 9689 SDDbgOperand FromLocOp = 9690 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9691 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9692 9693 SmallVector<SDDbgValue *, 2> ClonedDVs; 9694 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9695 if (Dbg->isInvalidated()) 9696 continue; 9697 9698 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9699 9700 // Create a new location ops vector that is equal to the old vector, but 9701 // with each instance of FromLocOp replaced with ToLocOp. 9702 bool Changed = false; 9703 auto NewLocOps = Dbg->copyLocationOps(); 9704 std::replace_if( 9705 NewLocOps.begin(), NewLocOps.end(), 9706 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9707 bool Match = Op == FromLocOp; 9708 Changed |= Match; 9709 return Match; 9710 }, 9711 ToLocOp); 9712 // Ignore this SDDbgValue if we didn't find a matching location. 9713 if (!Changed) 9714 continue; 9715 9716 DIVariable *Var = Dbg->getVariable(); 9717 auto *Expr = Dbg->getExpression(); 9718 // If a fragment is requested, update the expression. 9719 if (SizeInBits) { 9720 // When splitting a larger (e.g., sign-extended) value whose 9721 // lower bits are described with an SDDbgValue, do not attempt 9722 // to transfer the SDDbgValue to the upper bits. 9723 if (auto FI = Expr->getFragmentInfo()) 9724 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9725 continue; 9726 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9727 SizeInBits); 9728 if (!Fragment) 9729 continue; 9730 Expr = *Fragment; 9731 } 9732 9733 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9734 // Clone the SDDbgValue and move it to To. 9735 SDDbgValue *Clone = getDbgValueList( 9736 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9737 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9738 Dbg->isVariadic()); 9739 ClonedDVs.push_back(Clone); 9740 9741 if (InvalidateDbg) { 9742 // Invalidate value and indicate the SDDbgValue should not be emitted. 9743 Dbg->setIsInvalidated(); 9744 Dbg->setIsEmitted(); 9745 } 9746 } 9747 9748 for (SDDbgValue *Dbg : ClonedDVs) { 9749 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9750 "Transferred DbgValues should depend on the new SDNode"); 9751 AddDbgValue(Dbg, false); 9752 } 9753 } 9754 9755 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9756 if (!N.getHasDebugValue()) 9757 return; 9758 9759 SmallVector<SDDbgValue *, 2> ClonedDVs; 9760 for (auto DV : GetDbgValues(&N)) { 9761 if (DV->isInvalidated()) 9762 continue; 9763 switch (N.getOpcode()) { 9764 default: 9765 break; 9766 case ISD::ADD: 9767 SDValue N0 = N.getOperand(0); 9768 SDValue N1 = N.getOperand(1); 9769 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9770 isConstantIntBuildVectorOrConstantInt(N1)) { 9771 uint64_t Offset = N.getConstantOperandVal(1); 9772 9773 // Rewrite an ADD constant node into a DIExpression. Since we are 9774 // performing arithmetic to compute the variable's *value* in the 9775 // DIExpression, we need to mark the expression with a 9776 // DW_OP_stack_value. 9777 auto *DIExpr = DV->getExpression(); 9778 auto NewLocOps = DV->copyLocationOps(); 9779 bool Changed = false; 9780 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9781 // We're not given a ResNo to compare against because the whole 9782 // node is going away. We know that any ISD::ADD only has one 9783 // result, so we can assume any node match is using the result. 9784 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9785 NewLocOps[i].getSDNode() != &N) 9786 continue; 9787 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9788 SmallVector<uint64_t, 3> ExprOps; 9789 DIExpression::appendOffset(ExprOps, Offset); 9790 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9791 Changed = true; 9792 } 9793 (void)Changed; 9794 assert(Changed && "Salvage target doesn't use N"); 9795 9796 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9797 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9798 NewLocOps, AdditionalDependencies, 9799 DV->isIndirect(), DV->getDebugLoc(), 9800 DV->getOrder(), DV->isVariadic()); 9801 ClonedDVs.push_back(Clone); 9802 DV->setIsInvalidated(); 9803 DV->setIsEmitted(); 9804 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9805 N0.getNode()->dumprFull(this); 9806 dbgs() << " into " << *DIExpr << '\n'); 9807 } 9808 } 9809 } 9810 9811 for (SDDbgValue *Dbg : ClonedDVs) { 9812 assert(!Dbg->getSDNodes().empty() && 9813 "Salvaged DbgValue should depend on a new SDNode"); 9814 AddDbgValue(Dbg, false); 9815 } 9816 } 9817 9818 /// Creates a SDDbgLabel node. 9819 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9820 const DebugLoc &DL, unsigned O) { 9821 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9822 "Expected inlined-at fields to agree"); 9823 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9824 } 9825 9826 namespace { 9827 9828 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9829 /// pointed to by a use iterator is deleted, increment the use iterator 9830 /// so that it doesn't dangle. 9831 /// 9832 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9833 SDNode::use_iterator &UI; 9834 SDNode::use_iterator &UE; 9835 9836 void NodeDeleted(SDNode *N, SDNode *E) override { 9837 // Increment the iterator as needed. 9838 while (UI != UE && N == *UI) 9839 ++UI; 9840 } 9841 9842 public: 9843 RAUWUpdateListener(SelectionDAG &d, 9844 SDNode::use_iterator &ui, 9845 SDNode::use_iterator &ue) 9846 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9847 }; 9848 9849 } // end anonymous namespace 9850 9851 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9852 /// This can cause recursive merging of nodes in the DAG. 9853 /// 9854 /// This version assumes From has a single result value. 9855 /// 9856 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9857 SDNode *From = FromN.getNode(); 9858 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9859 "Cannot replace with this method!"); 9860 assert(From != To.getNode() && "Cannot replace uses of with self"); 9861 9862 // Preserve Debug Values 9863 transferDbgValues(FromN, To); 9864 9865 // Iterate over all the existing uses of From. New uses will be added 9866 // to the beginning of the use list, which we avoid visiting. 9867 // This specifically avoids visiting uses of From that arise while the 9868 // replacement is happening, because any such uses would be the result 9869 // of CSE: If an existing node looks like From after one of its operands 9870 // is replaced by To, we don't want to replace of all its users with To 9871 // too. See PR3018 for more info. 9872 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9873 RAUWUpdateListener Listener(*this, UI, UE); 9874 while (UI != UE) { 9875 SDNode *User = *UI; 9876 9877 // This node is about to morph, remove its old self from the CSE maps. 9878 RemoveNodeFromCSEMaps(User); 9879 9880 // A user can appear in a use list multiple times, and when this 9881 // happens the uses are usually next to each other in the list. 9882 // To help reduce the number of CSE recomputations, process all 9883 // the uses of this user that we can find this way. 9884 do { 9885 SDUse &Use = UI.getUse(); 9886 ++UI; 9887 Use.set(To); 9888 if (To->isDivergent() != From->isDivergent()) 9889 updateDivergence(User); 9890 } while (UI != UE && *UI == User); 9891 // Now that we have modified User, add it back to the CSE maps. If it 9892 // already exists there, recursively merge the results together. 9893 AddModifiedNodeToCSEMaps(User); 9894 } 9895 9896 // If we just RAUW'd the root, take note. 9897 if (FromN == getRoot()) 9898 setRoot(To); 9899 } 9900 9901 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9902 /// This can cause recursive merging of nodes in the DAG. 9903 /// 9904 /// This version assumes that for each value of From, there is a 9905 /// corresponding value in To in the same position with the same type. 9906 /// 9907 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9908 #ifndef NDEBUG 9909 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9910 assert((!From->hasAnyUseOfValue(i) || 9911 From->getValueType(i) == To->getValueType(i)) && 9912 "Cannot use this version of ReplaceAllUsesWith!"); 9913 #endif 9914 9915 // Handle the trivial case. 9916 if (From == To) 9917 return; 9918 9919 // Preserve Debug Info. Only do this if there's a use. 9920 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9921 if (From->hasAnyUseOfValue(i)) { 9922 assert((i < To->getNumValues()) && "Invalid To location"); 9923 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9924 } 9925 9926 // Iterate over just the existing users of From. See the comments in 9927 // the ReplaceAllUsesWith above. 9928 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9929 RAUWUpdateListener Listener(*this, UI, UE); 9930 while (UI != UE) { 9931 SDNode *User = *UI; 9932 9933 // This node is about to morph, remove its old self from the CSE maps. 9934 RemoveNodeFromCSEMaps(User); 9935 9936 // A user can appear in a use list multiple times, and when this 9937 // happens the uses are usually next to each other in the list. 9938 // To help reduce the number of CSE recomputations, process all 9939 // the uses of this user that we can find this way. 9940 do { 9941 SDUse &Use = UI.getUse(); 9942 ++UI; 9943 Use.setNode(To); 9944 if (To->isDivergent() != From->isDivergent()) 9945 updateDivergence(User); 9946 } while (UI != UE && *UI == User); 9947 9948 // Now that we have modified User, add it back to the CSE maps. If it 9949 // already exists there, recursively merge the results together. 9950 AddModifiedNodeToCSEMaps(User); 9951 } 9952 9953 // If we just RAUW'd the root, take note. 9954 if (From == getRoot().getNode()) 9955 setRoot(SDValue(To, getRoot().getResNo())); 9956 } 9957 9958 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9959 /// This can cause recursive merging of nodes in the DAG. 9960 /// 9961 /// This version can replace From with any result values. To must match the 9962 /// number and types of values returned by From. 9963 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9964 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9965 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9966 9967 // Preserve Debug Info. 9968 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9969 transferDbgValues(SDValue(From, i), To[i]); 9970 9971 // Iterate over just the existing users of From. See the comments in 9972 // the ReplaceAllUsesWith above. 9973 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9974 RAUWUpdateListener Listener(*this, UI, UE); 9975 while (UI != UE) { 9976 SDNode *User = *UI; 9977 9978 // This node is about to morph, remove its old self from the CSE maps. 9979 RemoveNodeFromCSEMaps(User); 9980 9981 // A user can appear in a use list multiple times, and when this happens the 9982 // uses are usually next to each other in the list. To help reduce the 9983 // number of CSE and divergence recomputations, process all the uses of this 9984 // user that we can find this way. 9985 bool To_IsDivergent = false; 9986 do { 9987 SDUse &Use = UI.getUse(); 9988 const SDValue &ToOp = To[Use.getResNo()]; 9989 ++UI; 9990 Use.set(ToOp); 9991 To_IsDivergent |= ToOp->isDivergent(); 9992 } while (UI != UE && *UI == User); 9993 9994 if (To_IsDivergent != From->isDivergent()) 9995 updateDivergence(User); 9996 9997 // Now that we have modified User, add it back to the CSE maps. If it 9998 // already exists there, recursively merge the results together. 9999 AddModifiedNodeToCSEMaps(User); 10000 } 10001 10002 // If we just RAUW'd the root, take note. 10003 if (From == getRoot().getNode()) 10004 setRoot(SDValue(To[getRoot().getResNo()])); 10005 } 10006 10007 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 10008 /// uses of other values produced by From.getNode() alone. The Deleted 10009 /// vector is handled the same way as for ReplaceAllUsesWith. 10010 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 10011 // Handle the really simple, really trivial case efficiently. 10012 if (From == To) return; 10013 10014 // Handle the simple, trivial, case efficiently. 10015 if (From.getNode()->getNumValues() == 1) { 10016 ReplaceAllUsesWith(From, To); 10017 return; 10018 } 10019 10020 // Preserve Debug Info. 10021 transferDbgValues(From, To); 10022 10023 // Iterate over just the existing users of From. See the comments in 10024 // the ReplaceAllUsesWith above. 10025 SDNode::use_iterator UI = From.getNode()->use_begin(), 10026 UE = From.getNode()->use_end(); 10027 RAUWUpdateListener Listener(*this, UI, UE); 10028 while (UI != UE) { 10029 SDNode *User = *UI; 10030 bool UserRemovedFromCSEMaps = false; 10031 10032 // A user can appear in a use list multiple times, and when this 10033 // happens the uses are usually next to each other in the list. 10034 // To help reduce the number of CSE recomputations, process all 10035 // the uses of this user that we can find this way. 10036 do { 10037 SDUse &Use = UI.getUse(); 10038 10039 // Skip uses of different values from the same node. 10040 if (Use.getResNo() != From.getResNo()) { 10041 ++UI; 10042 continue; 10043 } 10044 10045 // If this node hasn't been modified yet, it's still in the CSE maps, 10046 // so remove its old self from the CSE maps. 10047 if (!UserRemovedFromCSEMaps) { 10048 RemoveNodeFromCSEMaps(User); 10049 UserRemovedFromCSEMaps = true; 10050 } 10051 10052 ++UI; 10053 Use.set(To); 10054 if (To->isDivergent() != From->isDivergent()) 10055 updateDivergence(User); 10056 } while (UI != UE && *UI == User); 10057 // We are iterating over all uses of the From node, so if a use 10058 // doesn't use the specific value, no changes are made. 10059 if (!UserRemovedFromCSEMaps) 10060 continue; 10061 10062 // Now that we have modified User, add it back to the CSE maps. If it 10063 // already exists there, recursively merge the results together. 10064 AddModifiedNodeToCSEMaps(User); 10065 } 10066 10067 // If we just RAUW'd the root, take note. 10068 if (From == getRoot()) 10069 setRoot(To); 10070 } 10071 10072 namespace { 10073 10074 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10075 /// to record information about a use. 10076 struct UseMemo { 10077 SDNode *User; 10078 unsigned Index; 10079 SDUse *Use; 10080 }; 10081 10082 /// operator< - Sort Memos by User. 10083 bool operator<(const UseMemo &L, const UseMemo &R) { 10084 return (intptr_t)L.User < (intptr_t)R.User; 10085 } 10086 10087 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10088 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10089 /// the node already has been taken care of recursively. 10090 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10091 SmallVector<UseMemo, 4> &Uses; 10092 10093 void NodeDeleted(SDNode *N, SDNode *E) override { 10094 for (UseMemo &Memo : Uses) 10095 if (Memo.User == N) 10096 Memo.User = nullptr; 10097 } 10098 10099 public: 10100 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10101 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10102 }; 10103 10104 } // end anonymous namespace 10105 10106 bool SelectionDAG::calculateDivergence(SDNode *N) { 10107 if (TLI->isSDNodeAlwaysUniform(N)) { 10108 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 10109 "Conflicting divergence information!"); 10110 return false; 10111 } 10112 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 10113 return true; 10114 for (auto &Op : N->ops()) { 10115 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10116 return true; 10117 } 10118 return false; 10119 } 10120 10121 void SelectionDAG::updateDivergence(SDNode *N) { 10122 SmallVector<SDNode *, 16> Worklist(1, N); 10123 do { 10124 N = Worklist.pop_back_val(); 10125 bool IsDivergent = calculateDivergence(N); 10126 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10127 N->SDNodeBits.IsDivergent = IsDivergent; 10128 llvm::append_range(Worklist, N->uses()); 10129 } 10130 } while (!Worklist.empty()); 10131 } 10132 10133 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10134 DenseMap<SDNode *, unsigned> Degree; 10135 Order.reserve(AllNodes.size()); 10136 for (auto &N : allnodes()) { 10137 unsigned NOps = N.getNumOperands(); 10138 Degree[&N] = NOps; 10139 if (0 == NOps) 10140 Order.push_back(&N); 10141 } 10142 for (size_t I = 0; I != Order.size(); ++I) { 10143 SDNode *N = Order[I]; 10144 for (auto U : N->uses()) { 10145 unsigned &UnsortedOps = Degree[U]; 10146 if (0 == --UnsortedOps) 10147 Order.push_back(U); 10148 } 10149 } 10150 } 10151 10152 #ifndef NDEBUG 10153 void SelectionDAG::VerifyDAGDivergence() { 10154 std::vector<SDNode *> TopoOrder; 10155 CreateTopologicalOrder(TopoOrder); 10156 for (auto *N : TopoOrder) { 10157 assert(calculateDivergence(N) == N->isDivergent() && 10158 "Divergence bit inconsistency detected"); 10159 } 10160 } 10161 #endif 10162 10163 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10164 /// uses of other values produced by From.getNode() alone. The same value 10165 /// may appear in both the From and To list. The Deleted vector is 10166 /// handled the same way as for ReplaceAllUsesWith. 10167 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10168 const SDValue *To, 10169 unsigned Num){ 10170 // Handle the simple, trivial case efficiently. 10171 if (Num == 1) 10172 return ReplaceAllUsesOfValueWith(*From, *To); 10173 10174 transferDbgValues(*From, *To); 10175 10176 // Read up all the uses and make records of them. This helps 10177 // processing new uses that are introduced during the 10178 // replacement process. 10179 SmallVector<UseMemo, 4> Uses; 10180 for (unsigned i = 0; i != Num; ++i) { 10181 unsigned FromResNo = From[i].getResNo(); 10182 SDNode *FromNode = From[i].getNode(); 10183 for (SDNode::use_iterator UI = FromNode->use_begin(), 10184 E = FromNode->use_end(); UI != E; ++UI) { 10185 SDUse &Use = UI.getUse(); 10186 if (Use.getResNo() == FromResNo) { 10187 UseMemo Memo = { *UI, i, &Use }; 10188 Uses.push_back(Memo); 10189 } 10190 } 10191 } 10192 10193 // Sort the uses, so that all the uses from a given User are together. 10194 llvm::sort(Uses); 10195 RAUOVWUpdateListener Listener(*this, Uses); 10196 10197 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 10198 UseIndex != UseIndexEnd; ) { 10199 // We know that this user uses some value of From. If it is the right 10200 // value, update it. 10201 SDNode *User = Uses[UseIndex].User; 10202 // If the node has been deleted by recursive CSE updates when updating 10203 // another node, then just skip this entry. 10204 if (User == nullptr) { 10205 ++UseIndex; 10206 continue; 10207 } 10208 10209 // This node is about to morph, remove its old self from the CSE maps. 10210 RemoveNodeFromCSEMaps(User); 10211 10212 // The Uses array is sorted, so all the uses for a given User 10213 // are next to each other in the list. 10214 // To help reduce the number of CSE recomputations, process all 10215 // the uses of this user that we can find this way. 10216 do { 10217 unsigned i = Uses[UseIndex].Index; 10218 SDUse &Use = *Uses[UseIndex].Use; 10219 ++UseIndex; 10220 10221 Use.set(To[i]); 10222 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 10223 10224 // Now that we have modified User, add it back to the CSE maps. If it 10225 // already exists there, recursively merge the results together. 10226 AddModifiedNodeToCSEMaps(User); 10227 } 10228 } 10229 10230 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 10231 /// based on their topological order. It returns the maximum id and a vector 10232 /// of the SDNodes* in assigned order by reference. 10233 unsigned SelectionDAG::AssignTopologicalOrder() { 10234 unsigned DAGSize = 0; 10235 10236 // SortedPos tracks the progress of the algorithm. Nodes before it are 10237 // sorted, nodes after it are unsorted. When the algorithm completes 10238 // it is at the end of the list. 10239 allnodes_iterator SortedPos = allnodes_begin(); 10240 10241 // Visit all the nodes. Move nodes with no operands to the front of 10242 // the list immediately. Annotate nodes that do have operands with their 10243 // operand count. Before we do this, the Node Id fields of the nodes 10244 // may contain arbitrary values. After, the Node Id fields for nodes 10245 // before SortedPos will contain the topological sort index, and the 10246 // Node Id fields for nodes At SortedPos and after will contain the 10247 // count of outstanding operands. 10248 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 10249 checkForCycles(&N, this); 10250 unsigned Degree = N.getNumOperands(); 10251 if (Degree == 0) { 10252 // A node with no uses, add it to the result array immediately. 10253 N.setNodeId(DAGSize++); 10254 allnodes_iterator Q(&N); 10255 if (Q != SortedPos) 10256 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 10257 assert(SortedPos != AllNodes.end() && "Overran node list"); 10258 ++SortedPos; 10259 } else { 10260 // Temporarily use the Node Id as scratch space for the degree count. 10261 N.setNodeId(Degree); 10262 } 10263 } 10264 10265 // Visit all the nodes. As we iterate, move nodes into sorted order, 10266 // such that by the time the end is reached all nodes will be sorted. 10267 for (SDNode &Node : allnodes()) { 10268 SDNode *N = &Node; 10269 checkForCycles(N, this); 10270 // N is in sorted position, so all its uses have one less operand 10271 // that needs to be sorted. 10272 for (SDNode *P : N->uses()) { 10273 unsigned Degree = P->getNodeId(); 10274 assert(Degree != 0 && "Invalid node degree"); 10275 --Degree; 10276 if (Degree == 0) { 10277 // All of P's operands are sorted, so P may sorted now. 10278 P->setNodeId(DAGSize++); 10279 if (P->getIterator() != SortedPos) 10280 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 10281 assert(SortedPos != AllNodes.end() && "Overran node list"); 10282 ++SortedPos; 10283 } else { 10284 // Update P's outstanding operand count. 10285 P->setNodeId(Degree); 10286 } 10287 } 10288 if (Node.getIterator() == SortedPos) { 10289 #ifndef NDEBUG 10290 allnodes_iterator I(N); 10291 SDNode *S = &*++I; 10292 dbgs() << "Overran sorted position:\n"; 10293 S->dumprFull(this); dbgs() << "\n"; 10294 dbgs() << "Checking if this is due to cycles\n"; 10295 checkForCycles(this, true); 10296 #endif 10297 llvm_unreachable(nullptr); 10298 } 10299 } 10300 10301 assert(SortedPos == AllNodes.end() && 10302 "Topological sort incomplete!"); 10303 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 10304 "First node in topological sort is not the entry token!"); 10305 assert(AllNodes.front().getNodeId() == 0 && 10306 "First node in topological sort has non-zero id!"); 10307 assert(AllNodes.front().getNumOperands() == 0 && 10308 "First node in topological sort has operands!"); 10309 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 10310 "Last node in topologic sort has unexpected id!"); 10311 assert(AllNodes.back().use_empty() && 10312 "Last node in topologic sort has users!"); 10313 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 10314 return DAGSize; 10315 } 10316 10317 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 10318 /// value is produced by SD. 10319 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 10320 for (SDNode *SD : DB->getSDNodes()) { 10321 if (!SD) 10322 continue; 10323 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 10324 SD->setHasDebugValue(true); 10325 } 10326 DbgInfo->add(DB, isParameter); 10327 } 10328 10329 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 10330 10331 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 10332 SDValue NewMemOpChain) { 10333 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 10334 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 10335 // The new memory operation must have the same position as the old load in 10336 // terms of memory dependency. Create a TokenFactor for the old load and new 10337 // memory operation and update uses of the old load's output chain to use that 10338 // TokenFactor. 10339 if (OldChain == NewMemOpChain || OldChain.use_empty()) 10340 return NewMemOpChain; 10341 10342 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 10343 OldChain, NewMemOpChain); 10344 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 10345 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 10346 return TokenFactor; 10347 } 10348 10349 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 10350 SDValue NewMemOp) { 10351 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 10352 SDValue OldChain = SDValue(OldLoad, 1); 10353 SDValue NewMemOpChain = NewMemOp.getValue(1); 10354 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 10355 } 10356 10357 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 10358 Function **OutFunction) { 10359 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 10360 10361 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 10362 auto *Module = MF->getFunction().getParent(); 10363 auto *Function = Module->getFunction(Symbol); 10364 10365 if (OutFunction != nullptr) 10366 *OutFunction = Function; 10367 10368 if (Function != nullptr) { 10369 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 10370 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 10371 } 10372 10373 std::string ErrorStr; 10374 raw_string_ostream ErrorFormatter(ErrorStr); 10375 ErrorFormatter << "Undefined external symbol "; 10376 ErrorFormatter << '"' << Symbol << '"'; 10377 report_fatal_error(Twine(ErrorFormatter.str())); 10378 } 10379 10380 //===----------------------------------------------------------------------===// 10381 // SDNode Class 10382 //===----------------------------------------------------------------------===// 10383 10384 bool llvm::isNullConstant(SDValue V) { 10385 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10386 return Const != nullptr && Const->isZero(); 10387 } 10388 10389 bool llvm::isNullFPConstant(SDValue V) { 10390 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10391 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10392 } 10393 10394 bool llvm::isAllOnesConstant(SDValue V) { 10395 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10396 return Const != nullptr && Const->isAllOnes(); 10397 } 10398 10399 bool llvm::isOneConstant(SDValue V) { 10400 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10401 return Const != nullptr && Const->isOne(); 10402 } 10403 10404 bool llvm::isMinSignedConstant(SDValue V) { 10405 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10406 return Const != nullptr && Const->isMinSignedValue(); 10407 } 10408 10409 SDValue llvm::peekThroughBitcasts(SDValue V) { 10410 while (V.getOpcode() == ISD::BITCAST) 10411 V = V.getOperand(0); 10412 return V; 10413 } 10414 10415 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10416 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10417 V = V.getOperand(0); 10418 return V; 10419 } 10420 10421 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10422 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10423 V = V.getOperand(0); 10424 return V; 10425 } 10426 10427 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10428 if (V.getOpcode() != ISD::XOR) 10429 return false; 10430 V = peekThroughBitcasts(V.getOperand(1)); 10431 unsigned NumBits = V.getScalarValueSizeInBits(); 10432 ConstantSDNode *C = 10433 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10434 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10435 } 10436 10437 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10438 bool AllowTruncation) { 10439 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10440 return CN; 10441 10442 // SplatVectors can truncate their operands. Ignore that case here unless 10443 // AllowTruncation is set. 10444 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10445 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10446 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10447 EVT CVT = CN->getValueType(0); 10448 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10449 if (AllowTruncation || CVT == VecEltVT) 10450 return CN; 10451 } 10452 } 10453 10454 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10455 BitVector UndefElements; 10456 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10457 10458 // BuildVectors can truncate their operands. Ignore that case here unless 10459 // AllowTruncation is set. 10460 if (CN && (UndefElements.none() || AllowUndefs)) { 10461 EVT CVT = CN->getValueType(0); 10462 EVT NSVT = N.getValueType().getScalarType(); 10463 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10464 if (AllowTruncation || (CVT == NSVT)) 10465 return CN; 10466 } 10467 } 10468 10469 return nullptr; 10470 } 10471 10472 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10473 bool AllowUndefs, 10474 bool AllowTruncation) { 10475 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10476 return CN; 10477 10478 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10479 BitVector UndefElements; 10480 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10481 10482 // BuildVectors can truncate their operands. Ignore that case here unless 10483 // AllowTruncation is set. 10484 if (CN && (UndefElements.none() || AllowUndefs)) { 10485 EVT CVT = CN->getValueType(0); 10486 EVT NSVT = N.getValueType().getScalarType(); 10487 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10488 if (AllowTruncation || (CVT == NSVT)) 10489 return CN; 10490 } 10491 } 10492 10493 return nullptr; 10494 } 10495 10496 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10497 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10498 return CN; 10499 10500 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10501 BitVector UndefElements; 10502 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10503 if (CN && (UndefElements.none() || AllowUndefs)) 10504 return CN; 10505 } 10506 10507 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10508 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10509 return CN; 10510 10511 return nullptr; 10512 } 10513 10514 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10515 const APInt &DemandedElts, 10516 bool AllowUndefs) { 10517 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10518 return CN; 10519 10520 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10521 BitVector UndefElements; 10522 ConstantFPSDNode *CN = 10523 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10524 if (CN && (UndefElements.none() || AllowUndefs)) 10525 return CN; 10526 } 10527 10528 return nullptr; 10529 } 10530 10531 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10532 // TODO: may want to use peekThroughBitcast() here. 10533 ConstantSDNode *C = 10534 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10535 return C && C->isZero(); 10536 } 10537 10538 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10539 // TODO: may want to use peekThroughBitcast() here. 10540 unsigned BitWidth = N.getScalarValueSizeInBits(); 10541 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10542 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10543 } 10544 10545 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10546 N = peekThroughBitcasts(N); 10547 unsigned BitWidth = N.getScalarValueSizeInBits(); 10548 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10549 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10550 } 10551 10552 HandleSDNode::~HandleSDNode() { 10553 DropOperands(); 10554 } 10555 10556 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10557 const DebugLoc &DL, 10558 const GlobalValue *GA, EVT VT, 10559 int64_t o, unsigned TF) 10560 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10561 TheGlobal = GA; 10562 } 10563 10564 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10565 EVT VT, unsigned SrcAS, 10566 unsigned DestAS) 10567 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10568 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10569 10570 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10571 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10572 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10573 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10574 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10575 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10576 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10577 10578 // We check here that the size of the memory operand fits within the size of 10579 // the MMO. This is because the MMO might indicate only a possible address 10580 // range instead of specifying the affected memory addresses precisely. 10581 // TODO: Make MachineMemOperands aware of scalable vectors. 10582 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10583 "Size mismatch!"); 10584 } 10585 10586 /// Profile - Gather unique data for the node. 10587 /// 10588 void SDNode::Profile(FoldingSetNodeID &ID) const { 10589 AddNodeIDNode(ID, this); 10590 } 10591 10592 namespace { 10593 10594 struct EVTArray { 10595 std::vector<EVT> VTs; 10596 10597 EVTArray() { 10598 VTs.reserve(MVT::VALUETYPE_SIZE); 10599 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10600 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10601 } 10602 }; 10603 10604 } // end anonymous namespace 10605 10606 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10607 static ManagedStatic<EVTArray> SimpleVTArray; 10608 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10609 10610 /// getValueTypeList - Return a pointer to the specified value type. 10611 /// 10612 const EVT *SDNode::getValueTypeList(EVT VT) { 10613 if (VT.isExtended()) { 10614 sys::SmartScopedLock<true> Lock(*VTMutex); 10615 return &(*EVTs->insert(VT).first); 10616 } 10617 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10618 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10619 } 10620 10621 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10622 /// indicated value. This method ignores uses of other values defined by this 10623 /// operation. 10624 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10625 assert(Value < getNumValues() && "Bad value!"); 10626 10627 // TODO: Only iterate over uses of a given value of the node 10628 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10629 if (UI.getUse().getResNo() == Value) { 10630 if (NUses == 0) 10631 return false; 10632 --NUses; 10633 } 10634 } 10635 10636 // Found exactly the right number of uses? 10637 return NUses == 0; 10638 } 10639 10640 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10641 /// value. This method ignores uses of other values defined by this operation. 10642 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10643 assert(Value < getNumValues() && "Bad value!"); 10644 10645 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10646 if (UI.getUse().getResNo() == Value) 10647 return true; 10648 10649 return false; 10650 } 10651 10652 /// isOnlyUserOf - Return true if this node is the only use of N. 10653 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10654 bool Seen = false; 10655 for (const SDNode *User : N->uses()) { 10656 if (User == this) 10657 Seen = true; 10658 else 10659 return false; 10660 } 10661 10662 return Seen; 10663 } 10664 10665 /// Return true if the only users of N are contained in Nodes. 10666 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10667 bool Seen = false; 10668 for (const SDNode *User : N->uses()) { 10669 if (llvm::is_contained(Nodes, User)) 10670 Seen = true; 10671 else 10672 return false; 10673 } 10674 10675 return Seen; 10676 } 10677 10678 /// isOperand - Return true if this node is an operand of N. 10679 bool SDValue::isOperandOf(const SDNode *N) const { 10680 return is_contained(N->op_values(), *this); 10681 } 10682 10683 bool SDNode::isOperandOf(const SDNode *N) const { 10684 return any_of(N->op_values(), 10685 [this](SDValue Op) { return this == Op.getNode(); }); 10686 } 10687 10688 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10689 /// be a chain) reaches the specified operand without crossing any 10690 /// side-effecting instructions on any chain path. In practice, this looks 10691 /// through token factors and non-volatile loads. In order to remain efficient, 10692 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10693 /// 10694 /// Note that we only need to examine chains when we're searching for 10695 /// side-effects; SelectionDAG requires that all side-effects are represented 10696 /// by chains, even if another operand would force a specific ordering. This 10697 /// constraint is necessary to allow transformations like splitting loads. 10698 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10699 unsigned Depth) const { 10700 if (*this == Dest) return true; 10701 10702 // Don't search too deeply, we just want to be able to see through 10703 // TokenFactor's etc. 10704 if (Depth == 0) return false; 10705 10706 // If this is a token factor, all inputs to the TF happen in parallel. 10707 if (getOpcode() == ISD::TokenFactor) { 10708 // First, try a shallow search. 10709 if (is_contained((*this)->ops(), Dest)) { 10710 // We found the chain we want as an operand of this TokenFactor. 10711 // Essentially, we reach the chain without side-effects if we could 10712 // serialize the TokenFactor into a simple chain of operations with 10713 // Dest as the last operation. This is automatically true if the 10714 // chain has one use: there are no other ordering constraints. 10715 // If the chain has more than one use, we give up: some other 10716 // use of Dest might force a side-effect between Dest and the current 10717 // node. 10718 if (Dest.hasOneUse()) 10719 return true; 10720 } 10721 // Next, try a deep search: check whether every operand of the TokenFactor 10722 // reaches Dest. 10723 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10724 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10725 }); 10726 } 10727 10728 // Loads don't have side effects, look through them. 10729 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10730 if (Ld->isUnordered()) 10731 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10732 } 10733 return false; 10734 } 10735 10736 bool SDNode::hasPredecessor(const SDNode *N) const { 10737 SmallPtrSet<const SDNode *, 32> Visited; 10738 SmallVector<const SDNode *, 16> Worklist; 10739 Worklist.push_back(this); 10740 return hasPredecessorHelper(N, Visited, Worklist); 10741 } 10742 10743 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10744 this->Flags.intersectWith(Flags); 10745 } 10746 10747 SDValue 10748 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10749 ArrayRef<ISD::NodeType> CandidateBinOps, 10750 bool AllowPartials) { 10751 // The pattern must end in an extract from index 0. 10752 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10753 !isNullConstant(Extract->getOperand(1))) 10754 return SDValue(); 10755 10756 // Match against one of the candidate binary ops. 10757 SDValue Op = Extract->getOperand(0); 10758 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10759 return Op.getOpcode() == unsigned(BinOp); 10760 })) 10761 return SDValue(); 10762 10763 // Floating-point reductions may require relaxed constraints on the final step 10764 // of the reduction because they may reorder intermediate operations. 10765 unsigned CandidateBinOp = Op.getOpcode(); 10766 if (Op.getValueType().isFloatingPoint()) { 10767 SDNodeFlags Flags = Op->getFlags(); 10768 switch (CandidateBinOp) { 10769 case ISD::FADD: 10770 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10771 return SDValue(); 10772 break; 10773 default: 10774 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10775 } 10776 } 10777 10778 // Matching failed - attempt to see if we did enough stages that a partial 10779 // reduction from a subvector is possible. 10780 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10781 if (!AllowPartials || !Op) 10782 return SDValue(); 10783 EVT OpVT = Op.getValueType(); 10784 EVT OpSVT = OpVT.getScalarType(); 10785 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10786 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10787 return SDValue(); 10788 BinOp = (ISD::NodeType)CandidateBinOp; 10789 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10790 getVectorIdxConstant(0, SDLoc(Op))); 10791 }; 10792 10793 // At each stage, we're looking for something that looks like: 10794 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10795 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10796 // i32 undef, i32 undef, i32 undef, i32 undef> 10797 // %a = binop <8 x i32> %op, %s 10798 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10799 // we expect something like: 10800 // <4,5,6,7,u,u,u,u> 10801 // <2,3,u,u,u,u,u,u> 10802 // <1,u,u,u,u,u,u,u> 10803 // While a partial reduction match would be: 10804 // <2,3,u,u,u,u,u,u> 10805 // <1,u,u,u,u,u,u,u> 10806 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10807 SDValue PrevOp; 10808 for (unsigned i = 0; i < Stages; ++i) { 10809 unsigned MaskEnd = (1 << i); 10810 10811 if (Op.getOpcode() != CandidateBinOp) 10812 return PartialReduction(PrevOp, MaskEnd); 10813 10814 SDValue Op0 = Op.getOperand(0); 10815 SDValue Op1 = Op.getOperand(1); 10816 10817 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10818 if (Shuffle) { 10819 Op = Op1; 10820 } else { 10821 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10822 Op = Op0; 10823 } 10824 10825 // The first operand of the shuffle should be the same as the other operand 10826 // of the binop. 10827 if (!Shuffle || Shuffle->getOperand(0) != Op) 10828 return PartialReduction(PrevOp, MaskEnd); 10829 10830 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10831 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10832 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10833 return PartialReduction(PrevOp, MaskEnd); 10834 10835 PrevOp = Op; 10836 } 10837 10838 // Handle subvector reductions, which tend to appear after the shuffle 10839 // reduction stages. 10840 while (Op.getOpcode() == CandidateBinOp) { 10841 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10842 SDValue Op0 = Op.getOperand(0); 10843 SDValue Op1 = Op.getOperand(1); 10844 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10845 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10846 Op0.getOperand(0) != Op1.getOperand(0)) 10847 break; 10848 SDValue Src = Op0.getOperand(0); 10849 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10850 if (NumSrcElts != (2 * NumElts)) 10851 break; 10852 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10853 Op1.getConstantOperandAPInt(1) == NumElts) && 10854 !(Op1.getConstantOperandAPInt(1) == 0 && 10855 Op0.getConstantOperandAPInt(1) == NumElts)) 10856 break; 10857 Op = Src; 10858 } 10859 10860 BinOp = (ISD::NodeType)CandidateBinOp; 10861 return Op; 10862 } 10863 10864 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10865 assert(N->getNumValues() == 1 && 10866 "Can't unroll a vector with multiple results!"); 10867 10868 EVT VT = N->getValueType(0); 10869 unsigned NE = VT.getVectorNumElements(); 10870 EVT EltVT = VT.getVectorElementType(); 10871 SDLoc dl(N); 10872 10873 SmallVector<SDValue, 8> Scalars; 10874 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10875 10876 // If ResNE is 0, fully unroll the vector op. 10877 if (ResNE == 0) 10878 ResNE = NE; 10879 else if (NE > ResNE) 10880 NE = ResNE; 10881 10882 unsigned i; 10883 for (i= 0; i != NE; ++i) { 10884 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10885 SDValue Operand = N->getOperand(j); 10886 EVT OperandVT = Operand.getValueType(); 10887 if (OperandVT.isVector()) { 10888 // A vector operand; extract a single element. 10889 EVT OperandEltVT = OperandVT.getVectorElementType(); 10890 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10891 Operand, getVectorIdxConstant(i, dl)); 10892 } else { 10893 // A scalar operand; just use it as is. 10894 Operands[j] = Operand; 10895 } 10896 } 10897 10898 switch (N->getOpcode()) { 10899 default: { 10900 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10901 N->getFlags())); 10902 break; 10903 } 10904 case ISD::VSELECT: 10905 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10906 break; 10907 case ISD::SHL: 10908 case ISD::SRA: 10909 case ISD::SRL: 10910 case ISD::ROTL: 10911 case ISD::ROTR: 10912 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10913 getShiftAmountOperand(Operands[0].getValueType(), 10914 Operands[1]))); 10915 break; 10916 case ISD::SIGN_EXTEND_INREG: { 10917 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10918 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10919 Operands[0], 10920 getValueType(ExtVT))); 10921 } 10922 } 10923 } 10924 10925 for (; i < ResNE; ++i) 10926 Scalars.push_back(getUNDEF(EltVT)); 10927 10928 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10929 return getBuildVector(VecVT, dl, Scalars); 10930 } 10931 10932 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10933 SDNode *N, unsigned ResNE) { 10934 unsigned Opcode = N->getOpcode(); 10935 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10936 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10937 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10938 "Expected an overflow opcode"); 10939 10940 EVT ResVT = N->getValueType(0); 10941 EVT OvVT = N->getValueType(1); 10942 EVT ResEltVT = ResVT.getVectorElementType(); 10943 EVT OvEltVT = OvVT.getVectorElementType(); 10944 SDLoc dl(N); 10945 10946 // If ResNE is 0, fully unroll the vector op. 10947 unsigned NE = ResVT.getVectorNumElements(); 10948 if (ResNE == 0) 10949 ResNE = NE; 10950 else if (NE > ResNE) 10951 NE = ResNE; 10952 10953 SmallVector<SDValue, 8> LHSScalars; 10954 SmallVector<SDValue, 8> RHSScalars; 10955 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10956 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10957 10958 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10959 SDVTList VTs = getVTList(ResEltVT, SVT); 10960 SmallVector<SDValue, 8> ResScalars; 10961 SmallVector<SDValue, 8> OvScalars; 10962 for (unsigned i = 0; i < NE; ++i) { 10963 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10964 SDValue Ov = 10965 getSelect(dl, OvEltVT, Res.getValue(1), 10966 getBoolConstant(true, dl, OvEltVT, ResVT), 10967 getConstant(0, dl, OvEltVT)); 10968 10969 ResScalars.push_back(Res); 10970 OvScalars.push_back(Ov); 10971 } 10972 10973 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10974 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10975 10976 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10977 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10978 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10979 getBuildVector(NewOvVT, dl, OvScalars)); 10980 } 10981 10982 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10983 LoadSDNode *Base, 10984 unsigned Bytes, 10985 int Dist) const { 10986 if (LD->isVolatile() || Base->isVolatile()) 10987 return false; 10988 // TODO: probably too restrictive for atomics, revisit 10989 if (!LD->isSimple()) 10990 return false; 10991 if (LD->isIndexed() || Base->isIndexed()) 10992 return false; 10993 if (LD->getChain() != Base->getChain()) 10994 return false; 10995 EVT VT = LD->getValueType(0); 10996 if (VT.getSizeInBits() / 8 != Bytes) 10997 return false; 10998 10999 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 11000 auto LocDecomp = BaseIndexOffset::match(LD, *this); 11001 11002 int64_t Offset = 0; 11003 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 11004 return (Dist * Bytes == Offset); 11005 return false; 11006 } 11007 11008 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 11009 /// if it cannot be inferred. 11010 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 11011 // If this is a GlobalAddress + cst, return the alignment. 11012 const GlobalValue *GV = nullptr; 11013 int64_t GVOffset = 0; 11014 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 11015 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 11016 KnownBits Known(PtrWidth); 11017 llvm::computeKnownBits(GV, Known, getDataLayout()); 11018 unsigned AlignBits = Known.countMinTrailingZeros(); 11019 if (AlignBits) 11020 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11021 } 11022 11023 // If this is a direct reference to a stack slot, use information about the 11024 // stack slot's alignment. 11025 int FrameIdx = INT_MIN; 11026 int64_t FrameOffset = 0; 11027 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11028 FrameIdx = FI->getIndex(); 11029 } else if (isBaseWithConstantOffset(Ptr) && 11030 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11031 // Handle FI+Cst 11032 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11033 FrameOffset = Ptr.getConstantOperandVal(1); 11034 } 11035 11036 if (FrameIdx != INT_MIN) { 11037 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11038 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11039 } 11040 11041 return None; 11042 } 11043 11044 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11045 /// which is split (or expanded) into two not necessarily identical pieces. 11046 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11047 // Currently all types are split in half. 11048 EVT LoVT, HiVT; 11049 if (!VT.isVector()) 11050 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11051 else 11052 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11053 11054 return std::make_pair(LoVT, HiVT); 11055 } 11056 11057 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11058 /// type, dependent on an enveloping VT that has been split into two identical 11059 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11060 std::pair<EVT, EVT> 11061 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11062 bool *HiIsEmpty) const { 11063 EVT EltTp = VT.getVectorElementType(); 11064 // Examples: 11065 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11066 // custom VL=9 with enveloping VL=8/8 yields 8/1 11067 // custom VL=10 with enveloping VL=8/8 yields 8/2 11068 // etc. 11069 ElementCount VTNumElts = VT.getVectorElementCount(); 11070 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11071 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11072 "Mixing fixed width and scalable vectors when enveloping a type"); 11073 EVT LoVT, HiVT; 11074 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11075 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11076 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11077 *HiIsEmpty = false; 11078 } else { 11079 // Flag that hi type has zero storage size, but return split envelop type 11080 // (this would be easier if vector types with zero elements were allowed). 11081 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11082 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11083 *HiIsEmpty = true; 11084 } 11085 return std::make_pair(LoVT, HiVT); 11086 } 11087 11088 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11089 /// low/high part. 11090 std::pair<SDValue, SDValue> 11091 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11092 const EVT &HiVT) { 11093 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 11094 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 11095 "Splitting vector with an invalid mixture of fixed and scalable " 11096 "vector types"); 11097 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 11098 N.getValueType().getVectorMinNumElements() && 11099 "More vector elements requested than available!"); 11100 SDValue Lo, Hi; 11101 Lo = 11102 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 11103 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 11104 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 11105 // IDX with the runtime scaling factor of the result vector type. For 11106 // fixed-width result vectors, that runtime scaling factor is 1. 11107 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 11108 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 11109 return std::make_pair(Lo, Hi); 11110 } 11111 11112 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 11113 const SDLoc &DL) { 11114 // Split the vector length parameter. 11115 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 11116 EVT VT = N.getValueType(); 11117 assert(VecVT.getVectorElementCount().isKnownEven() && 11118 "Expecting the mask to be an evenly-sized vector"); 11119 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 11120 SDValue HalfNumElts = 11121 VecVT.isFixedLengthVector() 11122 ? getConstant(HalfMinNumElts, DL, VT) 11123 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 11124 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 11125 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 11126 return std::make_pair(Lo, Hi); 11127 } 11128 11129 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 11130 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 11131 EVT VT = N.getValueType(); 11132 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 11133 NextPowerOf2(VT.getVectorNumElements())); 11134 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 11135 getVectorIdxConstant(0, DL)); 11136 } 11137 11138 void SelectionDAG::ExtractVectorElements(SDValue Op, 11139 SmallVectorImpl<SDValue> &Args, 11140 unsigned Start, unsigned Count, 11141 EVT EltVT) { 11142 EVT VT = Op.getValueType(); 11143 if (Count == 0) 11144 Count = VT.getVectorNumElements(); 11145 if (EltVT == EVT()) 11146 EltVT = VT.getVectorElementType(); 11147 SDLoc SL(Op); 11148 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 11149 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 11150 getVectorIdxConstant(i, SL))); 11151 } 11152 } 11153 11154 // getAddressSpace - Return the address space this GlobalAddress belongs to. 11155 unsigned GlobalAddressSDNode::getAddressSpace() const { 11156 return getGlobal()->getType()->getAddressSpace(); 11157 } 11158 11159 Type *ConstantPoolSDNode::getType() const { 11160 if (isMachineConstantPoolEntry()) 11161 return Val.MachineCPVal->getType(); 11162 return Val.ConstVal->getType(); 11163 } 11164 11165 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 11166 unsigned &SplatBitSize, 11167 bool &HasAnyUndefs, 11168 unsigned MinSplatBits, 11169 bool IsBigEndian) const { 11170 EVT VT = getValueType(0); 11171 assert(VT.isVector() && "Expected a vector type"); 11172 unsigned VecWidth = VT.getSizeInBits(); 11173 if (MinSplatBits > VecWidth) 11174 return false; 11175 11176 // FIXME: The widths are based on this node's type, but build vectors can 11177 // truncate their operands. 11178 SplatValue = APInt(VecWidth, 0); 11179 SplatUndef = APInt(VecWidth, 0); 11180 11181 // Get the bits. Bits with undefined values (when the corresponding element 11182 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 11183 // in SplatValue. If any of the values are not constant, give up and return 11184 // false. 11185 unsigned int NumOps = getNumOperands(); 11186 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 11187 unsigned EltWidth = VT.getScalarSizeInBits(); 11188 11189 for (unsigned j = 0; j < NumOps; ++j) { 11190 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 11191 SDValue OpVal = getOperand(i); 11192 unsigned BitPos = j * EltWidth; 11193 11194 if (OpVal.isUndef()) 11195 SplatUndef.setBits(BitPos, BitPos + EltWidth); 11196 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 11197 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 11198 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 11199 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 11200 else 11201 return false; 11202 } 11203 11204 // The build_vector is all constants or undefs. Find the smallest element 11205 // size that splats the vector. 11206 HasAnyUndefs = (SplatUndef != 0); 11207 11208 // FIXME: This does not work for vectors with elements less than 8 bits. 11209 while (VecWidth > 8) { 11210 unsigned HalfSize = VecWidth / 2; 11211 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 11212 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 11213 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 11214 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 11215 11216 // If the two halves do not match (ignoring undef bits), stop here. 11217 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 11218 MinSplatBits > HalfSize) 11219 break; 11220 11221 SplatValue = HighValue | LowValue; 11222 SplatUndef = HighUndef & LowUndef; 11223 11224 VecWidth = HalfSize; 11225 } 11226 11227 SplatBitSize = VecWidth; 11228 return true; 11229 } 11230 11231 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 11232 BitVector *UndefElements) const { 11233 unsigned NumOps = getNumOperands(); 11234 if (UndefElements) { 11235 UndefElements->clear(); 11236 UndefElements->resize(NumOps); 11237 } 11238 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11239 if (!DemandedElts) 11240 return SDValue(); 11241 SDValue Splatted; 11242 for (unsigned i = 0; i != NumOps; ++i) { 11243 if (!DemandedElts[i]) 11244 continue; 11245 SDValue Op = getOperand(i); 11246 if (Op.isUndef()) { 11247 if (UndefElements) 11248 (*UndefElements)[i] = true; 11249 } else if (!Splatted) { 11250 Splatted = Op; 11251 } else if (Splatted != Op) { 11252 return SDValue(); 11253 } 11254 } 11255 11256 if (!Splatted) { 11257 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 11258 assert(getOperand(FirstDemandedIdx).isUndef() && 11259 "Can only have a splat without a constant for all undefs."); 11260 return getOperand(FirstDemandedIdx); 11261 } 11262 11263 return Splatted; 11264 } 11265 11266 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 11267 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11268 return getSplatValue(DemandedElts, UndefElements); 11269 } 11270 11271 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 11272 SmallVectorImpl<SDValue> &Sequence, 11273 BitVector *UndefElements) const { 11274 unsigned NumOps = getNumOperands(); 11275 Sequence.clear(); 11276 if (UndefElements) { 11277 UndefElements->clear(); 11278 UndefElements->resize(NumOps); 11279 } 11280 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11281 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 11282 return false; 11283 11284 // Set the undefs even if we don't find a sequence (like getSplatValue). 11285 if (UndefElements) 11286 for (unsigned I = 0; I != NumOps; ++I) 11287 if (DemandedElts[I] && getOperand(I).isUndef()) 11288 (*UndefElements)[I] = true; 11289 11290 // Iteratively widen the sequence length looking for repetitions. 11291 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 11292 Sequence.append(SeqLen, SDValue()); 11293 for (unsigned I = 0; I != NumOps; ++I) { 11294 if (!DemandedElts[I]) 11295 continue; 11296 SDValue &SeqOp = Sequence[I % SeqLen]; 11297 SDValue Op = getOperand(I); 11298 if (Op.isUndef()) { 11299 if (!SeqOp) 11300 SeqOp = Op; 11301 continue; 11302 } 11303 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 11304 Sequence.clear(); 11305 break; 11306 } 11307 SeqOp = Op; 11308 } 11309 if (!Sequence.empty()) 11310 return true; 11311 } 11312 11313 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 11314 return false; 11315 } 11316 11317 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 11318 BitVector *UndefElements) const { 11319 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11320 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 11321 } 11322 11323 ConstantSDNode * 11324 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 11325 BitVector *UndefElements) const { 11326 return dyn_cast_or_null<ConstantSDNode>( 11327 getSplatValue(DemandedElts, UndefElements)); 11328 } 11329 11330 ConstantSDNode * 11331 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 11332 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 11333 } 11334 11335 ConstantFPSDNode * 11336 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 11337 BitVector *UndefElements) const { 11338 return dyn_cast_or_null<ConstantFPSDNode>( 11339 getSplatValue(DemandedElts, UndefElements)); 11340 } 11341 11342 ConstantFPSDNode * 11343 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 11344 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 11345 } 11346 11347 int32_t 11348 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 11349 uint32_t BitWidth) const { 11350 if (ConstantFPSDNode *CN = 11351 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 11352 bool IsExact; 11353 APSInt IntVal(BitWidth); 11354 const APFloat &APF = CN->getValueAPF(); 11355 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 11356 APFloat::opOK || 11357 !IsExact) 11358 return -1; 11359 11360 return IntVal.exactLogBase2(); 11361 } 11362 return -1; 11363 } 11364 11365 bool BuildVectorSDNode::getConstantRawBits( 11366 bool IsLittleEndian, unsigned DstEltSizeInBits, 11367 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 11368 // Early-out if this contains anything but Undef/Constant/ConstantFP. 11369 if (!isConstant()) 11370 return false; 11371 11372 unsigned NumSrcOps = getNumOperands(); 11373 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 11374 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11375 "Invalid bitcast scale"); 11376 11377 // Extract raw src bits. 11378 SmallVector<APInt> SrcBitElements(NumSrcOps, 11379 APInt::getNullValue(SrcEltSizeInBits)); 11380 BitVector SrcUndeElements(NumSrcOps, false); 11381 11382 for (unsigned I = 0; I != NumSrcOps; ++I) { 11383 SDValue Op = getOperand(I); 11384 if (Op.isUndef()) { 11385 SrcUndeElements.set(I); 11386 continue; 11387 } 11388 auto *CInt = dyn_cast<ConstantSDNode>(Op); 11389 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 11390 assert((CInt || CFP) && "Unknown constant"); 11391 SrcBitElements[I] = 11392 CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits) 11393 : CFP->getValueAPF().bitcastToAPInt(); 11394 } 11395 11396 // Recast to dst width. 11397 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11398 SrcBitElements, UndefElements, SrcUndeElements); 11399 return true; 11400 } 11401 11402 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11403 unsigned DstEltSizeInBits, 11404 SmallVectorImpl<APInt> &DstBitElements, 11405 ArrayRef<APInt> SrcBitElements, 11406 BitVector &DstUndefElements, 11407 const BitVector &SrcUndefElements) { 11408 unsigned NumSrcOps = SrcBitElements.size(); 11409 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11410 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11411 "Invalid bitcast scale"); 11412 assert(NumSrcOps == SrcUndefElements.size() && 11413 "Vector size mismatch"); 11414 11415 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11416 DstUndefElements.clear(); 11417 DstUndefElements.resize(NumDstOps, false); 11418 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11419 11420 // Concatenate src elements constant bits together into dst element. 11421 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11422 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11423 for (unsigned I = 0; I != NumDstOps; ++I) { 11424 DstUndefElements.set(I); 11425 APInt &DstBits = DstBitElements[I]; 11426 for (unsigned J = 0; J != Scale; ++J) { 11427 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11428 if (SrcUndefElements[Idx]) 11429 continue; 11430 DstUndefElements.reset(I); 11431 const APInt &SrcBits = SrcBitElements[Idx]; 11432 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11433 "Illegal constant bitwidths"); 11434 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11435 } 11436 } 11437 return; 11438 } 11439 11440 // Split src element constant bits into dst elements. 11441 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11442 for (unsigned I = 0; I != NumSrcOps; ++I) { 11443 if (SrcUndefElements[I]) { 11444 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11445 continue; 11446 } 11447 const APInt &SrcBits = SrcBitElements[I]; 11448 for (unsigned J = 0; J != Scale; ++J) { 11449 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11450 APInt &DstBits = DstBitElements[Idx]; 11451 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11452 } 11453 } 11454 } 11455 11456 bool BuildVectorSDNode::isConstant() const { 11457 for (const SDValue &Op : op_values()) { 11458 unsigned Opc = Op.getOpcode(); 11459 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11460 return false; 11461 } 11462 return true; 11463 } 11464 11465 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11466 // Find the first non-undef value in the shuffle mask. 11467 unsigned i, e; 11468 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11469 /* search */; 11470 11471 // If all elements are undefined, this shuffle can be considered a splat 11472 // (although it should eventually get simplified away completely). 11473 if (i == e) 11474 return true; 11475 11476 // Make sure all remaining elements are either undef or the same as the first 11477 // non-undef value. 11478 for (int Idx = Mask[i]; i != e; ++i) 11479 if (Mask[i] >= 0 && Mask[i] != Idx) 11480 return false; 11481 return true; 11482 } 11483 11484 // Returns the SDNode if it is a constant integer BuildVector 11485 // or constant integer. 11486 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11487 if (isa<ConstantSDNode>(N)) 11488 return N.getNode(); 11489 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11490 return N.getNode(); 11491 // Treat a GlobalAddress supporting constant offset folding as a 11492 // constant integer. 11493 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11494 if (GA->getOpcode() == ISD::GlobalAddress && 11495 TLI->isOffsetFoldingLegal(GA)) 11496 return GA; 11497 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11498 isa<ConstantSDNode>(N.getOperand(0))) 11499 return N.getNode(); 11500 return nullptr; 11501 } 11502 11503 // Returns the SDNode if it is a constant float BuildVector 11504 // or constant float. 11505 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11506 if (isa<ConstantFPSDNode>(N)) 11507 return N.getNode(); 11508 11509 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11510 return N.getNode(); 11511 11512 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11513 isa<ConstantFPSDNode>(N.getOperand(0))) 11514 return N.getNode(); 11515 11516 return nullptr; 11517 } 11518 11519 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11520 assert(!Node->OperandList && "Node already has operands"); 11521 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11522 "too many operands to fit into SDNode"); 11523 SDUse *Ops = OperandRecycler.allocate( 11524 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11525 11526 bool IsDivergent = false; 11527 for (unsigned I = 0; I != Vals.size(); ++I) { 11528 Ops[I].setUser(Node); 11529 Ops[I].setInitial(Vals[I]); 11530 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11531 IsDivergent |= Ops[I].getNode()->isDivergent(); 11532 } 11533 Node->NumOperands = Vals.size(); 11534 Node->OperandList = Ops; 11535 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11536 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11537 Node->SDNodeBits.IsDivergent = IsDivergent; 11538 } 11539 checkForCycles(Node); 11540 } 11541 11542 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11543 SmallVectorImpl<SDValue> &Vals) { 11544 size_t Limit = SDNode::getMaxNumOperands(); 11545 while (Vals.size() > Limit) { 11546 unsigned SliceIdx = Vals.size() - Limit; 11547 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11548 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11549 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11550 Vals.emplace_back(NewTF); 11551 } 11552 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11553 } 11554 11555 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11556 EVT VT, SDNodeFlags Flags) { 11557 switch (Opcode) { 11558 default: 11559 return SDValue(); 11560 case ISD::ADD: 11561 case ISD::OR: 11562 case ISD::XOR: 11563 case ISD::UMAX: 11564 return getConstant(0, DL, VT); 11565 case ISD::MUL: 11566 return getConstant(1, DL, VT); 11567 case ISD::AND: 11568 case ISD::UMIN: 11569 return getAllOnesConstant(DL, VT); 11570 case ISD::SMAX: 11571 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11572 case ISD::SMIN: 11573 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11574 case ISD::FADD: 11575 return getConstantFP(-0.0, DL, VT); 11576 case ISD::FMUL: 11577 return getConstantFP(1.0, DL, VT); 11578 case ISD::FMINNUM: 11579 case ISD::FMAXNUM: { 11580 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11581 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11582 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11583 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11584 APFloat::getLargest(Semantics); 11585 if (Opcode == ISD::FMAXNUM) 11586 NeutralAF.changeSign(); 11587 11588 return getConstantFP(NeutralAF, DL, VT); 11589 } 11590 } 11591 } 11592 11593 #ifndef NDEBUG 11594 static void checkForCyclesHelper(const SDNode *N, 11595 SmallPtrSetImpl<const SDNode*> &Visited, 11596 SmallPtrSetImpl<const SDNode*> &Checked, 11597 const llvm::SelectionDAG *DAG) { 11598 // If this node has already been checked, don't check it again. 11599 if (Checked.count(N)) 11600 return; 11601 11602 // If a node has already been visited on this depth-first walk, reject it as 11603 // a cycle. 11604 if (!Visited.insert(N).second) { 11605 errs() << "Detected cycle in SelectionDAG\n"; 11606 dbgs() << "Offending node:\n"; 11607 N->dumprFull(DAG); dbgs() << "\n"; 11608 abort(); 11609 } 11610 11611 for (const SDValue &Op : N->op_values()) 11612 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11613 11614 Checked.insert(N); 11615 Visited.erase(N); 11616 } 11617 #endif 11618 11619 void llvm::checkForCycles(const llvm::SDNode *N, 11620 const llvm::SelectionDAG *DAG, 11621 bool force) { 11622 #ifndef NDEBUG 11623 bool check = force; 11624 #ifdef EXPENSIVE_CHECKS 11625 check = true; 11626 #endif // EXPENSIVE_CHECKS 11627 if (check) { 11628 assert(N && "Checking nonexistent SDNode"); 11629 SmallPtrSet<const SDNode*, 32> visited; 11630 SmallPtrSet<const SDNode*, 32> checked; 11631 checkForCyclesHelper(N, visited, checked, DAG); 11632 } 11633 #endif // !NDEBUG 11634 } 11635 11636 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11637 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11638 } 11639