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 break; 5062 case ISD::TokenFactor: 5063 case ISD::MERGE_VALUES: 5064 case ISD::CONCAT_VECTORS: 5065 return Operand; // Factor, merge or concat of one node? No need. 5066 case ISD::BUILD_VECTOR: { 5067 // Attempt to simplify BUILD_VECTOR. 5068 SDValue Ops[] = {Operand}; 5069 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5070 return V; 5071 break; 5072 } 5073 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5074 case ISD::FP_EXTEND: 5075 assert(VT.isFloatingPoint() && 5076 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 5077 if (Operand.getValueType() == VT) return Operand; // noop conversion. 5078 assert((!VT.isVector() || 5079 VT.getVectorElementCount() == 5080 Operand.getValueType().getVectorElementCount()) && 5081 "Vector element count mismatch!"); 5082 assert(Operand.getValueType().bitsLT(VT) && 5083 "Invalid fpext node, dst < src!"); 5084 if (Operand.isUndef()) 5085 return getUNDEF(VT); 5086 break; 5087 case ISD::FP_TO_SINT: 5088 case ISD::FP_TO_UINT: 5089 if (Operand.isUndef()) 5090 return getUNDEF(VT); 5091 break; 5092 case ISD::SINT_TO_FP: 5093 case ISD::UINT_TO_FP: 5094 // [us]itofp(undef) = 0, because the result value is bounded. 5095 if (Operand.isUndef()) 5096 return getConstantFP(0.0, DL, VT); 5097 break; 5098 case ISD::SIGN_EXTEND: 5099 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5100 "Invalid SIGN_EXTEND!"); 5101 assert(VT.isVector() == Operand.getValueType().isVector() && 5102 "SIGN_EXTEND result type type should be vector iff the operand " 5103 "type is vector!"); 5104 if (Operand.getValueType() == VT) return Operand; // noop extension 5105 assert((!VT.isVector() || 5106 VT.getVectorElementCount() == 5107 Operand.getValueType().getVectorElementCount()) && 5108 "Vector element count mismatch!"); 5109 assert(Operand.getValueType().bitsLT(VT) && 5110 "Invalid sext node, dst < src!"); 5111 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5112 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5113 if (OpOpcode == ISD::UNDEF) 5114 // sext(undef) = 0, because the top bits will all be the same. 5115 return getConstant(0, DL, VT); 5116 break; 5117 case ISD::ZERO_EXTEND: 5118 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5119 "Invalid ZERO_EXTEND!"); 5120 assert(VT.isVector() == Operand.getValueType().isVector() && 5121 "ZERO_EXTEND result type type should be vector iff the operand " 5122 "type is vector!"); 5123 if (Operand.getValueType() == VT) return Operand; // noop extension 5124 assert((!VT.isVector() || 5125 VT.getVectorElementCount() == 5126 Operand.getValueType().getVectorElementCount()) && 5127 "Vector element count mismatch!"); 5128 assert(Operand.getValueType().bitsLT(VT) && 5129 "Invalid zext node, dst < src!"); 5130 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5131 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5132 if (OpOpcode == ISD::UNDEF) 5133 // zext(undef) = 0, because the top bits will be zero. 5134 return getConstant(0, DL, VT); 5135 break; 5136 case ISD::ANY_EXTEND: 5137 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5138 "Invalid ANY_EXTEND!"); 5139 assert(VT.isVector() == Operand.getValueType().isVector() && 5140 "ANY_EXTEND result type type should be vector iff the operand " 5141 "type is vector!"); 5142 if (Operand.getValueType() == VT) return Operand; // noop extension 5143 assert((!VT.isVector() || 5144 VT.getVectorElementCount() == 5145 Operand.getValueType().getVectorElementCount()) && 5146 "Vector element count mismatch!"); 5147 assert(Operand.getValueType().bitsLT(VT) && 5148 "Invalid anyext node, dst < src!"); 5149 5150 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5151 OpOpcode == ISD::ANY_EXTEND) 5152 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5153 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5154 if (OpOpcode == ISD::UNDEF) 5155 return getUNDEF(VT); 5156 5157 // (ext (trunc x)) -> x 5158 if (OpOpcode == ISD::TRUNCATE) { 5159 SDValue OpOp = Operand.getOperand(0); 5160 if (OpOp.getValueType() == VT) { 5161 transferDbgValues(Operand, OpOp); 5162 return OpOp; 5163 } 5164 } 5165 break; 5166 case ISD::TRUNCATE: 5167 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5168 "Invalid TRUNCATE!"); 5169 assert(VT.isVector() == Operand.getValueType().isVector() && 5170 "TRUNCATE result type type should be vector iff the operand " 5171 "type is vector!"); 5172 if (Operand.getValueType() == VT) return Operand; // noop truncate 5173 assert((!VT.isVector() || 5174 VT.getVectorElementCount() == 5175 Operand.getValueType().getVectorElementCount()) && 5176 "Vector element count mismatch!"); 5177 assert(Operand.getValueType().bitsGT(VT) && 5178 "Invalid truncate node, src < dst!"); 5179 if (OpOpcode == ISD::TRUNCATE) 5180 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5181 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5182 OpOpcode == ISD::ANY_EXTEND) { 5183 // If the source is smaller than the dest, we still need an extend. 5184 if (Operand.getOperand(0).getValueType().getScalarType() 5185 .bitsLT(VT.getScalarType())) 5186 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5187 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5188 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5189 return Operand.getOperand(0); 5190 } 5191 if (OpOpcode == ISD::UNDEF) 5192 return getUNDEF(VT); 5193 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5194 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5195 break; 5196 case ISD::ANY_EXTEND_VECTOR_INREG: 5197 case ISD::ZERO_EXTEND_VECTOR_INREG: 5198 case ISD::SIGN_EXTEND_VECTOR_INREG: 5199 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5200 assert(Operand.getValueType().bitsLE(VT) && 5201 "The input must be the same size or smaller than the result."); 5202 assert(VT.getVectorMinNumElements() < 5203 Operand.getValueType().getVectorMinNumElements() && 5204 "The destination vector type must have fewer lanes than the input."); 5205 break; 5206 case ISD::ABS: 5207 assert(VT.isInteger() && VT == Operand.getValueType() && 5208 "Invalid ABS!"); 5209 if (OpOpcode == ISD::UNDEF) 5210 return getUNDEF(VT); 5211 break; 5212 case ISD::BSWAP: 5213 assert(VT.isInteger() && VT == Operand.getValueType() && 5214 "Invalid BSWAP!"); 5215 assert((VT.getScalarSizeInBits() % 16 == 0) && 5216 "BSWAP types must be a multiple of 16 bits!"); 5217 if (OpOpcode == ISD::UNDEF) 5218 return getUNDEF(VT); 5219 // bswap(bswap(X)) -> X. 5220 if (OpOpcode == ISD::BSWAP) 5221 return Operand.getOperand(0); 5222 break; 5223 case ISD::BITREVERSE: 5224 assert(VT.isInteger() && VT == Operand.getValueType() && 5225 "Invalid BITREVERSE!"); 5226 if (OpOpcode == ISD::UNDEF) 5227 return getUNDEF(VT); 5228 break; 5229 case ISD::BITCAST: 5230 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5231 "Cannot BITCAST between types of different sizes!"); 5232 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5233 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5234 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5235 if (OpOpcode == ISD::UNDEF) 5236 return getUNDEF(VT); 5237 break; 5238 case ISD::SCALAR_TO_VECTOR: 5239 assert(VT.isVector() && !Operand.getValueType().isVector() && 5240 (VT.getVectorElementType() == Operand.getValueType() || 5241 (VT.getVectorElementType().isInteger() && 5242 Operand.getValueType().isInteger() && 5243 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5244 "Illegal SCALAR_TO_VECTOR node!"); 5245 if (OpOpcode == ISD::UNDEF) 5246 return getUNDEF(VT); 5247 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5248 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5249 isa<ConstantSDNode>(Operand.getOperand(1)) && 5250 Operand.getConstantOperandVal(1) == 0 && 5251 Operand.getOperand(0).getValueType() == VT) 5252 return Operand.getOperand(0); 5253 break; 5254 case ISD::FNEG: 5255 // Negation of an unknown bag of bits is still completely undefined. 5256 if (OpOpcode == ISD::UNDEF) 5257 return getUNDEF(VT); 5258 5259 if (OpOpcode == ISD::FNEG) // --X -> X 5260 return Operand.getOperand(0); 5261 break; 5262 case ISD::FABS: 5263 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5264 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5265 break; 5266 case ISD::VSCALE: 5267 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5268 break; 5269 case ISD::CTPOP: 5270 if (Operand.getValueType().getScalarType() == MVT::i1) 5271 return Operand; 5272 break; 5273 case ISD::CTLZ: 5274 case ISD::CTTZ: 5275 if (Operand.getValueType().getScalarType() == MVT::i1) 5276 return getNOT(DL, Operand, Operand.getValueType()); 5277 break; 5278 case ISD::VECREDUCE_SMIN: 5279 case ISD::VECREDUCE_UMAX: 5280 if (Operand.getValueType().getScalarType() == MVT::i1) 5281 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5282 break; 5283 case ISD::VECREDUCE_SMAX: 5284 case ISD::VECREDUCE_UMIN: 5285 if (Operand.getValueType().getScalarType() == MVT::i1) 5286 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5287 break; 5288 } 5289 5290 SDNode *N; 5291 SDVTList VTs = getVTList(VT); 5292 SDValue Ops[] = {Operand}; 5293 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5294 FoldingSetNodeID ID; 5295 AddNodeIDNode(ID, Opcode, VTs, Ops); 5296 void *IP = nullptr; 5297 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5298 E->intersectFlagsWith(Flags); 5299 return SDValue(E, 0); 5300 } 5301 5302 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5303 N->setFlags(Flags); 5304 createOperands(N, Ops); 5305 CSEMap.InsertNode(N, IP); 5306 } else { 5307 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5308 createOperands(N, Ops); 5309 } 5310 5311 InsertNode(N); 5312 SDValue V = SDValue(N, 0); 5313 NewSDValueDbgMsg(V, "Creating new node: ", this); 5314 return V; 5315 } 5316 5317 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5318 const APInt &C2) { 5319 switch (Opcode) { 5320 case ISD::ADD: return C1 + C2; 5321 case ISD::SUB: return C1 - C2; 5322 case ISD::MUL: return C1 * C2; 5323 case ISD::AND: return C1 & C2; 5324 case ISD::OR: return C1 | C2; 5325 case ISD::XOR: return C1 ^ C2; 5326 case ISD::SHL: return C1 << C2; 5327 case ISD::SRL: return C1.lshr(C2); 5328 case ISD::SRA: return C1.ashr(C2); 5329 case ISD::ROTL: return C1.rotl(C2); 5330 case ISD::ROTR: return C1.rotr(C2); 5331 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5332 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5333 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5334 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5335 case ISD::SADDSAT: return C1.sadd_sat(C2); 5336 case ISD::UADDSAT: return C1.uadd_sat(C2); 5337 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5338 case ISD::USUBSAT: return C1.usub_sat(C2); 5339 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5340 case ISD::USHLSAT: return C1.ushl_sat(C2); 5341 case ISD::UDIV: 5342 if (!C2.getBoolValue()) 5343 break; 5344 return C1.udiv(C2); 5345 case ISD::UREM: 5346 if (!C2.getBoolValue()) 5347 break; 5348 return C1.urem(C2); 5349 case ISD::SDIV: 5350 if (!C2.getBoolValue()) 5351 break; 5352 return C1.sdiv(C2); 5353 case ISD::SREM: 5354 if (!C2.getBoolValue()) 5355 break; 5356 return C1.srem(C2); 5357 case ISD::MULHS: { 5358 unsigned FullWidth = C1.getBitWidth() * 2; 5359 APInt C1Ext = C1.sext(FullWidth); 5360 APInt C2Ext = C2.sext(FullWidth); 5361 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5362 } 5363 case ISD::MULHU: { 5364 unsigned FullWidth = C1.getBitWidth() * 2; 5365 APInt C1Ext = C1.zext(FullWidth); 5366 APInt C2Ext = C2.zext(FullWidth); 5367 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5368 } 5369 case ISD::AVGFLOORS: { 5370 unsigned FullWidth = C1.getBitWidth() + 1; 5371 APInt C1Ext = C1.sext(FullWidth); 5372 APInt C2Ext = C2.sext(FullWidth); 5373 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5374 } 5375 case ISD::AVGFLOORU: { 5376 unsigned FullWidth = C1.getBitWidth() + 1; 5377 APInt C1Ext = C1.zext(FullWidth); 5378 APInt C2Ext = C2.zext(FullWidth); 5379 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5380 } 5381 case ISD::AVGCEILS: { 5382 unsigned FullWidth = C1.getBitWidth() + 1; 5383 APInt C1Ext = C1.sext(FullWidth); 5384 APInt C2Ext = C2.sext(FullWidth); 5385 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5386 } 5387 case ISD::AVGCEILU: { 5388 unsigned FullWidth = C1.getBitWidth() + 1; 5389 APInt C1Ext = C1.zext(FullWidth); 5390 APInt C2Ext = C2.zext(FullWidth); 5391 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5392 } 5393 } 5394 return llvm::None; 5395 } 5396 5397 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5398 const GlobalAddressSDNode *GA, 5399 const SDNode *N2) { 5400 if (GA->getOpcode() != ISD::GlobalAddress) 5401 return SDValue(); 5402 if (!TLI->isOffsetFoldingLegal(GA)) 5403 return SDValue(); 5404 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5405 if (!C2) 5406 return SDValue(); 5407 int64_t Offset = C2->getSExtValue(); 5408 switch (Opcode) { 5409 case ISD::ADD: break; 5410 case ISD::SUB: Offset = -uint64_t(Offset); break; 5411 default: return SDValue(); 5412 } 5413 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5414 GA->getOffset() + uint64_t(Offset)); 5415 } 5416 5417 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5418 switch (Opcode) { 5419 case ISD::SDIV: 5420 case ISD::UDIV: 5421 case ISD::SREM: 5422 case ISD::UREM: { 5423 // If a divisor is zero/undef or any element of a divisor vector is 5424 // zero/undef, the whole op is undef. 5425 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5426 SDValue Divisor = Ops[1]; 5427 if (Divisor.isUndef() || isNullConstant(Divisor)) 5428 return true; 5429 5430 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5431 llvm::any_of(Divisor->op_values(), 5432 [](SDValue V) { return V.isUndef() || 5433 isNullConstant(V); }); 5434 // TODO: Handle signed overflow. 5435 } 5436 // TODO: Handle oversized shifts. 5437 default: 5438 return false; 5439 } 5440 } 5441 5442 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5443 EVT VT, ArrayRef<SDValue> Ops) { 5444 // If the opcode is a target-specific ISD node, there's nothing we can 5445 // do here and the operand rules may not line up with the below, so 5446 // bail early. 5447 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5448 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5449 // foldCONCAT_VECTORS in getNode before this is called. 5450 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5451 return SDValue(); 5452 5453 unsigned NumOps = Ops.size(); 5454 if (NumOps == 0) 5455 return SDValue(); 5456 5457 if (isUndef(Opcode, Ops)) 5458 return getUNDEF(VT); 5459 5460 // Handle binops special cases. 5461 if (NumOps == 2) { 5462 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5463 return CFP; 5464 5465 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5466 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5467 if (C1->isOpaque() || C2->isOpaque()) 5468 return SDValue(); 5469 5470 Optional<APInt> FoldAttempt = 5471 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5472 if (!FoldAttempt) 5473 return SDValue(); 5474 5475 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5476 assert((!Folded || !VT.isVector()) && 5477 "Can't fold vectors ops with scalar operands"); 5478 return Folded; 5479 } 5480 } 5481 5482 // fold (add Sym, c) -> Sym+c 5483 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5484 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5485 if (TLI->isCommutativeBinOp(Opcode)) 5486 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5487 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5488 } 5489 5490 // This is for vector folding only from here on. 5491 if (!VT.isVector()) 5492 return SDValue(); 5493 5494 ElementCount NumElts = VT.getVectorElementCount(); 5495 5496 // See if we can fold through bitcasted integer ops. 5497 // TODO: Can we handle undef elements? 5498 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5499 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5500 Ops[0].getOpcode() == ISD::BITCAST && 5501 Ops[1].getOpcode() == ISD::BITCAST) { 5502 SDValue N1 = peekThroughBitcasts(Ops[0]); 5503 SDValue N2 = peekThroughBitcasts(Ops[1]); 5504 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5505 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5506 EVT BVVT = N1.getValueType(); 5507 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5508 bool IsLE = getDataLayout().isLittleEndian(); 5509 unsigned EltBits = VT.getScalarSizeInBits(); 5510 SmallVector<APInt> RawBits1, RawBits2; 5511 BitVector UndefElts1, UndefElts2; 5512 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5513 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5514 UndefElts1.none() && UndefElts2.none()) { 5515 SmallVector<APInt> RawBits; 5516 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5517 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5518 if (!Fold) 5519 break; 5520 RawBits.push_back(Fold.getValue()); 5521 } 5522 if (RawBits.size() == NumElts.getFixedValue()) { 5523 // We have constant folded, but we need to cast this again back to 5524 // the original (possibly legalized) type. 5525 SmallVector<APInt> DstBits; 5526 BitVector DstUndefs; 5527 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5528 DstBits, RawBits, DstUndefs, 5529 BitVector(RawBits.size(), false)); 5530 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5531 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5532 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5533 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5534 if (DstUndefs[I]) 5535 continue; 5536 Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT); 5537 } 5538 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5539 } 5540 } 5541 } 5542 } 5543 5544 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5545 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5546 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5547 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5548 APInt RHSVal; 5549 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5550 APInt NewStep = Opcode == ISD::MUL 5551 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5552 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5553 return getStepVector(DL, VT, NewStep); 5554 } 5555 } 5556 5557 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5558 return !Op.getValueType().isVector() || 5559 Op.getValueType().getVectorElementCount() == NumElts; 5560 }; 5561 5562 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5563 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5564 Op.getOpcode() == ISD::BUILD_VECTOR || 5565 Op.getOpcode() == ISD::SPLAT_VECTOR; 5566 }; 5567 5568 // All operands must be vector types with the same number of elements as 5569 // the result type and must be either UNDEF or a build/splat vector 5570 // or UNDEF scalars. 5571 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5572 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5573 return SDValue(); 5574 5575 // If we are comparing vectors, then the result needs to be a i1 boolean 5576 // that is then sign-extended back to the legal result type. 5577 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5578 5579 // Find legal integer scalar type for constant promotion and 5580 // ensure that its scalar size is at least as large as source. 5581 EVT LegalSVT = VT.getScalarType(); 5582 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5583 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5584 if (LegalSVT.bitsLT(VT.getScalarType())) 5585 return SDValue(); 5586 } 5587 5588 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5589 // only have one operand to check. For fixed-length vector types we may have 5590 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5591 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5592 5593 // Constant fold each scalar lane separately. 5594 SmallVector<SDValue, 4> ScalarResults; 5595 for (unsigned I = 0; I != NumVectorElts; I++) { 5596 SmallVector<SDValue, 4> ScalarOps; 5597 for (SDValue Op : Ops) { 5598 EVT InSVT = Op.getValueType().getScalarType(); 5599 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5600 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5601 if (Op.isUndef()) 5602 ScalarOps.push_back(getUNDEF(InSVT)); 5603 else 5604 ScalarOps.push_back(Op); 5605 continue; 5606 } 5607 5608 SDValue ScalarOp = 5609 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5610 EVT ScalarVT = ScalarOp.getValueType(); 5611 5612 // Build vector (integer) scalar operands may need implicit 5613 // truncation - do this before constant folding. 5614 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 5615 // Don't create illegally-typed nodes unless they're constants or undef 5616 // - if we fail to constant fold we can't guarantee the (dead) nodes 5617 // we're creating will be cleaned up before being visited for 5618 // legalization. 5619 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 5620 !isa<ConstantSDNode>(ScalarOp) && 5621 TLI->getTypeAction(*getContext(), InSVT) != 5622 TargetLowering::TypeLegal) 5623 return SDValue(); 5624 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5625 } 5626 5627 ScalarOps.push_back(ScalarOp); 5628 } 5629 5630 // Constant fold the scalar operands. 5631 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5632 5633 // Legalize the (integer) scalar constant if necessary. 5634 if (LegalSVT != SVT) 5635 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5636 5637 // Scalar folding only succeeded if the result is a constant or UNDEF. 5638 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5639 ScalarResult.getOpcode() != ISD::ConstantFP) 5640 return SDValue(); 5641 ScalarResults.push_back(ScalarResult); 5642 } 5643 5644 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5645 : getBuildVector(VT, DL, ScalarResults); 5646 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5647 return V; 5648 } 5649 5650 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5651 EVT VT, SDValue N1, SDValue N2) { 5652 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5653 // should. That will require dealing with a potentially non-default 5654 // rounding mode, checking the "opStatus" return value from the APFloat 5655 // math calculations, and possibly other variations. 5656 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5657 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5658 if (N1CFP && N2CFP) { 5659 APFloat C1 = N1CFP->getValueAPF(); // make copy 5660 const APFloat &C2 = N2CFP->getValueAPF(); 5661 switch (Opcode) { 5662 case ISD::FADD: 5663 C1.add(C2, APFloat::rmNearestTiesToEven); 5664 return getConstantFP(C1, DL, VT); 5665 case ISD::FSUB: 5666 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5667 return getConstantFP(C1, DL, VT); 5668 case ISD::FMUL: 5669 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5670 return getConstantFP(C1, DL, VT); 5671 case ISD::FDIV: 5672 C1.divide(C2, APFloat::rmNearestTiesToEven); 5673 return getConstantFP(C1, DL, VT); 5674 case ISD::FREM: 5675 C1.mod(C2); 5676 return getConstantFP(C1, DL, VT); 5677 case ISD::FCOPYSIGN: 5678 C1.copySign(C2); 5679 return getConstantFP(C1, DL, VT); 5680 case ISD::FMINNUM: 5681 return getConstantFP(minnum(C1, C2), DL, VT); 5682 case ISD::FMAXNUM: 5683 return getConstantFP(maxnum(C1, C2), DL, VT); 5684 case ISD::FMINIMUM: 5685 return getConstantFP(minimum(C1, C2), DL, VT); 5686 case ISD::FMAXIMUM: 5687 return getConstantFP(maximum(C1, C2), DL, VT); 5688 default: break; 5689 } 5690 } 5691 if (N1CFP && Opcode == ISD::FP_ROUND) { 5692 APFloat C1 = N1CFP->getValueAPF(); // make copy 5693 bool Unused; 5694 // This can return overflow, underflow, or inexact; we don't care. 5695 // FIXME need to be more flexible about rounding mode. 5696 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5697 &Unused); 5698 return getConstantFP(C1, DL, VT); 5699 } 5700 5701 switch (Opcode) { 5702 case ISD::FSUB: 5703 // -0.0 - undef --> undef (consistent with "fneg undef") 5704 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5705 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5706 return getUNDEF(VT); 5707 LLVM_FALLTHROUGH; 5708 5709 case ISD::FADD: 5710 case ISD::FMUL: 5711 case ISD::FDIV: 5712 case ISD::FREM: 5713 // If both operands are undef, the result is undef. If 1 operand is undef, 5714 // the result is NaN. This should match the behavior of the IR optimizer. 5715 if (N1.isUndef() && N2.isUndef()) 5716 return getUNDEF(VT); 5717 if (N1.isUndef() || N2.isUndef()) 5718 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5719 } 5720 return SDValue(); 5721 } 5722 5723 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5724 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5725 5726 // There's no need to assert on a byte-aligned pointer. All pointers are at 5727 // least byte aligned. 5728 if (A == Align(1)) 5729 return Val; 5730 5731 FoldingSetNodeID ID; 5732 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5733 ID.AddInteger(A.value()); 5734 5735 void *IP = nullptr; 5736 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5737 return SDValue(E, 0); 5738 5739 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5740 Val.getValueType(), A); 5741 createOperands(N, {Val}); 5742 5743 CSEMap.InsertNode(N, IP); 5744 InsertNode(N); 5745 5746 SDValue V(N, 0); 5747 NewSDValueDbgMsg(V, "Creating new node: ", this); 5748 return V; 5749 } 5750 5751 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5752 SDValue N1, SDValue N2) { 5753 SDNodeFlags Flags; 5754 if (Inserter) 5755 Flags = Inserter->getFlags(); 5756 return getNode(Opcode, DL, VT, N1, N2, Flags); 5757 } 5758 5759 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5760 SDValue &N2) const { 5761 if (!TLI->isCommutativeBinOp(Opcode)) 5762 return; 5763 5764 // Canonicalize: 5765 // binop(const, nonconst) -> binop(nonconst, const) 5766 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5767 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5768 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5769 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5770 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5771 std::swap(N1, N2); 5772 5773 // Canonicalize: 5774 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5775 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5776 N2.getOpcode() == ISD::STEP_VECTOR) 5777 std::swap(N1, N2); 5778 } 5779 5780 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5781 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5782 assert(N1.getOpcode() != ISD::DELETED_NODE && 5783 N2.getOpcode() != ISD::DELETED_NODE && 5784 "Operand is DELETED_NODE!"); 5785 5786 canonicalizeCommutativeBinop(Opcode, N1, N2); 5787 5788 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5789 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5790 5791 // Don't allow undefs in vector splats - we might be returning N2 when folding 5792 // to zero etc. 5793 ConstantSDNode *N2CV = 5794 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5795 5796 switch (Opcode) { 5797 default: break; 5798 case ISD::TokenFactor: 5799 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5800 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5801 // Fold trivial token factors. 5802 if (N1.getOpcode() == ISD::EntryToken) return N2; 5803 if (N2.getOpcode() == ISD::EntryToken) return N1; 5804 if (N1 == N2) return N1; 5805 break; 5806 case ISD::BUILD_VECTOR: { 5807 // Attempt to simplify BUILD_VECTOR. 5808 SDValue Ops[] = {N1, N2}; 5809 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5810 return V; 5811 break; 5812 } 5813 case ISD::CONCAT_VECTORS: { 5814 SDValue Ops[] = {N1, N2}; 5815 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5816 return V; 5817 break; 5818 } 5819 case ISD::AND: 5820 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5821 assert(N1.getValueType() == N2.getValueType() && 5822 N1.getValueType() == VT && "Binary operator types must match!"); 5823 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5824 // worth handling here. 5825 if (N2CV && N2CV->isZero()) 5826 return N2; 5827 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5828 return N1; 5829 break; 5830 case ISD::OR: 5831 case ISD::XOR: 5832 case ISD::ADD: 5833 case ISD::SUB: 5834 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5835 assert(N1.getValueType() == N2.getValueType() && 5836 N1.getValueType() == VT && "Binary operator types must match!"); 5837 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5838 // it's worth handling here. 5839 if (N2CV && N2CV->isZero()) 5840 return N1; 5841 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5842 VT.getVectorElementType() == MVT::i1) 5843 return getNode(ISD::XOR, DL, VT, N1, N2); 5844 break; 5845 case ISD::MUL: 5846 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5847 assert(N1.getValueType() == N2.getValueType() && 5848 N1.getValueType() == VT && "Binary operator types must match!"); 5849 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5850 return getNode(ISD::AND, DL, VT, N1, N2); 5851 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5852 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5853 const APInt &N2CImm = N2C->getAPIntValue(); 5854 return getVScale(DL, VT, MulImm * N2CImm); 5855 } 5856 break; 5857 case ISD::UDIV: 5858 case ISD::UREM: 5859 case ISD::MULHU: 5860 case ISD::MULHS: 5861 case ISD::SDIV: 5862 case ISD::SREM: 5863 case ISD::SADDSAT: 5864 case ISD::SSUBSAT: 5865 case ISD::UADDSAT: 5866 case ISD::USUBSAT: 5867 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5868 assert(N1.getValueType() == N2.getValueType() && 5869 N1.getValueType() == VT && "Binary operator types must match!"); 5870 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5871 // fold (add_sat x, y) -> (or x, y) for bool types. 5872 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5873 return getNode(ISD::OR, DL, VT, N1, N2); 5874 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5875 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5876 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5877 } 5878 break; 5879 case ISD::SMIN: 5880 case ISD::UMAX: 5881 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5882 assert(N1.getValueType() == N2.getValueType() && 5883 N1.getValueType() == VT && "Binary operator types must match!"); 5884 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5885 return getNode(ISD::OR, DL, VT, N1, N2); 5886 break; 5887 case ISD::SMAX: 5888 case ISD::UMIN: 5889 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5890 assert(N1.getValueType() == N2.getValueType() && 5891 N1.getValueType() == VT && "Binary operator types must match!"); 5892 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5893 return getNode(ISD::AND, DL, VT, N1, N2); 5894 break; 5895 case ISD::FADD: 5896 case ISD::FSUB: 5897 case ISD::FMUL: 5898 case ISD::FDIV: 5899 case ISD::FREM: 5900 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5901 assert(N1.getValueType() == N2.getValueType() && 5902 N1.getValueType() == VT && "Binary operator types must match!"); 5903 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5904 return V; 5905 break; 5906 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5907 assert(N1.getValueType() == VT && 5908 N1.getValueType().isFloatingPoint() && 5909 N2.getValueType().isFloatingPoint() && 5910 "Invalid FCOPYSIGN!"); 5911 break; 5912 case ISD::SHL: 5913 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5914 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5915 const APInt &ShiftImm = N2C->getAPIntValue(); 5916 return getVScale(DL, VT, MulImm << ShiftImm); 5917 } 5918 LLVM_FALLTHROUGH; 5919 case ISD::SRA: 5920 case ISD::SRL: 5921 if (SDValue V = simplifyShift(N1, N2)) 5922 return V; 5923 LLVM_FALLTHROUGH; 5924 case ISD::ROTL: 5925 case ISD::ROTR: 5926 assert(VT == N1.getValueType() && 5927 "Shift operators return type must be the same as their first arg"); 5928 assert(VT.isInteger() && N2.getValueType().isInteger() && 5929 "Shifts only work on integers"); 5930 assert((!VT.isVector() || VT == N2.getValueType()) && 5931 "Vector shift amounts must be in the same as their first arg"); 5932 // Verify that the shift amount VT is big enough to hold valid shift 5933 // amounts. This catches things like trying to shift an i1024 value by an 5934 // i8, which is easy to fall into in generic code that uses 5935 // TLI.getShiftAmount(). 5936 assert(N2.getValueType().getScalarSizeInBits() >= 5937 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5938 "Invalid use of small shift amount with oversized value!"); 5939 5940 // Always fold shifts of i1 values so the code generator doesn't need to 5941 // handle them. Since we know the size of the shift has to be less than the 5942 // size of the value, the shift/rotate count is guaranteed to be zero. 5943 if (VT == MVT::i1) 5944 return N1; 5945 if (N2CV && N2CV->isZero()) 5946 return N1; 5947 break; 5948 case ISD::FP_ROUND: 5949 assert(VT.isFloatingPoint() && 5950 N1.getValueType().isFloatingPoint() && 5951 VT.bitsLE(N1.getValueType()) && 5952 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5953 "Invalid FP_ROUND!"); 5954 if (N1.getValueType() == VT) return N1; // noop conversion. 5955 break; 5956 case ISD::AssertSext: 5957 case ISD::AssertZext: { 5958 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5959 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5960 assert(VT.isInteger() && EVT.isInteger() && 5961 "Cannot *_EXTEND_INREG FP types"); 5962 assert(!EVT.isVector() && 5963 "AssertSExt/AssertZExt type should be the vector element type " 5964 "rather than the vector type!"); 5965 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5966 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5967 break; 5968 } 5969 case ISD::SIGN_EXTEND_INREG: { 5970 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5971 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5972 assert(VT.isInteger() && EVT.isInteger() && 5973 "Cannot *_EXTEND_INREG FP types"); 5974 assert(EVT.isVector() == VT.isVector() && 5975 "SIGN_EXTEND_INREG type should be vector iff the operand " 5976 "type is vector!"); 5977 assert((!EVT.isVector() || 5978 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5979 "Vector element counts must match in SIGN_EXTEND_INREG"); 5980 assert(EVT.bitsLE(VT) && "Not extending!"); 5981 if (EVT == VT) return N1; // Not actually extending 5982 5983 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5984 unsigned FromBits = EVT.getScalarSizeInBits(); 5985 Val <<= Val.getBitWidth() - FromBits; 5986 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5987 return getConstant(Val, DL, ConstantVT); 5988 }; 5989 5990 if (N1C) { 5991 const APInt &Val = N1C->getAPIntValue(); 5992 return SignExtendInReg(Val, VT); 5993 } 5994 5995 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5996 SmallVector<SDValue, 8> Ops; 5997 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5998 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5999 SDValue Op = N1.getOperand(i); 6000 if (Op.isUndef()) { 6001 Ops.push_back(getUNDEF(OpVT)); 6002 continue; 6003 } 6004 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6005 APInt Val = C->getAPIntValue(); 6006 Ops.push_back(SignExtendInReg(Val, OpVT)); 6007 } 6008 return getBuildVector(VT, DL, Ops); 6009 } 6010 break; 6011 } 6012 case ISD::FP_TO_SINT_SAT: 6013 case ISD::FP_TO_UINT_SAT: { 6014 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6015 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6016 assert(N1.getValueType().isVector() == VT.isVector() && 6017 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6018 "vector!"); 6019 assert((!VT.isVector() || VT.getVectorNumElements() == 6020 N1.getValueType().getVectorNumElements()) && 6021 "Vector element counts must match in FP_TO_*INT_SAT"); 6022 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6023 "Type to saturate to must be a scalar."); 6024 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6025 "Not extending!"); 6026 break; 6027 } 6028 case ISD::EXTRACT_VECTOR_ELT: 6029 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6030 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6031 element type of the vector."); 6032 6033 // Extract from an undefined value or using an undefined index is undefined. 6034 if (N1.isUndef() || N2.isUndef()) 6035 return getUNDEF(VT); 6036 6037 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6038 // vectors. For scalable vectors we will provide appropriate support for 6039 // dealing with arbitrary indices. 6040 if (N2C && N1.getValueType().isFixedLengthVector() && 6041 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6042 return getUNDEF(VT); 6043 6044 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6045 // expanding copies of large vectors from registers. This only works for 6046 // fixed length vectors, since we need to know the exact number of 6047 // elements. 6048 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6049 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6050 unsigned Factor = 6051 N1.getOperand(0).getValueType().getVectorNumElements(); 6052 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6053 N1.getOperand(N2C->getZExtValue() / Factor), 6054 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6055 } 6056 6057 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6058 // lowering is expanding large vector constants. 6059 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6060 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6061 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6062 N1.getValueType().isFixedLengthVector()) && 6063 "BUILD_VECTOR used for scalable vectors"); 6064 unsigned Index = 6065 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6066 SDValue Elt = N1.getOperand(Index); 6067 6068 if (VT != Elt.getValueType()) 6069 // If the vector element type is not legal, the BUILD_VECTOR operands 6070 // are promoted and implicitly truncated, and the result implicitly 6071 // extended. Make that explicit here. 6072 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6073 6074 return Elt; 6075 } 6076 6077 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6078 // operations are lowered to scalars. 6079 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6080 // If the indices are the same, return the inserted element else 6081 // if the indices are known different, extract the element from 6082 // the original vector. 6083 SDValue N1Op2 = N1.getOperand(2); 6084 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6085 6086 if (N1Op2C && N2C) { 6087 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6088 if (VT == N1.getOperand(1).getValueType()) 6089 return N1.getOperand(1); 6090 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6091 } 6092 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6093 } 6094 } 6095 6096 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6097 // when vector types are scalarized and v1iX is legal. 6098 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6099 // Here we are completely ignoring the extract element index (N2), 6100 // which is fine for fixed width vectors, since any index other than 0 6101 // is undefined anyway. However, this cannot be ignored for scalable 6102 // vectors - in theory we could support this, but we don't want to do this 6103 // without a profitability check. 6104 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6105 N1.getValueType().isFixedLengthVector() && 6106 N1.getValueType().getVectorNumElements() == 1) { 6107 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6108 N1.getOperand(1)); 6109 } 6110 break; 6111 case ISD::EXTRACT_ELEMENT: 6112 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6113 assert(!N1.getValueType().isVector() && !VT.isVector() && 6114 (N1.getValueType().isInteger() == VT.isInteger()) && 6115 N1.getValueType() != VT && 6116 "Wrong types for EXTRACT_ELEMENT!"); 6117 6118 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6119 // 64-bit integers into 32-bit parts. Instead of building the extract of 6120 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6121 if (N1.getOpcode() == ISD::BUILD_PAIR) 6122 return N1.getOperand(N2C->getZExtValue()); 6123 6124 // EXTRACT_ELEMENT of a constant int is also very common. 6125 if (N1C) { 6126 unsigned ElementSize = VT.getSizeInBits(); 6127 unsigned Shift = ElementSize * N2C->getZExtValue(); 6128 const APInt &Val = N1C->getAPIntValue(); 6129 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6130 } 6131 break; 6132 case ISD::EXTRACT_SUBVECTOR: { 6133 EVT N1VT = N1.getValueType(); 6134 assert(VT.isVector() && N1VT.isVector() && 6135 "Extract subvector VTs must be vectors!"); 6136 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6137 "Extract subvector VTs must have the same element type!"); 6138 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6139 "Cannot extract a scalable vector from a fixed length vector!"); 6140 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6141 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6142 "Extract subvector must be from larger vector to smaller vector!"); 6143 assert(N2C && "Extract subvector index must be a constant"); 6144 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6145 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6146 N1VT.getVectorMinNumElements()) && 6147 "Extract subvector overflow!"); 6148 assert(N2C->getAPIntValue().getBitWidth() == 6149 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6150 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6151 6152 // Trivial extraction. 6153 if (VT == N1VT) 6154 return N1; 6155 6156 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6157 if (N1.isUndef()) 6158 return getUNDEF(VT); 6159 6160 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6161 // the concat have the same type as the extract. 6162 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6163 VT == N1.getOperand(0).getValueType()) { 6164 unsigned Factor = VT.getVectorMinNumElements(); 6165 return N1.getOperand(N2C->getZExtValue() / Factor); 6166 } 6167 6168 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6169 // during shuffle legalization. 6170 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6171 VT == N1.getOperand(1).getValueType()) 6172 return N1.getOperand(1); 6173 break; 6174 } 6175 } 6176 6177 // Perform trivial constant folding. 6178 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6179 return SV; 6180 6181 // Canonicalize an UNDEF to the RHS, even over a constant. 6182 if (N1.isUndef()) { 6183 if (TLI->isCommutativeBinOp(Opcode)) { 6184 std::swap(N1, N2); 6185 } else { 6186 switch (Opcode) { 6187 case ISD::SIGN_EXTEND_INREG: 6188 case ISD::SUB: 6189 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6190 case ISD::UDIV: 6191 case ISD::SDIV: 6192 case ISD::UREM: 6193 case ISD::SREM: 6194 case ISD::SSUBSAT: 6195 case ISD::USUBSAT: 6196 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6197 } 6198 } 6199 } 6200 6201 // Fold a bunch of operators when the RHS is undef. 6202 if (N2.isUndef()) { 6203 switch (Opcode) { 6204 case ISD::XOR: 6205 if (N1.isUndef()) 6206 // Handle undef ^ undef -> 0 special case. This is a common 6207 // idiom (misuse). 6208 return getConstant(0, DL, VT); 6209 LLVM_FALLTHROUGH; 6210 case ISD::ADD: 6211 case ISD::SUB: 6212 case ISD::UDIV: 6213 case ISD::SDIV: 6214 case ISD::UREM: 6215 case ISD::SREM: 6216 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6217 case ISD::MUL: 6218 case ISD::AND: 6219 case ISD::SSUBSAT: 6220 case ISD::USUBSAT: 6221 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6222 case ISD::OR: 6223 case ISD::SADDSAT: 6224 case ISD::UADDSAT: 6225 return getAllOnesConstant(DL, VT); 6226 } 6227 } 6228 6229 // Memoize this node if possible. 6230 SDNode *N; 6231 SDVTList VTs = getVTList(VT); 6232 SDValue Ops[] = {N1, N2}; 6233 if (VT != MVT::Glue) { 6234 FoldingSetNodeID ID; 6235 AddNodeIDNode(ID, Opcode, VTs, Ops); 6236 void *IP = nullptr; 6237 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6238 E->intersectFlagsWith(Flags); 6239 return SDValue(E, 0); 6240 } 6241 6242 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6243 N->setFlags(Flags); 6244 createOperands(N, Ops); 6245 CSEMap.InsertNode(N, IP); 6246 } else { 6247 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6248 createOperands(N, Ops); 6249 } 6250 6251 InsertNode(N); 6252 SDValue V = SDValue(N, 0); 6253 NewSDValueDbgMsg(V, "Creating new node: ", this); 6254 return V; 6255 } 6256 6257 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6258 SDValue N1, SDValue N2, SDValue N3) { 6259 SDNodeFlags Flags; 6260 if (Inserter) 6261 Flags = Inserter->getFlags(); 6262 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6263 } 6264 6265 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6266 SDValue N1, SDValue N2, SDValue N3, 6267 const SDNodeFlags Flags) { 6268 assert(N1.getOpcode() != ISD::DELETED_NODE && 6269 N2.getOpcode() != ISD::DELETED_NODE && 6270 N3.getOpcode() != ISD::DELETED_NODE && 6271 "Operand is DELETED_NODE!"); 6272 // Perform various simplifications. 6273 switch (Opcode) { 6274 case ISD::FMA: { 6275 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6276 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6277 N3.getValueType() == VT && "FMA types must match!"); 6278 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6279 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6280 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6281 if (N1CFP && N2CFP && N3CFP) { 6282 APFloat V1 = N1CFP->getValueAPF(); 6283 const APFloat &V2 = N2CFP->getValueAPF(); 6284 const APFloat &V3 = N3CFP->getValueAPF(); 6285 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6286 return getConstantFP(V1, DL, VT); 6287 } 6288 break; 6289 } 6290 case ISD::BUILD_VECTOR: { 6291 // Attempt to simplify BUILD_VECTOR. 6292 SDValue Ops[] = {N1, N2, N3}; 6293 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6294 return V; 6295 break; 6296 } 6297 case ISD::CONCAT_VECTORS: { 6298 SDValue Ops[] = {N1, N2, N3}; 6299 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6300 return V; 6301 break; 6302 } 6303 case ISD::SETCC: { 6304 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6305 assert(N1.getValueType() == N2.getValueType() && 6306 "SETCC operands must have the same type!"); 6307 assert(VT.isVector() == N1.getValueType().isVector() && 6308 "SETCC type should be vector iff the operand type is vector!"); 6309 assert((!VT.isVector() || VT.getVectorElementCount() == 6310 N1.getValueType().getVectorElementCount()) && 6311 "SETCC vector element counts must match!"); 6312 // Use FoldSetCC to simplify SETCC's. 6313 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6314 return V; 6315 // Vector constant folding. 6316 SDValue Ops[] = {N1, N2, N3}; 6317 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6318 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6319 return V; 6320 } 6321 break; 6322 } 6323 case ISD::SELECT: 6324 case ISD::VSELECT: 6325 if (SDValue V = simplifySelect(N1, N2, N3)) 6326 return V; 6327 break; 6328 case ISD::VECTOR_SHUFFLE: 6329 llvm_unreachable("should use getVectorShuffle constructor!"); 6330 case ISD::VECTOR_SPLICE: { 6331 if (cast<ConstantSDNode>(N3)->isNullValue()) 6332 return N1; 6333 break; 6334 } 6335 case ISD::INSERT_VECTOR_ELT: { 6336 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6337 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6338 // for scalable vectors where we will generate appropriate code to 6339 // deal with out-of-bounds cases correctly. 6340 if (N3C && N1.getValueType().isFixedLengthVector() && 6341 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6342 return getUNDEF(VT); 6343 6344 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6345 if (N3.isUndef()) 6346 return getUNDEF(VT); 6347 6348 // If the inserted element is an UNDEF, just use the input vector. 6349 if (N2.isUndef()) 6350 return N1; 6351 6352 break; 6353 } 6354 case ISD::INSERT_SUBVECTOR: { 6355 // Inserting undef into undef is still undef. 6356 if (N1.isUndef() && N2.isUndef()) 6357 return getUNDEF(VT); 6358 6359 EVT N2VT = N2.getValueType(); 6360 assert(VT == N1.getValueType() && 6361 "Dest and insert subvector source types must match!"); 6362 assert(VT.isVector() && N2VT.isVector() && 6363 "Insert subvector VTs must be vectors!"); 6364 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6365 "Cannot insert a scalable vector into a fixed length vector!"); 6366 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6367 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6368 "Insert subvector must be from smaller vector to larger vector!"); 6369 assert(isa<ConstantSDNode>(N3) && 6370 "Insert subvector index must be constant"); 6371 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6372 (N2VT.getVectorMinNumElements() + 6373 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6374 VT.getVectorMinNumElements()) && 6375 "Insert subvector overflow!"); 6376 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6377 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6378 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6379 6380 // Trivial insertion. 6381 if (VT == N2VT) 6382 return N2; 6383 6384 // If this is an insert of an extracted vector into an undef vector, we 6385 // can just use the input to the extract. 6386 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6387 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6388 return N2.getOperand(0); 6389 break; 6390 } 6391 case ISD::BITCAST: 6392 // Fold bit_convert nodes from a type to themselves. 6393 if (N1.getValueType() == VT) 6394 return N1; 6395 break; 6396 } 6397 6398 // Memoize node if it doesn't produce a flag. 6399 SDNode *N; 6400 SDVTList VTs = getVTList(VT); 6401 SDValue Ops[] = {N1, N2, N3}; 6402 if (VT != MVT::Glue) { 6403 FoldingSetNodeID ID; 6404 AddNodeIDNode(ID, Opcode, VTs, Ops); 6405 void *IP = nullptr; 6406 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6407 E->intersectFlagsWith(Flags); 6408 return SDValue(E, 0); 6409 } 6410 6411 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6412 N->setFlags(Flags); 6413 createOperands(N, Ops); 6414 CSEMap.InsertNode(N, IP); 6415 } else { 6416 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6417 createOperands(N, Ops); 6418 } 6419 6420 InsertNode(N); 6421 SDValue V = SDValue(N, 0); 6422 NewSDValueDbgMsg(V, "Creating new node: ", this); 6423 return V; 6424 } 6425 6426 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6427 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6428 SDValue Ops[] = { N1, N2, N3, N4 }; 6429 return getNode(Opcode, DL, VT, Ops); 6430 } 6431 6432 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6433 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6434 SDValue N5) { 6435 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6436 return getNode(Opcode, DL, VT, Ops); 6437 } 6438 6439 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6440 /// the incoming stack arguments to be loaded from the stack. 6441 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6442 SmallVector<SDValue, 8> ArgChains; 6443 6444 // Include the original chain at the beginning of the list. When this is 6445 // used by target LowerCall hooks, this helps legalize find the 6446 // CALLSEQ_BEGIN node. 6447 ArgChains.push_back(Chain); 6448 6449 // Add a chain value for each stack argument. 6450 for (SDNode *U : getEntryNode().getNode()->uses()) 6451 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6452 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6453 if (FI->getIndex() < 0) 6454 ArgChains.push_back(SDValue(L, 1)); 6455 6456 // Build a tokenfactor for all the chains. 6457 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6458 } 6459 6460 /// getMemsetValue - Vectorized representation of the memset value 6461 /// operand. 6462 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6463 const SDLoc &dl) { 6464 assert(!Value.isUndef()); 6465 6466 unsigned NumBits = VT.getScalarSizeInBits(); 6467 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6468 assert(C->getAPIntValue().getBitWidth() == 8); 6469 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6470 if (VT.isInteger()) { 6471 bool IsOpaque = VT.getSizeInBits() > 64 || 6472 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6473 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6474 } 6475 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6476 VT); 6477 } 6478 6479 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6480 EVT IntVT = VT.getScalarType(); 6481 if (!IntVT.isInteger()) 6482 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6483 6484 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6485 if (NumBits > 8) { 6486 // Use a multiplication with 0x010101... to extend the input to the 6487 // required length. 6488 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6489 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6490 DAG.getConstant(Magic, dl, IntVT)); 6491 } 6492 6493 if (VT != Value.getValueType() && !VT.isInteger()) 6494 Value = DAG.getBitcast(VT.getScalarType(), Value); 6495 if (VT != Value.getValueType()) 6496 Value = DAG.getSplatBuildVector(VT, dl, Value); 6497 6498 return Value; 6499 } 6500 6501 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6502 /// used when a memcpy is turned into a memset when the source is a constant 6503 /// string ptr. 6504 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6505 const TargetLowering &TLI, 6506 const ConstantDataArraySlice &Slice) { 6507 // Handle vector with all elements zero. 6508 if (Slice.Array == nullptr) { 6509 if (VT.isInteger()) 6510 return DAG.getConstant(0, dl, VT); 6511 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6512 return DAG.getConstantFP(0.0, dl, VT); 6513 if (VT.isVector()) { 6514 unsigned NumElts = VT.getVectorNumElements(); 6515 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6516 return DAG.getNode(ISD::BITCAST, dl, VT, 6517 DAG.getConstant(0, dl, 6518 EVT::getVectorVT(*DAG.getContext(), 6519 EltVT, NumElts))); 6520 } 6521 llvm_unreachable("Expected type!"); 6522 } 6523 6524 assert(!VT.isVector() && "Can't handle vector type here!"); 6525 unsigned NumVTBits = VT.getSizeInBits(); 6526 unsigned NumVTBytes = NumVTBits / 8; 6527 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6528 6529 APInt Val(NumVTBits, 0); 6530 if (DAG.getDataLayout().isLittleEndian()) { 6531 for (unsigned i = 0; i != NumBytes; ++i) 6532 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6533 } else { 6534 for (unsigned i = 0; i != NumBytes; ++i) 6535 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6536 } 6537 6538 // If the "cost" of materializing the integer immediate is less than the cost 6539 // of a load, then it is cost effective to turn the load into the immediate. 6540 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6541 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6542 return DAG.getConstant(Val, dl, VT); 6543 return SDValue(); 6544 } 6545 6546 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6547 const SDLoc &DL, 6548 const SDNodeFlags Flags) { 6549 EVT VT = Base.getValueType(); 6550 SDValue Index; 6551 6552 if (Offset.isScalable()) 6553 Index = getVScale(DL, Base.getValueType(), 6554 APInt(Base.getValueSizeInBits().getFixedSize(), 6555 Offset.getKnownMinSize())); 6556 else 6557 Index = getConstant(Offset.getFixedSize(), DL, VT); 6558 6559 return getMemBasePlusOffset(Base, Index, DL, Flags); 6560 } 6561 6562 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6563 const SDLoc &DL, 6564 const SDNodeFlags Flags) { 6565 assert(Offset.getValueType().isInteger()); 6566 EVT BasePtrVT = Ptr.getValueType(); 6567 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6568 } 6569 6570 /// Returns true if memcpy source is constant data. 6571 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6572 uint64_t SrcDelta = 0; 6573 GlobalAddressSDNode *G = nullptr; 6574 if (Src.getOpcode() == ISD::GlobalAddress) 6575 G = cast<GlobalAddressSDNode>(Src); 6576 else if (Src.getOpcode() == ISD::ADD && 6577 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6578 Src.getOperand(1).getOpcode() == ISD::Constant) { 6579 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6580 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6581 } 6582 if (!G) 6583 return false; 6584 6585 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6586 SrcDelta + G->getOffset()); 6587 } 6588 6589 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6590 SelectionDAG &DAG) { 6591 // On Darwin, -Os means optimize for size without hurting performance, so 6592 // only really optimize for size when -Oz (MinSize) is used. 6593 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6594 return MF.getFunction().hasMinSize(); 6595 return DAG.shouldOptForSize(); 6596 } 6597 6598 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6599 SmallVector<SDValue, 32> &OutChains, unsigned From, 6600 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6601 SmallVector<SDValue, 16> &OutStoreChains) { 6602 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6603 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6604 SmallVector<SDValue, 16> GluedLoadChains; 6605 for (unsigned i = From; i < To; ++i) { 6606 OutChains.push_back(OutLoadChains[i]); 6607 GluedLoadChains.push_back(OutLoadChains[i]); 6608 } 6609 6610 // Chain for all loads. 6611 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6612 GluedLoadChains); 6613 6614 for (unsigned i = From; i < To; ++i) { 6615 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6616 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6617 ST->getBasePtr(), ST->getMemoryVT(), 6618 ST->getMemOperand()); 6619 OutChains.push_back(NewStore); 6620 } 6621 } 6622 6623 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6624 SDValue Chain, SDValue Dst, SDValue Src, 6625 uint64_t Size, Align Alignment, 6626 bool isVol, bool AlwaysInline, 6627 MachinePointerInfo DstPtrInfo, 6628 MachinePointerInfo SrcPtrInfo, 6629 const AAMDNodes &AAInfo) { 6630 // Turn a memcpy of undef to nop. 6631 // FIXME: We need to honor volatile even is Src is undef. 6632 if (Src.isUndef()) 6633 return Chain; 6634 6635 // Expand memcpy to a series of load and store ops if the size operand falls 6636 // below a certain threshold. 6637 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6638 // rather than maybe a humongous number of loads and stores. 6639 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6640 const DataLayout &DL = DAG.getDataLayout(); 6641 LLVMContext &C = *DAG.getContext(); 6642 std::vector<EVT> MemOps; 6643 bool DstAlignCanChange = false; 6644 MachineFunction &MF = DAG.getMachineFunction(); 6645 MachineFrameInfo &MFI = MF.getFrameInfo(); 6646 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6647 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6648 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6649 DstAlignCanChange = true; 6650 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6651 if (!SrcAlign || Alignment > *SrcAlign) 6652 SrcAlign = Alignment; 6653 assert(SrcAlign && "SrcAlign must be set"); 6654 ConstantDataArraySlice Slice; 6655 // If marked as volatile, perform a copy even when marked as constant. 6656 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6657 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6658 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6659 const MemOp Op = isZeroConstant 6660 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6661 /*IsZeroMemset*/ true, isVol) 6662 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6663 *SrcAlign, isVol, CopyFromConstant); 6664 if (!TLI.findOptimalMemOpLowering( 6665 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6666 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6667 return SDValue(); 6668 6669 if (DstAlignCanChange) { 6670 Type *Ty = MemOps[0].getTypeForEVT(C); 6671 Align NewAlign = DL.getABITypeAlign(Ty); 6672 6673 // Don't promote to an alignment that would require dynamic stack 6674 // realignment. 6675 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6676 if (!TRI->hasStackRealignment(MF)) 6677 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6678 NewAlign = NewAlign / 2; 6679 6680 if (NewAlign > Alignment) { 6681 // Give the stack frame object a larger alignment if needed. 6682 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6683 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6684 Alignment = NewAlign; 6685 } 6686 } 6687 6688 // Prepare AAInfo for loads/stores after lowering this memcpy. 6689 AAMDNodes NewAAInfo = AAInfo; 6690 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6691 6692 MachineMemOperand::Flags MMOFlags = 6693 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6694 SmallVector<SDValue, 16> OutLoadChains; 6695 SmallVector<SDValue, 16> OutStoreChains; 6696 SmallVector<SDValue, 32> OutChains; 6697 unsigned NumMemOps = MemOps.size(); 6698 uint64_t SrcOff = 0, DstOff = 0; 6699 for (unsigned i = 0; i != NumMemOps; ++i) { 6700 EVT VT = MemOps[i]; 6701 unsigned VTSize = VT.getSizeInBits() / 8; 6702 SDValue Value, Store; 6703 6704 if (VTSize > Size) { 6705 // Issuing an unaligned load / store pair that overlaps with the previous 6706 // pair. Adjust the offset accordingly. 6707 assert(i == NumMemOps-1 && i != 0); 6708 SrcOff -= VTSize - Size; 6709 DstOff -= VTSize - Size; 6710 } 6711 6712 if (CopyFromConstant && 6713 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6714 // It's unlikely a store of a vector immediate can be done in a single 6715 // instruction. It would require a load from a constantpool first. 6716 // We only handle zero vectors here. 6717 // FIXME: Handle other cases where store of vector immediate is done in 6718 // a single instruction. 6719 ConstantDataArraySlice SubSlice; 6720 if (SrcOff < Slice.Length) { 6721 SubSlice = Slice; 6722 SubSlice.move(SrcOff); 6723 } else { 6724 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6725 SubSlice.Array = nullptr; 6726 SubSlice.Offset = 0; 6727 SubSlice.Length = VTSize; 6728 } 6729 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6730 if (Value.getNode()) { 6731 Store = DAG.getStore( 6732 Chain, dl, Value, 6733 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6734 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6735 OutChains.push_back(Store); 6736 } 6737 } 6738 6739 if (!Store.getNode()) { 6740 // The type might not be legal for the target. This should only happen 6741 // if the type is smaller than a legal type, as on PPC, so the right 6742 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6743 // to Load/Store if NVT==VT. 6744 // FIXME does the case above also need this? 6745 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6746 assert(NVT.bitsGE(VT)); 6747 6748 bool isDereferenceable = 6749 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6750 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6751 if (isDereferenceable) 6752 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6753 6754 Value = DAG.getExtLoad( 6755 ISD::EXTLOAD, dl, NVT, Chain, 6756 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6757 SrcPtrInfo.getWithOffset(SrcOff), VT, 6758 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6759 OutLoadChains.push_back(Value.getValue(1)); 6760 6761 Store = DAG.getTruncStore( 6762 Chain, dl, Value, 6763 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6764 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6765 OutStoreChains.push_back(Store); 6766 } 6767 SrcOff += VTSize; 6768 DstOff += VTSize; 6769 Size -= VTSize; 6770 } 6771 6772 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6773 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6774 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6775 6776 if (NumLdStInMemcpy) { 6777 // It may be that memcpy might be converted to memset if it's memcpy 6778 // of constants. In such a case, we won't have loads and stores, but 6779 // just stores. In the absence of loads, there is nothing to gang up. 6780 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6781 // If target does not care, just leave as it. 6782 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6783 OutChains.push_back(OutLoadChains[i]); 6784 OutChains.push_back(OutStoreChains[i]); 6785 } 6786 } else { 6787 // Ld/St less than/equal limit set by target. 6788 if (NumLdStInMemcpy <= GluedLdStLimit) { 6789 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6790 NumLdStInMemcpy, OutLoadChains, 6791 OutStoreChains); 6792 } else { 6793 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6794 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6795 unsigned GlueIter = 0; 6796 6797 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6798 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6799 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6800 6801 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6802 OutLoadChains, OutStoreChains); 6803 GlueIter += GluedLdStLimit; 6804 } 6805 6806 // Residual ld/st. 6807 if (RemainingLdStInMemcpy) { 6808 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6809 RemainingLdStInMemcpy, OutLoadChains, 6810 OutStoreChains); 6811 } 6812 } 6813 } 6814 } 6815 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6816 } 6817 6818 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6819 SDValue Chain, SDValue Dst, SDValue Src, 6820 uint64_t Size, Align Alignment, 6821 bool isVol, bool AlwaysInline, 6822 MachinePointerInfo DstPtrInfo, 6823 MachinePointerInfo SrcPtrInfo, 6824 const AAMDNodes &AAInfo) { 6825 // Turn a memmove of undef to nop. 6826 // FIXME: We need to honor volatile even is Src is undef. 6827 if (Src.isUndef()) 6828 return Chain; 6829 6830 // Expand memmove to a series of load and store ops if the size operand falls 6831 // below a certain threshold. 6832 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6833 const DataLayout &DL = DAG.getDataLayout(); 6834 LLVMContext &C = *DAG.getContext(); 6835 std::vector<EVT> MemOps; 6836 bool DstAlignCanChange = false; 6837 MachineFunction &MF = DAG.getMachineFunction(); 6838 MachineFrameInfo &MFI = MF.getFrameInfo(); 6839 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6840 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6841 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6842 DstAlignCanChange = true; 6843 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6844 if (!SrcAlign || Alignment > *SrcAlign) 6845 SrcAlign = Alignment; 6846 assert(SrcAlign && "SrcAlign must be set"); 6847 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6848 if (!TLI.findOptimalMemOpLowering( 6849 MemOps, Limit, 6850 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6851 /*IsVolatile*/ true), 6852 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6853 MF.getFunction().getAttributes())) 6854 return SDValue(); 6855 6856 if (DstAlignCanChange) { 6857 Type *Ty = MemOps[0].getTypeForEVT(C); 6858 Align NewAlign = DL.getABITypeAlign(Ty); 6859 if (NewAlign > Alignment) { 6860 // Give the stack frame object a larger alignment if needed. 6861 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6862 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6863 Alignment = NewAlign; 6864 } 6865 } 6866 6867 // Prepare AAInfo for loads/stores after lowering this memmove. 6868 AAMDNodes NewAAInfo = AAInfo; 6869 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6870 6871 MachineMemOperand::Flags MMOFlags = 6872 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6873 uint64_t SrcOff = 0, DstOff = 0; 6874 SmallVector<SDValue, 8> LoadValues; 6875 SmallVector<SDValue, 8> LoadChains; 6876 SmallVector<SDValue, 8> OutChains; 6877 unsigned NumMemOps = MemOps.size(); 6878 for (unsigned i = 0; i < NumMemOps; i++) { 6879 EVT VT = MemOps[i]; 6880 unsigned VTSize = VT.getSizeInBits() / 8; 6881 SDValue Value; 6882 6883 bool isDereferenceable = 6884 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6885 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6886 if (isDereferenceable) 6887 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6888 6889 Value = DAG.getLoad( 6890 VT, dl, Chain, 6891 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6892 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6893 LoadValues.push_back(Value); 6894 LoadChains.push_back(Value.getValue(1)); 6895 SrcOff += VTSize; 6896 } 6897 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6898 OutChains.clear(); 6899 for (unsigned i = 0; i < NumMemOps; i++) { 6900 EVT VT = MemOps[i]; 6901 unsigned VTSize = VT.getSizeInBits() / 8; 6902 SDValue Store; 6903 6904 Store = DAG.getStore( 6905 Chain, dl, LoadValues[i], 6906 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6907 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6908 OutChains.push_back(Store); 6909 DstOff += VTSize; 6910 } 6911 6912 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6913 } 6914 6915 /// Lower the call to 'memset' intrinsic function into a series of store 6916 /// operations. 6917 /// 6918 /// \param DAG Selection DAG where lowered code is placed. 6919 /// \param dl Link to corresponding IR location. 6920 /// \param Chain Control flow dependency. 6921 /// \param Dst Pointer to destination memory location. 6922 /// \param Src Value of byte to write into the memory. 6923 /// \param Size Number of bytes to write. 6924 /// \param Alignment Alignment of the destination in bytes. 6925 /// \param isVol True if destination is volatile. 6926 /// \param DstPtrInfo IR information on the memory pointer. 6927 /// \returns New head in the control flow, if lowering was successful, empty 6928 /// SDValue otherwise. 6929 /// 6930 /// The function tries to replace 'llvm.memset' intrinsic with several store 6931 /// operations and value calculation code. This is usually profitable for small 6932 /// memory size. 6933 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6934 SDValue Chain, SDValue Dst, SDValue Src, 6935 uint64_t Size, Align Alignment, bool isVol, 6936 MachinePointerInfo DstPtrInfo, 6937 const AAMDNodes &AAInfo) { 6938 // Turn a memset of undef to nop. 6939 // FIXME: We need to honor volatile even is Src is undef. 6940 if (Src.isUndef()) 6941 return Chain; 6942 6943 // Expand memset to a series of load/store ops if the size operand 6944 // falls below a certain threshold. 6945 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6946 std::vector<EVT> MemOps; 6947 bool DstAlignCanChange = false; 6948 MachineFunction &MF = DAG.getMachineFunction(); 6949 MachineFrameInfo &MFI = MF.getFrameInfo(); 6950 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6951 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6952 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6953 DstAlignCanChange = true; 6954 bool IsZeroVal = 6955 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6956 if (!TLI.findOptimalMemOpLowering( 6957 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6958 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6959 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6960 return SDValue(); 6961 6962 if (DstAlignCanChange) { 6963 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6964 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6965 if (NewAlign > Alignment) { 6966 // Give the stack frame object a larger alignment if needed. 6967 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6968 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6969 Alignment = NewAlign; 6970 } 6971 } 6972 6973 SmallVector<SDValue, 8> OutChains; 6974 uint64_t DstOff = 0; 6975 unsigned NumMemOps = MemOps.size(); 6976 6977 // Find the largest store and generate the bit pattern for it. 6978 EVT LargestVT = MemOps[0]; 6979 for (unsigned i = 1; i < NumMemOps; i++) 6980 if (MemOps[i].bitsGT(LargestVT)) 6981 LargestVT = MemOps[i]; 6982 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6983 6984 // Prepare AAInfo for loads/stores after lowering this memset. 6985 AAMDNodes NewAAInfo = AAInfo; 6986 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6987 6988 for (unsigned i = 0; i < NumMemOps; i++) { 6989 EVT VT = MemOps[i]; 6990 unsigned VTSize = VT.getSizeInBits() / 8; 6991 if (VTSize > Size) { 6992 // Issuing an unaligned load / store pair that overlaps with the previous 6993 // pair. Adjust the offset accordingly. 6994 assert(i == NumMemOps-1 && i != 0); 6995 DstOff -= VTSize - Size; 6996 } 6997 6998 // If this store is smaller than the largest store see whether we can get 6999 // the smaller value for free with a truncate. 7000 SDValue Value = MemSetValue; 7001 if (VT.bitsLT(LargestVT)) { 7002 if (!LargestVT.isVector() && !VT.isVector() && 7003 TLI.isTruncateFree(LargestVT, VT)) 7004 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7005 else 7006 Value = getMemsetValue(Src, VT, DAG, dl); 7007 } 7008 assert(Value.getValueType() == VT && "Value with wrong type."); 7009 SDValue Store = DAG.getStore( 7010 Chain, dl, Value, 7011 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7012 DstPtrInfo.getWithOffset(DstOff), Alignment, 7013 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7014 NewAAInfo); 7015 OutChains.push_back(Store); 7016 DstOff += VT.getSizeInBits() / 8; 7017 Size -= VTSize; 7018 } 7019 7020 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7021 } 7022 7023 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7024 unsigned AS) { 7025 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7026 // pointer operands can be losslessly bitcasted to pointers of address space 0 7027 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7028 report_fatal_error("cannot lower memory intrinsic in address space " + 7029 Twine(AS)); 7030 } 7031 } 7032 7033 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7034 SDValue Src, SDValue Size, Align Alignment, 7035 bool isVol, bool AlwaysInline, bool isTailCall, 7036 MachinePointerInfo DstPtrInfo, 7037 MachinePointerInfo SrcPtrInfo, 7038 const AAMDNodes &AAInfo) { 7039 // Check to see if we should lower the memcpy to loads and stores first. 7040 // For cases within the target-specified limits, this is the best choice. 7041 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7042 if (ConstantSize) { 7043 // Memcpy with size zero? Just return the original chain. 7044 if (ConstantSize->isZero()) 7045 return Chain; 7046 7047 SDValue Result = getMemcpyLoadsAndStores( 7048 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7049 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7050 if (Result.getNode()) 7051 return Result; 7052 } 7053 7054 // Then check to see if we should lower the memcpy with target-specific 7055 // code. If the target chooses to do this, this is the next best. 7056 if (TSI) { 7057 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7058 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7059 DstPtrInfo, SrcPtrInfo); 7060 if (Result.getNode()) 7061 return Result; 7062 } 7063 7064 // If we really need inline code and the target declined to provide it, 7065 // use a (potentially long) sequence of loads and stores. 7066 if (AlwaysInline) { 7067 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7068 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 7069 ConstantSize->getZExtValue(), Alignment, 7070 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 7071 } 7072 7073 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7074 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7075 7076 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7077 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7078 // respect volatile, so they may do things like read or write memory 7079 // beyond the given memory regions. But fixing this isn't easy, and most 7080 // people don't care. 7081 7082 // Emit a library call. 7083 TargetLowering::ArgListTy Args; 7084 TargetLowering::ArgListEntry Entry; 7085 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7086 Entry.Node = Dst; Args.push_back(Entry); 7087 Entry.Node = Src; Args.push_back(Entry); 7088 7089 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7090 Entry.Node = Size; Args.push_back(Entry); 7091 // FIXME: pass in SDLoc 7092 TargetLowering::CallLoweringInfo CLI(*this); 7093 CLI.setDebugLoc(dl) 7094 .setChain(Chain) 7095 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7096 Dst.getValueType().getTypeForEVT(*getContext()), 7097 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7098 TLI->getPointerTy(getDataLayout())), 7099 std::move(Args)) 7100 .setDiscardResult() 7101 .setTailCall(isTailCall); 7102 7103 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7104 return CallResult.second; 7105 } 7106 7107 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7108 SDValue Dst, unsigned DstAlign, 7109 SDValue Src, unsigned SrcAlign, 7110 SDValue Size, Type *SizeTy, 7111 unsigned ElemSz, bool isTailCall, 7112 MachinePointerInfo DstPtrInfo, 7113 MachinePointerInfo SrcPtrInfo) { 7114 // Emit a library call. 7115 TargetLowering::ArgListTy Args; 7116 TargetLowering::ArgListEntry Entry; 7117 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7118 Entry.Node = Dst; 7119 Args.push_back(Entry); 7120 7121 Entry.Node = Src; 7122 Args.push_back(Entry); 7123 7124 Entry.Ty = SizeTy; 7125 Entry.Node = Size; 7126 Args.push_back(Entry); 7127 7128 RTLIB::Libcall LibraryCall = 7129 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7130 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7131 report_fatal_error("Unsupported element size"); 7132 7133 TargetLowering::CallLoweringInfo CLI(*this); 7134 CLI.setDebugLoc(dl) 7135 .setChain(Chain) 7136 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7137 Type::getVoidTy(*getContext()), 7138 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7139 TLI->getPointerTy(getDataLayout())), 7140 std::move(Args)) 7141 .setDiscardResult() 7142 .setTailCall(isTailCall); 7143 7144 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7145 return CallResult.second; 7146 } 7147 7148 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7149 SDValue Src, SDValue Size, Align Alignment, 7150 bool isVol, bool isTailCall, 7151 MachinePointerInfo DstPtrInfo, 7152 MachinePointerInfo SrcPtrInfo, 7153 const AAMDNodes &AAInfo) { 7154 // Check to see if we should lower the memmove to loads and stores first. 7155 // For cases within the target-specified limits, this is the best choice. 7156 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7157 if (ConstantSize) { 7158 // Memmove with size zero? Just return the original chain. 7159 if (ConstantSize->isZero()) 7160 return Chain; 7161 7162 SDValue Result = getMemmoveLoadsAndStores( 7163 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7164 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7165 if (Result.getNode()) 7166 return Result; 7167 } 7168 7169 // Then check to see if we should lower the memmove with target-specific 7170 // code. If the target chooses to do this, this is the next best. 7171 if (TSI) { 7172 SDValue Result = 7173 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7174 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7175 if (Result.getNode()) 7176 return Result; 7177 } 7178 7179 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7180 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7181 7182 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7183 // not be safe. See memcpy above for more details. 7184 7185 // Emit a library call. 7186 TargetLowering::ArgListTy Args; 7187 TargetLowering::ArgListEntry Entry; 7188 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7189 Entry.Node = Dst; Args.push_back(Entry); 7190 Entry.Node = Src; Args.push_back(Entry); 7191 7192 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7193 Entry.Node = Size; Args.push_back(Entry); 7194 // FIXME: pass in SDLoc 7195 TargetLowering::CallLoweringInfo CLI(*this); 7196 CLI.setDebugLoc(dl) 7197 .setChain(Chain) 7198 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7199 Dst.getValueType().getTypeForEVT(*getContext()), 7200 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7201 TLI->getPointerTy(getDataLayout())), 7202 std::move(Args)) 7203 .setDiscardResult() 7204 .setTailCall(isTailCall); 7205 7206 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7207 return CallResult.second; 7208 } 7209 7210 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7211 SDValue Dst, unsigned DstAlign, 7212 SDValue Src, unsigned SrcAlign, 7213 SDValue Size, Type *SizeTy, 7214 unsigned ElemSz, bool isTailCall, 7215 MachinePointerInfo DstPtrInfo, 7216 MachinePointerInfo SrcPtrInfo) { 7217 // Emit a library call. 7218 TargetLowering::ArgListTy Args; 7219 TargetLowering::ArgListEntry Entry; 7220 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7221 Entry.Node = Dst; 7222 Args.push_back(Entry); 7223 7224 Entry.Node = Src; 7225 Args.push_back(Entry); 7226 7227 Entry.Ty = SizeTy; 7228 Entry.Node = Size; 7229 Args.push_back(Entry); 7230 7231 RTLIB::Libcall LibraryCall = 7232 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7233 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7234 report_fatal_error("Unsupported element size"); 7235 7236 TargetLowering::CallLoweringInfo CLI(*this); 7237 CLI.setDebugLoc(dl) 7238 .setChain(Chain) 7239 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7240 Type::getVoidTy(*getContext()), 7241 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7242 TLI->getPointerTy(getDataLayout())), 7243 std::move(Args)) 7244 .setDiscardResult() 7245 .setTailCall(isTailCall); 7246 7247 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7248 return CallResult.second; 7249 } 7250 7251 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7252 SDValue Src, SDValue Size, Align Alignment, 7253 bool isVol, bool isTailCall, 7254 MachinePointerInfo DstPtrInfo, 7255 const AAMDNodes &AAInfo) { 7256 // Check to see if we should lower the memset to stores first. 7257 // For cases within the target-specified limits, this is the best choice. 7258 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7259 if (ConstantSize) { 7260 // Memset with size zero? Just return the original chain. 7261 if (ConstantSize->isZero()) 7262 return Chain; 7263 7264 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7265 ConstantSize->getZExtValue(), Alignment, 7266 isVol, DstPtrInfo, AAInfo); 7267 7268 if (Result.getNode()) 7269 return Result; 7270 } 7271 7272 // Then check to see if we should lower the memset with target-specific 7273 // code. If the target chooses to do this, this is the next best. 7274 if (TSI) { 7275 SDValue Result = TSI->EmitTargetCodeForMemset( 7276 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7277 if (Result.getNode()) 7278 return Result; 7279 } 7280 7281 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7282 7283 // Emit a library call. 7284 TargetLowering::ArgListTy Args; 7285 TargetLowering::ArgListEntry Entry; 7286 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7287 Args.push_back(Entry); 7288 Entry.Node = Src; 7289 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7290 Args.push_back(Entry); 7291 Entry.Node = Size; 7292 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7293 Args.push_back(Entry); 7294 7295 // FIXME: pass in SDLoc 7296 TargetLowering::CallLoweringInfo CLI(*this); 7297 CLI.setDebugLoc(dl) 7298 .setChain(Chain) 7299 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7300 Dst.getValueType().getTypeForEVT(*getContext()), 7301 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7302 TLI->getPointerTy(getDataLayout())), 7303 std::move(Args)) 7304 .setDiscardResult() 7305 .setTailCall(isTailCall); 7306 7307 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7308 return CallResult.second; 7309 } 7310 7311 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7312 SDValue Dst, unsigned DstAlign, 7313 SDValue Value, SDValue Size, Type *SizeTy, 7314 unsigned ElemSz, bool isTailCall, 7315 MachinePointerInfo DstPtrInfo) { 7316 // Emit a library call. 7317 TargetLowering::ArgListTy Args; 7318 TargetLowering::ArgListEntry Entry; 7319 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7320 Entry.Node = Dst; 7321 Args.push_back(Entry); 7322 7323 Entry.Ty = Type::getInt8Ty(*getContext()); 7324 Entry.Node = Value; 7325 Args.push_back(Entry); 7326 7327 Entry.Ty = SizeTy; 7328 Entry.Node = Size; 7329 Args.push_back(Entry); 7330 7331 RTLIB::Libcall LibraryCall = 7332 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7333 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7334 report_fatal_error("Unsupported element size"); 7335 7336 TargetLowering::CallLoweringInfo CLI(*this); 7337 CLI.setDebugLoc(dl) 7338 .setChain(Chain) 7339 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7340 Type::getVoidTy(*getContext()), 7341 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7342 TLI->getPointerTy(getDataLayout())), 7343 std::move(Args)) 7344 .setDiscardResult() 7345 .setTailCall(isTailCall); 7346 7347 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7348 return CallResult.second; 7349 } 7350 7351 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7352 SDVTList VTList, ArrayRef<SDValue> Ops, 7353 MachineMemOperand *MMO) { 7354 FoldingSetNodeID ID; 7355 ID.AddInteger(MemVT.getRawBits()); 7356 AddNodeIDNode(ID, Opcode, VTList, Ops); 7357 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7358 ID.AddInteger(MMO->getFlags()); 7359 void* IP = nullptr; 7360 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7361 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7362 return SDValue(E, 0); 7363 } 7364 7365 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7366 VTList, MemVT, MMO); 7367 createOperands(N, Ops); 7368 7369 CSEMap.InsertNode(N, IP); 7370 InsertNode(N); 7371 return SDValue(N, 0); 7372 } 7373 7374 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7375 EVT MemVT, SDVTList VTs, SDValue Chain, 7376 SDValue Ptr, SDValue Cmp, SDValue Swp, 7377 MachineMemOperand *MMO) { 7378 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7379 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7380 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7381 7382 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7383 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7384 } 7385 7386 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7387 SDValue Chain, SDValue Ptr, SDValue Val, 7388 MachineMemOperand *MMO) { 7389 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7390 Opcode == ISD::ATOMIC_LOAD_SUB || 7391 Opcode == ISD::ATOMIC_LOAD_AND || 7392 Opcode == ISD::ATOMIC_LOAD_CLR || 7393 Opcode == ISD::ATOMIC_LOAD_OR || 7394 Opcode == ISD::ATOMIC_LOAD_XOR || 7395 Opcode == ISD::ATOMIC_LOAD_NAND || 7396 Opcode == ISD::ATOMIC_LOAD_MIN || 7397 Opcode == ISD::ATOMIC_LOAD_MAX || 7398 Opcode == ISD::ATOMIC_LOAD_UMIN || 7399 Opcode == ISD::ATOMIC_LOAD_UMAX || 7400 Opcode == ISD::ATOMIC_LOAD_FADD || 7401 Opcode == ISD::ATOMIC_LOAD_FSUB || 7402 Opcode == ISD::ATOMIC_SWAP || 7403 Opcode == ISD::ATOMIC_STORE) && 7404 "Invalid Atomic Op"); 7405 7406 EVT VT = Val.getValueType(); 7407 7408 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7409 getVTList(VT, MVT::Other); 7410 SDValue Ops[] = {Chain, Ptr, Val}; 7411 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7412 } 7413 7414 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7415 EVT VT, SDValue Chain, SDValue Ptr, 7416 MachineMemOperand *MMO) { 7417 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7418 7419 SDVTList VTs = getVTList(VT, MVT::Other); 7420 SDValue Ops[] = {Chain, Ptr}; 7421 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7422 } 7423 7424 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7425 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7426 if (Ops.size() == 1) 7427 return Ops[0]; 7428 7429 SmallVector<EVT, 4> VTs; 7430 VTs.reserve(Ops.size()); 7431 for (const SDValue &Op : Ops) 7432 VTs.push_back(Op.getValueType()); 7433 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7434 } 7435 7436 SDValue SelectionDAG::getMemIntrinsicNode( 7437 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7438 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7439 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7440 if (!Size && MemVT.isScalableVector()) 7441 Size = MemoryLocation::UnknownSize; 7442 else if (!Size) 7443 Size = MemVT.getStoreSize(); 7444 7445 MachineFunction &MF = getMachineFunction(); 7446 MachineMemOperand *MMO = 7447 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7448 7449 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7450 } 7451 7452 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7453 SDVTList VTList, 7454 ArrayRef<SDValue> Ops, EVT MemVT, 7455 MachineMemOperand *MMO) { 7456 assert((Opcode == ISD::INTRINSIC_VOID || 7457 Opcode == ISD::INTRINSIC_W_CHAIN || 7458 Opcode == ISD::PREFETCH || 7459 ((int)Opcode <= std::numeric_limits<int>::max() && 7460 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7461 "Opcode is not a memory-accessing opcode!"); 7462 7463 // Memoize the node unless it returns a flag. 7464 MemIntrinsicSDNode *N; 7465 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7466 FoldingSetNodeID ID; 7467 AddNodeIDNode(ID, Opcode, VTList, Ops); 7468 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7469 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7470 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7471 ID.AddInteger(MMO->getFlags()); 7472 void *IP = nullptr; 7473 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7474 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7475 return SDValue(E, 0); 7476 } 7477 7478 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7479 VTList, MemVT, MMO); 7480 createOperands(N, Ops); 7481 7482 CSEMap.InsertNode(N, IP); 7483 } else { 7484 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7485 VTList, MemVT, MMO); 7486 createOperands(N, Ops); 7487 } 7488 InsertNode(N); 7489 SDValue V(N, 0); 7490 NewSDValueDbgMsg(V, "Creating new node: ", this); 7491 return V; 7492 } 7493 7494 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7495 SDValue Chain, int FrameIndex, 7496 int64_t Size, int64_t Offset) { 7497 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7498 const auto VTs = getVTList(MVT::Other); 7499 SDValue Ops[2] = { 7500 Chain, 7501 getFrameIndex(FrameIndex, 7502 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7503 true)}; 7504 7505 FoldingSetNodeID ID; 7506 AddNodeIDNode(ID, Opcode, VTs, Ops); 7507 ID.AddInteger(FrameIndex); 7508 ID.AddInteger(Size); 7509 ID.AddInteger(Offset); 7510 void *IP = nullptr; 7511 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7512 return SDValue(E, 0); 7513 7514 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7515 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7516 createOperands(N, Ops); 7517 CSEMap.InsertNode(N, IP); 7518 InsertNode(N); 7519 SDValue V(N, 0); 7520 NewSDValueDbgMsg(V, "Creating new node: ", this); 7521 return V; 7522 } 7523 7524 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7525 uint64_t Guid, uint64_t Index, 7526 uint32_t Attr) { 7527 const unsigned Opcode = ISD::PSEUDO_PROBE; 7528 const auto VTs = getVTList(MVT::Other); 7529 SDValue Ops[] = {Chain}; 7530 FoldingSetNodeID ID; 7531 AddNodeIDNode(ID, Opcode, VTs, Ops); 7532 ID.AddInteger(Guid); 7533 ID.AddInteger(Index); 7534 void *IP = nullptr; 7535 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7536 return SDValue(E, 0); 7537 7538 auto *N = newSDNode<PseudoProbeSDNode>( 7539 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7540 createOperands(N, Ops); 7541 CSEMap.InsertNode(N, IP); 7542 InsertNode(N); 7543 SDValue V(N, 0); 7544 NewSDValueDbgMsg(V, "Creating new node: ", this); 7545 return V; 7546 } 7547 7548 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7549 /// MachinePointerInfo record from it. This is particularly useful because the 7550 /// code generator has many cases where it doesn't bother passing in a 7551 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7552 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7553 SelectionDAG &DAG, SDValue Ptr, 7554 int64_t Offset = 0) { 7555 // If this is FI+Offset, we can model it. 7556 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7557 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7558 FI->getIndex(), Offset); 7559 7560 // If this is (FI+Offset1)+Offset2, we can model it. 7561 if (Ptr.getOpcode() != ISD::ADD || 7562 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7563 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7564 return Info; 7565 7566 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7567 return MachinePointerInfo::getFixedStack( 7568 DAG.getMachineFunction(), FI, 7569 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7570 } 7571 7572 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7573 /// MachinePointerInfo record from it. This is particularly useful because the 7574 /// code generator has many cases where it doesn't bother passing in a 7575 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7576 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7577 SelectionDAG &DAG, SDValue Ptr, 7578 SDValue OffsetOp) { 7579 // If the 'Offset' value isn't a constant, we can't handle this. 7580 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7581 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7582 if (OffsetOp.isUndef()) 7583 return InferPointerInfo(Info, DAG, Ptr); 7584 return Info; 7585 } 7586 7587 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7588 EVT VT, const SDLoc &dl, SDValue Chain, 7589 SDValue Ptr, SDValue Offset, 7590 MachinePointerInfo PtrInfo, EVT MemVT, 7591 Align Alignment, 7592 MachineMemOperand::Flags MMOFlags, 7593 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7594 assert(Chain.getValueType() == MVT::Other && 7595 "Invalid chain type"); 7596 7597 MMOFlags |= MachineMemOperand::MOLoad; 7598 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7599 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7600 // clients. 7601 if (PtrInfo.V.isNull()) 7602 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7603 7604 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7605 MachineFunction &MF = getMachineFunction(); 7606 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7607 Alignment, AAInfo, Ranges); 7608 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7609 } 7610 7611 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7612 EVT VT, const SDLoc &dl, SDValue Chain, 7613 SDValue Ptr, SDValue Offset, EVT MemVT, 7614 MachineMemOperand *MMO) { 7615 if (VT == MemVT) { 7616 ExtType = ISD::NON_EXTLOAD; 7617 } else if (ExtType == ISD::NON_EXTLOAD) { 7618 assert(VT == MemVT && "Non-extending load from different memory type!"); 7619 } else { 7620 // Extending load. 7621 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7622 "Should only be an extending load, not truncating!"); 7623 assert(VT.isInteger() == MemVT.isInteger() && 7624 "Cannot convert from FP to Int or Int -> FP!"); 7625 assert(VT.isVector() == MemVT.isVector() && 7626 "Cannot use an ext load to convert to or from a vector!"); 7627 assert((!VT.isVector() || 7628 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7629 "Cannot use an ext load to change the number of vector elements!"); 7630 } 7631 7632 bool Indexed = AM != ISD::UNINDEXED; 7633 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7634 7635 SDVTList VTs = Indexed ? 7636 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7637 SDValue Ops[] = { Chain, Ptr, Offset }; 7638 FoldingSetNodeID ID; 7639 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7640 ID.AddInteger(MemVT.getRawBits()); 7641 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7642 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7643 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7644 ID.AddInteger(MMO->getFlags()); 7645 void *IP = nullptr; 7646 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7647 cast<LoadSDNode>(E)->refineAlignment(MMO); 7648 return SDValue(E, 0); 7649 } 7650 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7651 ExtType, MemVT, MMO); 7652 createOperands(N, Ops); 7653 7654 CSEMap.InsertNode(N, IP); 7655 InsertNode(N); 7656 SDValue V(N, 0); 7657 NewSDValueDbgMsg(V, "Creating new node: ", this); 7658 return V; 7659 } 7660 7661 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7662 SDValue Ptr, MachinePointerInfo PtrInfo, 7663 MaybeAlign Alignment, 7664 MachineMemOperand::Flags MMOFlags, 7665 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7666 SDValue Undef = getUNDEF(Ptr.getValueType()); 7667 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7668 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7669 } 7670 7671 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7672 SDValue Ptr, MachineMemOperand *MMO) { 7673 SDValue Undef = getUNDEF(Ptr.getValueType()); 7674 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7675 VT, MMO); 7676 } 7677 7678 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7679 EVT VT, SDValue Chain, SDValue Ptr, 7680 MachinePointerInfo PtrInfo, EVT MemVT, 7681 MaybeAlign Alignment, 7682 MachineMemOperand::Flags MMOFlags, 7683 const AAMDNodes &AAInfo) { 7684 SDValue Undef = getUNDEF(Ptr.getValueType()); 7685 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7686 MemVT, Alignment, MMOFlags, AAInfo); 7687 } 7688 7689 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7690 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7691 MachineMemOperand *MMO) { 7692 SDValue Undef = getUNDEF(Ptr.getValueType()); 7693 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7694 MemVT, MMO); 7695 } 7696 7697 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7698 SDValue Base, SDValue Offset, 7699 ISD::MemIndexedMode AM) { 7700 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7701 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7702 // Don't propagate the invariant or dereferenceable flags. 7703 auto MMOFlags = 7704 LD->getMemOperand()->getFlags() & 7705 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7706 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7707 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7708 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7709 } 7710 7711 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7712 SDValue Ptr, MachinePointerInfo PtrInfo, 7713 Align Alignment, 7714 MachineMemOperand::Flags MMOFlags, 7715 const AAMDNodes &AAInfo) { 7716 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7717 7718 MMOFlags |= MachineMemOperand::MOStore; 7719 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7720 7721 if (PtrInfo.V.isNull()) 7722 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7723 7724 MachineFunction &MF = getMachineFunction(); 7725 uint64_t Size = 7726 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7727 MachineMemOperand *MMO = 7728 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7729 return getStore(Chain, dl, Val, Ptr, MMO); 7730 } 7731 7732 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7733 SDValue Ptr, MachineMemOperand *MMO) { 7734 assert(Chain.getValueType() == MVT::Other && 7735 "Invalid chain type"); 7736 EVT VT = Val.getValueType(); 7737 SDVTList VTs = getVTList(MVT::Other); 7738 SDValue Undef = getUNDEF(Ptr.getValueType()); 7739 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7740 FoldingSetNodeID ID; 7741 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7742 ID.AddInteger(VT.getRawBits()); 7743 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7744 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7745 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7746 ID.AddInteger(MMO->getFlags()); 7747 void *IP = nullptr; 7748 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7749 cast<StoreSDNode>(E)->refineAlignment(MMO); 7750 return SDValue(E, 0); 7751 } 7752 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7753 ISD::UNINDEXED, false, VT, MMO); 7754 createOperands(N, Ops); 7755 7756 CSEMap.InsertNode(N, IP); 7757 InsertNode(N); 7758 SDValue V(N, 0); 7759 NewSDValueDbgMsg(V, "Creating new node: ", this); 7760 return V; 7761 } 7762 7763 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7764 SDValue Ptr, MachinePointerInfo PtrInfo, 7765 EVT SVT, Align Alignment, 7766 MachineMemOperand::Flags MMOFlags, 7767 const AAMDNodes &AAInfo) { 7768 assert(Chain.getValueType() == MVT::Other && 7769 "Invalid chain type"); 7770 7771 MMOFlags |= MachineMemOperand::MOStore; 7772 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7773 7774 if (PtrInfo.V.isNull()) 7775 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7776 7777 MachineFunction &MF = getMachineFunction(); 7778 MachineMemOperand *MMO = MF.getMachineMemOperand( 7779 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7780 Alignment, AAInfo); 7781 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7782 } 7783 7784 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7785 SDValue Ptr, EVT SVT, 7786 MachineMemOperand *MMO) { 7787 EVT VT = Val.getValueType(); 7788 7789 assert(Chain.getValueType() == MVT::Other && 7790 "Invalid chain type"); 7791 if (VT == SVT) 7792 return getStore(Chain, dl, Val, Ptr, MMO); 7793 7794 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7795 "Should only be a truncating store, not extending!"); 7796 assert(VT.isInteger() == SVT.isInteger() && 7797 "Can't do FP-INT conversion!"); 7798 assert(VT.isVector() == SVT.isVector() && 7799 "Cannot use trunc store to convert to or from a vector!"); 7800 assert((!VT.isVector() || 7801 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7802 "Cannot use trunc store to change the number of vector elements!"); 7803 7804 SDVTList VTs = getVTList(MVT::Other); 7805 SDValue Undef = getUNDEF(Ptr.getValueType()); 7806 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7807 FoldingSetNodeID ID; 7808 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7809 ID.AddInteger(SVT.getRawBits()); 7810 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7811 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7812 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7813 ID.AddInteger(MMO->getFlags()); 7814 void *IP = nullptr; 7815 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7816 cast<StoreSDNode>(E)->refineAlignment(MMO); 7817 return SDValue(E, 0); 7818 } 7819 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7820 ISD::UNINDEXED, true, SVT, MMO); 7821 createOperands(N, Ops); 7822 7823 CSEMap.InsertNode(N, IP); 7824 InsertNode(N); 7825 SDValue V(N, 0); 7826 NewSDValueDbgMsg(V, "Creating new node: ", this); 7827 return V; 7828 } 7829 7830 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7831 SDValue Base, SDValue Offset, 7832 ISD::MemIndexedMode AM) { 7833 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7834 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7835 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7836 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7837 FoldingSetNodeID ID; 7838 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7839 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7840 ID.AddInteger(ST->getRawSubclassData()); 7841 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7842 ID.AddInteger(ST->getMemOperand()->getFlags()); 7843 void *IP = nullptr; 7844 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7845 return SDValue(E, 0); 7846 7847 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7848 ST->isTruncatingStore(), ST->getMemoryVT(), 7849 ST->getMemOperand()); 7850 createOperands(N, Ops); 7851 7852 CSEMap.InsertNode(N, IP); 7853 InsertNode(N); 7854 SDValue V(N, 0); 7855 NewSDValueDbgMsg(V, "Creating new node: ", this); 7856 return V; 7857 } 7858 7859 SDValue SelectionDAG::getLoadVP( 7860 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7861 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7862 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7863 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7864 const MDNode *Ranges, bool IsExpanding) { 7865 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7866 7867 MMOFlags |= MachineMemOperand::MOLoad; 7868 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7869 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7870 // clients. 7871 if (PtrInfo.V.isNull()) 7872 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7873 7874 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7875 MachineFunction &MF = getMachineFunction(); 7876 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7877 Alignment, AAInfo, Ranges); 7878 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7879 MMO, IsExpanding); 7880 } 7881 7882 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7883 ISD::LoadExtType ExtType, EVT VT, 7884 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7885 SDValue Offset, SDValue Mask, SDValue EVL, 7886 EVT MemVT, MachineMemOperand *MMO, 7887 bool IsExpanding) { 7888 bool Indexed = AM != ISD::UNINDEXED; 7889 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7890 7891 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7892 : getVTList(VT, MVT::Other); 7893 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7894 FoldingSetNodeID ID; 7895 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7896 ID.AddInteger(VT.getRawBits()); 7897 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7898 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7899 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7900 ID.AddInteger(MMO->getFlags()); 7901 void *IP = nullptr; 7902 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7903 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7904 return SDValue(E, 0); 7905 } 7906 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7907 ExtType, IsExpanding, MemVT, MMO); 7908 createOperands(N, Ops); 7909 7910 CSEMap.InsertNode(N, IP); 7911 InsertNode(N); 7912 SDValue V(N, 0); 7913 NewSDValueDbgMsg(V, "Creating new node: ", this); 7914 return V; 7915 } 7916 7917 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7918 SDValue Ptr, SDValue Mask, SDValue EVL, 7919 MachinePointerInfo PtrInfo, 7920 MaybeAlign Alignment, 7921 MachineMemOperand::Flags MMOFlags, 7922 const AAMDNodes &AAInfo, const MDNode *Ranges, 7923 bool IsExpanding) { 7924 SDValue Undef = getUNDEF(Ptr.getValueType()); 7925 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7926 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7927 IsExpanding); 7928 } 7929 7930 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7931 SDValue Ptr, SDValue Mask, SDValue EVL, 7932 MachineMemOperand *MMO, bool IsExpanding) { 7933 SDValue Undef = getUNDEF(Ptr.getValueType()); 7934 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7935 Mask, EVL, VT, MMO, IsExpanding); 7936 } 7937 7938 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7939 EVT VT, SDValue Chain, SDValue Ptr, 7940 SDValue Mask, SDValue EVL, 7941 MachinePointerInfo PtrInfo, EVT MemVT, 7942 MaybeAlign Alignment, 7943 MachineMemOperand::Flags MMOFlags, 7944 const AAMDNodes &AAInfo, bool IsExpanding) { 7945 SDValue Undef = getUNDEF(Ptr.getValueType()); 7946 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7947 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7948 IsExpanding); 7949 } 7950 7951 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7952 EVT VT, SDValue Chain, SDValue Ptr, 7953 SDValue Mask, SDValue EVL, EVT MemVT, 7954 MachineMemOperand *MMO, bool IsExpanding) { 7955 SDValue Undef = getUNDEF(Ptr.getValueType()); 7956 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7957 EVL, MemVT, MMO, IsExpanding); 7958 } 7959 7960 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7961 SDValue Base, SDValue Offset, 7962 ISD::MemIndexedMode AM) { 7963 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7964 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7965 // Don't propagate the invariant or dereferenceable flags. 7966 auto MMOFlags = 7967 LD->getMemOperand()->getFlags() & 7968 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7969 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7970 LD->getChain(), Base, Offset, LD->getMask(), 7971 LD->getVectorLength(), LD->getPointerInfo(), 7972 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7973 nullptr, LD->isExpandingLoad()); 7974 } 7975 7976 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7977 SDValue Ptr, SDValue Offset, SDValue Mask, 7978 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 7979 ISD::MemIndexedMode AM, bool IsTruncating, 7980 bool IsCompressing) { 7981 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7982 bool Indexed = AM != ISD::UNINDEXED; 7983 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 7984 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 7985 : getVTList(MVT::Other); 7986 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 7987 FoldingSetNodeID ID; 7988 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7989 ID.AddInteger(MemVT.getRawBits()); 7990 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7991 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7992 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7993 ID.AddInteger(MMO->getFlags()); 7994 void *IP = nullptr; 7995 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7996 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7997 return SDValue(E, 0); 7998 } 7999 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8000 IsTruncating, IsCompressing, MemVT, MMO); 8001 createOperands(N, Ops); 8002 8003 CSEMap.InsertNode(N, IP); 8004 InsertNode(N); 8005 SDValue V(N, 0); 8006 NewSDValueDbgMsg(V, "Creating new node: ", this); 8007 return V; 8008 } 8009 8010 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8011 SDValue Val, SDValue Ptr, SDValue Mask, 8012 SDValue EVL, MachinePointerInfo PtrInfo, 8013 EVT SVT, Align Alignment, 8014 MachineMemOperand::Flags MMOFlags, 8015 const AAMDNodes &AAInfo, 8016 bool IsCompressing) { 8017 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8018 8019 MMOFlags |= MachineMemOperand::MOStore; 8020 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8021 8022 if (PtrInfo.V.isNull()) 8023 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8024 8025 MachineFunction &MF = getMachineFunction(); 8026 MachineMemOperand *MMO = MF.getMachineMemOperand( 8027 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8028 Alignment, AAInfo); 8029 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8030 IsCompressing); 8031 } 8032 8033 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8034 SDValue Val, SDValue Ptr, SDValue Mask, 8035 SDValue EVL, EVT SVT, 8036 MachineMemOperand *MMO, 8037 bool IsCompressing) { 8038 EVT VT = Val.getValueType(); 8039 8040 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8041 if (VT == SVT) 8042 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8043 EVL, VT, MMO, ISD::UNINDEXED, 8044 /*IsTruncating*/ false, IsCompressing); 8045 8046 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8047 "Should only be a truncating store, not extending!"); 8048 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8049 assert(VT.isVector() == SVT.isVector() && 8050 "Cannot use trunc store to convert to or from a vector!"); 8051 assert((!VT.isVector() || 8052 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8053 "Cannot use trunc store to change the number of vector elements!"); 8054 8055 SDVTList VTs = getVTList(MVT::Other); 8056 SDValue Undef = getUNDEF(Ptr.getValueType()); 8057 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8058 FoldingSetNodeID ID; 8059 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8060 ID.AddInteger(SVT.getRawBits()); 8061 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8062 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8063 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8064 ID.AddInteger(MMO->getFlags()); 8065 void *IP = nullptr; 8066 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8067 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8068 return SDValue(E, 0); 8069 } 8070 auto *N = 8071 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8072 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8073 createOperands(N, Ops); 8074 8075 CSEMap.InsertNode(N, IP); 8076 InsertNode(N); 8077 SDValue V(N, 0); 8078 NewSDValueDbgMsg(V, "Creating new node: ", this); 8079 return V; 8080 } 8081 8082 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8083 SDValue Base, SDValue Offset, 8084 ISD::MemIndexedMode AM) { 8085 auto *ST = cast<VPStoreSDNode>(OrigStore); 8086 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8087 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8088 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8089 Offset, ST->getMask(), ST->getVectorLength()}; 8090 FoldingSetNodeID ID; 8091 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8092 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8093 ID.AddInteger(ST->getRawSubclassData()); 8094 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8095 ID.AddInteger(ST->getMemOperand()->getFlags()); 8096 void *IP = nullptr; 8097 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8098 return SDValue(E, 0); 8099 8100 auto *N = newSDNode<VPStoreSDNode>( 8101 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8102 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8103 createOperands(N, Ops); 8104 8105 CSEMap.InsertNode(N, IP); 8106 InsertNode(N); 8107 SDValue V(N, 0); 8108 NewSDValueDbgMsg(V, "Creating new node: ", this); 8109 return V; 8110 } 8111 8112 SDValue SelectionDAG::getStridedLoadVP( 8113 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8114 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8115 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8116 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8117 const MDNode *Ranges, bool IsExpanding) { 8118 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8119 8120 MMOFlags |= MachineMemOperand::MOLoad; 8121 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8122 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8123 // clients. 8124 if (PtrInfo.V.isNull()) 8125 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8126 8127 uint64_t Size = MemoryLocation::UnknownSize; 8128 MachineFunction &MF = getMachineFunction(); 8129 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8130 Alignment, AAInfo, Ranges); 8131 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8132 EVL, MemVT, MMO, IsExpanding); 8133 } 8134 8135 SDValue SelectionDAG::getStridedLoadVP( 8136 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8137 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8138 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8139 bool Indexed = AM != ISD::UNINDEXED; 8140 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8141 8142 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8143 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8144 : getVTList(VT, MVT::Other); 8145 FoldingSetNodeID ID; 8146 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8147 ID.AddInteger(VT.getRawBits()); 8148 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8149 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8150 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8151 8152 void *IP = nullptr; 8153 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8154 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8155 return SDValue(E, 0); 8156 } 8157 8158 auto *N = 8159 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8160 ExtType, IsExpanding, MemVT, MMO); 8161 createOperands(N, Ops); 8162 CSEMap.InsertNode(N, IP); 8163 InsertNode(N); 8164 SDValue V(N, 0); 8165 NewSDValueDbgMsg(V, "Creating new node: ", this); 8166 return V; 8167 } 8168 8169 SDValue SelectionDAG::getStridedLoadVP( 8170 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8171 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8172 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8173 const MDNode *Ranges, bool IsExpanding) { 8174 SDValue Undef = getUNDEF(Ptr.getValueType()); 8175 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8176 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8177 MMOFlags, AAInfo, Ranges, IsExpanding); 8178 } 8179 8180 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8181 SDValue Ptr, SDValue Stride, 8182 SDValue Mask, SDValue EVL, 8183 MachineMemOperand *MMO, 8184 bool IsExpanding) { 8185 SDValue Undef = getUNDEF(Ptr.getValueType()); 8186 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8187 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8188 } 8189 8190 SDValue SelectionDAG::getExtStridedLoadVP( 8191 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8192 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8193 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8194 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8195 bool IsExpanding) { 8196 SDValue Undef = getUNDEF(Ptr.getValueType()); 8197 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8198 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8199 MMOFlags, AAInfo, nullptr, IsExpanding); 8200 } 8201 8202 SDValue SelectionDAG::getExtStridedLoadVP( 8203 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8204 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8205 MachineMemOperand *MMO, bool IsExpanding) { 8206 SDValue Undef = getUNDEF(Ptr.getValueType()); 8207 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8208 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8209 } 8210 8211 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8212 SDValue Base, SDValue Offset, 8213 ISD::MemIndexedMode AM) { 8214 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8215 assert(SLD->getOffset().isUndef() && 8216 "Strided load is already a indexed load!"); 8217 // Don't propagate the invariant or dereferenceable flags. 8218 auto MMOFlags = 8219 SLD->getMemOperand()->getFlags() & 8220 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8221 return getStridedLoadVP( 8222 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8223 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8224 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8225 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8226 } 8227 8228 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8229 SDValue Val, SDValue Ptr, 8230 SDValue Offset, SDValue Stride, 8231 SDValue Mask, SDValue EVL, EVT MemVT, 8232 MachineMemOperand *MMO, 8233 ISD::MemIndexedMode AM, 8234 bool IsTruncating, bool IsCompressing) { 8235 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8236 bool Indexed = AM != ISD::UNINDEXED; 8237 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8238 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8239 : getVTList(MVT::Other); 8240 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8241 FoldingSetNodeID ID; 8242 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8243 ID.AddInteger(MemVT.getRawBits()); 8244 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8245 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8246 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8247 void *IP = nullptr; 8248 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8249 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8250 return SDValue(E, 0); 8251 } 8252 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8253 VTs, AM, IsTruncating, 8254 IsCompressing, MemVT, MMO); 8255 createOperands(N, Ops); 8256 8257 CSEMap.InsertNode(N, IP); 8258 InsertNode(N); 8259 SDValue V(N, 0); 8260 NewSDValueDbgMsg(V, "Creating new node: ", this); 8261 return V; 8262 } 8263 8264 SDValue SelectionDAG::getTruncStridedStoreVP( 8265 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8266 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8267 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8268 bool IsCompressing) { 8269 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8270 8271 MMOFlags |= MachineMemOperand::MOStore; 8272 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8273 8274 if (PtrInfo.V.isNull()) 8275 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8276 8277 MachineFunction &MF = getMachineFunction(); 8278 MachineMemOperand *MMO = MF.getMachineMemOperand( 8279 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8280 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8281 MMO, IsCompressing); 8282 } 8283 8284 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8285 SDValue Val, SDValue Ptr, 8286 SDValue Stride, SDValue Mask, 8287 SDValue EVL, EVT SVT, 8288 MachineMemOperand *MMO, 8289 bool IsCompressing) { 8290 EVT VT = Val.getValueType(); 8291 8292 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8293 if (VT == SVT) 8294 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8295 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8296 /*IsTruncating*/ false, IsCompressing); 8297 8298 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8299 "Should only be a truncating store, not extending!"); 8300 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8301 assert(VT.isVector() == SVT.isVector() && 8302 "Cannot use trunc store to convert to or from a vector!"); 8303 assert((!VT.isVector() || 8304 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8305 "Cannot use trunc store to change the number of vector elements!"); 8306 8307 SDVTList VTs = getVTList(MVT::Other); 8308 SDValue Undef = getUNDEF(Ptr.getValueType()); 8309 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8310 FoldingSetNodeID ID; 8311 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8312 ID.AddInteger(SVT.getRawBits()); 8313 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8314 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8315 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8316 void *IP = nullptr; 8317 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8318 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8319 return SDValue(E, 0); 8320 } 8321 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8322 VTs, ISD::UNINDEXED, true, 8323 IsCompressing, SVT, MMO); 8324 createOperands(N, Ops); 8325 8326 CSEMap.InsertNode(N, IP); 8327 InsertNode(N); 8328 SDValue V(N, 0); 8329 NewSDValueDbgMsg(V, "Creating new node: ", this); 8330 return V; 8331 } 8332 8333 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 8334 const SDLoc &DL, SDValue Base, 8335 SDValue Offset, 8336 ISD::MemIndexedMode AM) { 8337 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 8338 assert(SST->getOffset().isUndef() && 8339 "Strided store is already an indexed store!"); 8340 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8341 SDValue Ops[] = { 8342 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 8343 SST->getMask(), SST->getVectorLength()}; 8344 FoldingSetNodeID ID; 8345 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8346 ID.AddInteger(SST->getMemoryVT().getRawBits()); 8347 ID.AddInteger(SST->getRawSubclassData()); 8348 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 8349 void *IP = nullptr; 8350 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8351 return SDValue(E, 0); 8352 8353 auto *N = newSDNode<VPStridedStoreSDNode>( 8354 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 8355 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 8356 createOperands(N, Ops); 8357 8358 CSEMap.InsertNode(N, IP); 8359 InsertNode(N); 8360 SDValue V(N, 0); 8361 NewSDValueDbgMsg(V, "Creating new node: ", this); 8362 return V; 8363 } 8364 8365 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8366 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8367 ISD::MemIndexType IndexType) { 8368 assert(Ops.size() == 6 && "Incompatible number of operands"); 8369 8370 FoldingSetNodeID ID; 8371 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8372 ID.AddInteger(VT.getRawBits()); 8373 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8374 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8375 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8376 ID.AddInteger(MMO->getFlags()); 8377 void *IP = nullptr; 8378 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8379 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8380 return SDValue(E, 0); 8381 } 8382 8383 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8384 VT, MMO, IndexType); 8385 createOperands(N, Ops); 8386 8387 assert(N->getMask().getValueType().getVectorElementCount() == 8388 N->getValueType(0).getVectorElementCount() && 8389 "Vector width mismatch between mask and data"); 8390 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8391 N->getValueType(0).getVectorElementCount().isScalable() && 8392 "Scalable flags of index and data do not match"); 8393 assert(ElementCount::isKnownGE( 8394 N->getIndex().getValueType().getVectorElementCount(), 8395 N->getValueType(0).getVectorElementCount()) && 8396 "Vector width mismatch between index and data"); 8397 assert(isa<ConstantSDNode>(N->getScale()) && 8398 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8399 "Scale should be a constant power of 2"); 8400 8401 CSEMap.InsertNode(N, IP); 8402 InsertNode(N); 8403 SDValue V(N, 0); 8404 NewSDValueDbgMsg(V, "Creating new node: ", this); 8405 return V; 8406 } 8407 8408 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8409 ArrayRef<SDValue> Ops, 8410 MachineMemOperand *MMO, 8411 ISD::MemIndexType IndexType) { 8412 assert(Ops.size() == 7 && "Incompatible number of operands"); 8413 8414 FoldingSetNodeID ID; 8415 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8416 ID.AddInteger(VT.getRawBits()); 8417 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8418 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8419 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8420 ID.AddInteger(MMO->getFlags()); 8421 void *IP = nullptr; 8422 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8423 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8424 return SDValue(E, 0); 8425 } 8426 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8427 VT, MMO, IndexType); 8428 createOperands(N, Ops); 8429 8430 assert(N->getMask().getValueType().getVectorElementCount() == 8431 N->getValue().getValueType().getVectorElementCount() && 8432 "Vector width mismatch between mask and data"); 8433 assert( 8434 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8435 N->getValue().getValueType().getVectorElementCount().isScalable() && 8436 "Scalable flags of index and data do not match"); 8437 assert(ElementCount::isKnownGE( 8438 N->getIndex().getValueType().getVectorElementCount(), 8439 N->getValue().getValueType().getVectorElementCount()) && 8440 "Vector width mismatch between index and data"); 8441 assert(isa<ConstantSDNode>(N->getScale()) && 8442 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8443 "Scale should be a constant power of 2"); 8444 8445 CSEMap.InsertNode(N, IP); 8446 InsertNode(N); 8447 SDValue V(N, 0); 8448 NewSDValueDbgMsg(V, "Creating new node: ", this); 8449 return V; 8450 } 8451 8452 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8453 SDValue Base, SDValue Offset, SDValue Mask, 8454 SDValue PassThru, EVT MemVT, 8455 MachineMemOperand *MMO, 8456 ISD::MemIndexedMode AM, 8457 ISD::LoadExtType ExtTy, bool isExpanding) { 8458 bool Indexed = AM != ISD::UNINDEXED; 8459 assert((Indexed || Offset.isUndef()) && 8460 "Unindexed masked load with an offset!"); 8461 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8462 : getVTList(VT, MVT::Other); 8463 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8464 FoldingSetNodeID ID; 8465 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8466 ID.AddInteger(MemVT.getRawBits()); 8467 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8468 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8469 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8470 ID.AddInteger(MMO->getFlags()); 8471 void *IP = nullptr; 8472 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8473 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8474 return SDValue(E, 0); 8475 } 8476 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8477 AM, ExtTy, isExpanding, MemVT, MMO); 8478 createOperands(N, Ops); 8479 8480 CSEMap.InsertNode(N, IP); 8481 InsertNode(N); 8482 SDValue V(N, 0); 8483 NewSDValueDbgMsg(V, "Creating new node: ", this); 8484 return V; 8485 } 8486 8487 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8488 SDValue Base, SDValue Offset, 8489 ISD::MemIndexedMode AM) { 8490 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8491 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8492 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8493 Offset, LD->getMask(), LD->getPassThru(), 8494 LD->getMemoryVT(), LD->getMemOperand(), AM, 8495 LD->getExtensionType(), LD->isExpandingLoad()); 8496 } 8497 8498 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8499 SDValue Val, SDValue Base, SDValue Offset, 8500 SDValue Mask, EVT MemVT, 8501 MachineMemOperand *MMO, 8502 ISD::MemIndexedMode AM, bool IsTruncating, 8503 bool IsCompressing) { 8504 assert(Chain.getValueType() == MVT::Other && 8505 "Invalid chain type"); 8506 bool Indexed = AM != ISD::UNINDEXED; 8507 assert((Indexed || Offset.isUndef()) && 8508 "Unindexed masked store with an offset!"); 8509 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8510 : getVTList(MVT::Other); 8511 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8512 FoldingSetNodeID ID; 8513 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8514 ID.AddInteger(MemVT.getRawBits()); 8515 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8516 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8517 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8518 ID.AddInteger(MMO->getFlags()); 8519 void *IP = nullptr; 8520 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8521 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8522 return SDValue(E, 0); 8523 } 8524 auto *N = 8525 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8526 IsTruncating, IsCompressing, MemVT, MMO); 8527 createOperands(N, Ops); 8528 8529 CSEMap.InsertNode(N, IP); 8530 InsertNode(N); 8531 SDValue V(N, 0); 8532 NewSDValueDbgMsg(V, "Creating new node: ", this); 8533 return V; 8534 } 8535 8536 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8537 SDValue Base, SDValue Offset, 8538 ISD::MemIndexedMode AM) { 8539 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8540 assert(ST->getOffset().isUndef() && 8541 "Masked store is already a indexed store!"); 8542 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8543 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8544 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8545 } 8546 8547 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8548 ArrayRef<SDValue> Ops, 8549 MachineMemOperand *MMO, 8550 ISD::MemIndexType IndexType, 8551 ISD::LoadExtType ExtTy) { 8552 assert(Ops.size() == 6 && "Incompatible number of operands"); 8553 8554 FoldingSetNodeID ID; 8555 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8556 ID.AddInteger(MemVT.getRawBits()); 8557 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8558 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8559 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8560 ID.AddInteger(MMO->getFlags()); 8561 void *IP = nullptr; 8562 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8563 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8564 return SDValue(E, 0); 8565 } 8566 8567 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8568 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8569 VTs, MemVT, MMO, IndexType, ExtTy); 8570 createOperands(N, Ops); 8571 8572 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8573 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8574 assert(N->getMask().getValueType().getVectorElementCount() == 8575 N->getValueType(0).getVectorElementCount() && 8576 "Vector width mismatch between mask and data"); 8577 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8578 N->getValueType(0).getVectorElementCount().isScalable() && 8579 "Scalable flags of index and data do not match"); 8580 assert(ElementCount::isKnownGE( 8581 N->getIndex().getValueType().getVectorElementCount(), 8582 N->getValueType(0).getVectorElementCount()) && 8583 "Vector width mismatch between index and data"); 8584 assert(isa<ConstantSDNode>(N->getScale()) && 8585 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8586 "Scale should be a constant power of 2"); 8587 8588 CSEMap.InsertNode(N, IP); 8589 InsertNode(N); 8590 SDValue V(N, 0); 8591 NewSDValueDbgMsg(V, "Creating new node: ", this); 8592 return V; 8593 } 8594 8595 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8596 ArrayRef<SDValue> Ops, 8597 MachineMemOperand *MMO, 8598 ISD::MemIndexType IndexType, 8599 bool IsTrunc) { 8600 assert(Ops.size() == 6 && "Incompatible number of operands"); 8601 8602 FoldingSetNodeID ID; 8603 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8604 ID.AddInteger(MemVT.getRawBits()); 8605 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8606 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8607 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8608 ID.AddInteger(MMO->getFlags()); 8609 void *IP = nullptr; 8610 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8611 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8612 return SDValue(E, 0); 8613 } 8614 8615 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8616 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8617 VTs, MemVT, MMO, IndexType, IsTrunc); 8618 createOperands(N, Ops); 8619 8620 assert(N->getMask().getValueType().getVectorElementCount() == 8621 N->getValue().getValueType().getVectorElementCount() && 8622 "Vector width mismatch between mask and data"); 8623 assert( 8624 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8625 N->getValue().getValueType().getVectorElementCount().isScalable() && 8626 "Scalable flags of index and data do not match"); 8627 assert(ElementCount::isKnownGE( 8628 N->getIndex().getValueType().getVectorElementCount(), 8629 N->getValue().getValueType().getVectorElementCount()) && 8630 "Vector width mismatch between index and data"); 8631 assert(isa<ConstantSDNode>(N->getScale()) && 8632 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8633 "Scale should be a constant power of 2"); 8634 8635 CSEMap.InsertNode(N, IP); 8636 InsertNode(N); 8637 SDValue V(N, 0); 8638 NewSDValueDbgMsg(V, "Creating new node: ", this); 8639 return V; 8640 } 8641 8642 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8643 // select undef, T, F --> T (if T is a constant), otherwise F 8644 // select, ?, undef, F --> F 8645 // select, ?, T, undef --> T 8646 if (Cond.isUndef()) 8647 return isConstantValueOfAnyType(T) ? T : F; 8648 if (T.isUndef()) 8649 return F; 8650 if (F.isUndef()) 8651 return T; 8652 8653 // select true, T, F --> T 8654 // select false, T, F --> F 8655 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8656 return CondC->isZero() ? F : T; 8657 8658 // TODO: This should simplify VSELECT with constant condition using something 8659 // like this (but check boolean contents to be complete?): 8660 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8661 // return T; 8662 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8663 // return F; 8664 8665 // select ?, T, T --> T 8666 if (T == F) 8667 return T; 8668 8669 return SDValue(); 8670 } 8671 8672 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8673 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8674 if (X.isUndef()) 8675 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8676 // shift X, undef --> undef (because it may shift by the bitwidth) 8677 if (Y.isUndef()) 8678 return getUNDEF(X.getValueType()); 8679 8680 // shift 0, Y --> 0 8681 // shift X, 0 --> X 8682 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8683 return X; 8684 8685 // shift X, C >= bitwidth(X) --> undef 8686 // All vector elements must be too big (or undef) to avoid partial undefs. 8687 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8688 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8689 }; 8690 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8691 return getUNDEF(X.getValueType()); 8692 8693 return SDValue(); 8694 } 8695 8696 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8697 SDNodeFlags Flags) { 8698 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8699 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8700 // operation is poison. That result can be relaxed to undef. 8701 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8702 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8703 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8704 (YC && YC->getValueAPF().isNaN()); 8705 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8706 (YC && YC->getValueAPF().isInfinity()); 8707 8708 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8709 return getUNDEF(X.getValueType()); 8710 8711 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8712 return getUNDEF(X.getValueType()); 8713 8714 if (!YC) 8715 return SDValue(); 8716 8717 // X + -0.0 --> X 8718 if (Opcode == ISD::FADD) 8719 if (YC->getValueAPF().isNegZero()) 8720 return X; 8721 8722 // X - +0.0 --> X 8723 if (Opcode == ISD::FSUB) 8724 if (YC->getValueAPF().isPosZero()) 8725 return X; 8726 8727 // X * 1.0 --> X 8728 // X / 1.0 --> X 8729 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8730 if (YC->getValueAPF().isExactlyValue(1.0)) 8731 return X; 8732 8733 // X * 0.0 --> 0.0 8734 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8735 if (YC->getValueAPF().isZero()) 8736 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8737 8738 return SDValue(); 8739 } 8740 8741 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8742 SDValue Ptr, SDValue SV, unsigned Align) { 8743 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8744 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8745 } 8746 8747 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8748 ArrayRef<SDUse> Ops) { 8749 switch (Ops.size()) { 8750 case 0: return getNode(Opcode, DL, VT); 8751 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8752 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8753 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8754 default: break; 8755 } 8756 8757 // Copy from an SDUse array into an SDValue array for use with 8758 // the regular getNode logic. 8759 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8760 return getNode(Opcode, DL, VT, NewOps); 8761 } 8762 8763 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8764 ArrayRef<SDValue> Ops) { 8765 SDNodeFlags Flags; 8766 if (Inserter) 8767 Flags = Inserter->getFlags(); 8768 return getNode(Opcode, DL, VT, Ops, Flags); 8769 } 8770 8771 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8772 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8773 unsigned NumOps = Ops.size(); 8774 switch (NumOps) { 8775 case 0: return getNode(Opcode, DL, VT); 8776 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8777 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8778 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8779 default: break; 8780 } 8781 8782 #ifndef NDEBUG 8783 for (auto &Op : Ops) 8784 assert(Op.getOpcode() != ISD::DELETED_NODE && 8785 "Operand is DELETED_NODE!"); 8786 #endif 8787 8788 switch (Opcode) { 8789 default: break; 8790 case ISD::BUILD_VECTOR: 8791 // Attempt to simplify BUILD_VECTOR. 8792 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8793 return V; 8794 break; 8795 case ISD::CONCAT_VECTORS: 8796 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8797 return V; 8798 break; 8799 case ISD::SELECT_CC: 8800 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8801 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8802 "LHS and RHS of condition must have same type!"); 8803 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8804 "True and False arms of SelectCC must have same type!"); 8805 assert(Ops[2].getValueType() == VT && 8806 "select_cc node must be of same type as true and false value!"); 8807 break; 8808 case ISD::BR_CC: 8809 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8810 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8811 "LHS/RHS of comparison should match types!"); 8812 break; 8813 } 8814 8815 // Memoize nodes. 8816 SDNode *N; 8817 SDVTList VTs = getVTList(VT); 8818 8819 if (VT != MVT::Glue) { 8820 FoldingSetNodeID ID; 8821 AddNodeIDNode(ID, Opcode, VTs, Ops); 8822 void *IP = nullptr; 8823 8824 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8825 return SDValue(E, 0); 8826 8827 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8828 createOperands(N, Ops); 8829 8830 CSEMap.InsertNode(N, IP); 8831 } else { 8832 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8833 createOperands(N, Ops); 8834 } 8835 8836 N->setFlags(Flags); 8837 InsertNode(N); 8838 SDValue V(N, 0); 8839 NewSDValueDbgMsg(V, "Creating new node: ", this); 8840 return V; 8841 } 8842 8843 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8844 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8845 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8846 } 8847 8848 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8849 ArrayRef<SDValue> Ops) { 8850 SDNodeFlags Flags; 8851 if (Inserter) 8852 Flags = Inserter->getFlags(); 8853 return getNode(Opcode, DL, VTList, Ops, Flags); 8854 } 8855 8856 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8857 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8858 if (VTList.NumVTs == 1) 8859 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8860 8861 #ifndef NDEBUG 8862 for (auto &Op : Ops) 8863 assert(Op.getOpcode() != ISD::DELETED_NODE && 8864 "Operand is DELETED_NODE!"); 8865 #endif 8866 8867 switch (Opcode) { 8868 case ISD::STRICT_FP_EXTEND: 8869 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8870 "Invalid STRICT_FP_EXTEND!"); 8871 assert(VTList.VTs[0].isFloatingPoint() && 8872 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8873 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8874 "STRICT_FP_EXTEND result type should be vector iff the operand " 8875 "type is vector!"); 8876 assert((!VTList.VTs[0].isVector() || 8877 VTList.VTs[0].getVectorNumElements() == 8878 Ops[1].getValueType().getVectorNumElements()) && 8879 "Vector element count mismatch!"); 8880 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8881 "Invalid fpext node, dst <= src!"); 8882 break; 8883 case ISD::STRICT_FP_ROUND: 8884 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8885 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8886 "STRICT_FP_ROUND result type should be vector iff the operand " 8887 "type is vector!"); 8888 assert((!VTList.VTs[0].isVector() || 8889 VTList.VTs[0].getVectorNumElements() == 8890 Ops[1].getValueType().getVectorNumElements()) && 8891 "Vector element count mismatch!"); 8892 assert(VTList.VTs[0].isFloatingPoint() && 8893 Ops[1].getValueType().isFloatingPoint() && 8894 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8895 isa<ConstantSDNode>(Ops[2]) && 8896 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8897 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8898 "Invalid STRICT_FP_ROUND!"); 8899 break; 8900 #if 0 8901 // FIXME: figure out how to safely handle things like 8902 // int foo(int x) { return 1 << (x & 255); } 8903 // int bar() { return foo(256); } 8904 case ISD::SRA_PARTS: 8905 case ISD::SRL_PARTS: 8906 case ISD::SHL_PARTS: 8907 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8908 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8909 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8910 else if (N3.getOpcode() == ISD::AND) 8911 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8912 // If the and is only masking out bits that cannot effect the shift, 8913 // eliminate the and. 8914 unsigned NumBits = VT.getScalarSizeInBits()*2; 8915 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8916 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8917 } 8918 break; 8919 #endif 8920 } 8921 8922 // Memoize the node unless it returns a flag. 8923 SDNode *N; 8924 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8925 FoldingSetNodeID ID; 8926 AddNodeIDNode(ID, Opcode, VTList, Ops); 8927 void *IP = nullptr; 8928 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8929 return SDValue(E, 0); 8930 8931 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8932 createOperands(N, Ops); 8933 CSEMap.InsertNode(N, IP); 8934 } else { 8935 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8936 createOperands(N, Ops); 8937 } 8938 8939 N->setFlags(Flags); 8940 InsertNode(N); 8941 SDValue V(N, 0); 8942 NewSDValueDbgMsg(V, "Creating new node: ", this); 8943 return V; 8944 } 8945 8946 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8947 SDVTList VTList) { 8948 return getNode(Opcode, DL, VTList, None); 8949 } 8950 8951 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8952 SDValue N1) { 8953 SDValue Ops[] = { N1 }; 8954 return getNode(Opcode, DL, VTList, Ops); 8955 } 8956 8957 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8958 SDValue N1, SDValue N2) { 8959 SDValue Ops[] = { N1, N2 }; 8960 return getNode(Opcode, DL, VTList, Ops); 8961 } 8962 8963 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8964 SDValue N1, SDValue N2, SDValue N3) { 8965 SDValue Ops[] = { N1, N2, N3 }; 8966 return getNode(Opcode, DL, VTList, Ops); 8967 } 8968 8969 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8970 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8971 SDValue Ops[] = { N1, N2, N3, N4 }; 8972 return getNode(Opcode, DL, VTList, Ops); 8973 } 8974 8975 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8976 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8977 SDValue N5) { 8978 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8979 return getNode(Opcode, DL, VTList, Ops); 8980 } 8981 8982 SDVTList SelectionDAG::getVTList(EVT VT) { 8983 return makeVTList(SDNode::getValueTypeList(VT), 1); 8984 } 8985 8986 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8987 FoldingSetNodeID ID; 8988 ID.AddInteger(2U); 8989 ID.AddInteger(VT1.getRawBits()); 8990 ID.AddInteger(VT2.getRawBits()); 8991 8992 void *IP = nullptr; 8993 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8994 if (!Result) { 8995 EVT *Array = Allocator.Allocate<EVT>(2); 8996 Array[0] = VT1; 8997 Array[1] = VT2; 8998 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8999 VTListMap.InsertNode(Result, IP); 9000 } 9001 return Result->getSDVTList(); 9002 } 9003 9004 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 9005 FoldingSetNodeID ID; 9006 ID.AddInteger(3U); 9007 ID.AddInteger(VT1.getRawBits()); 9008 ID.AddInteger(VT2.getRawBits()); 9009 ID.AddInteger(VT3.getRawBits()); 9010 9011 void *IP = nullptr; 9012 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9013 if (!Result) { 9014 EVT *Array = Allocator.Allocate<EVT>(3); 9015 Array[0] = VT1; 9016 Array[1] = VT2; 9017 Array[2] = VT3; 9018 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9019 VTListMap.InsertNode(Result, IP); 9020 } 9021 return Result->getSDVTList(); 9022 } 9023 9024 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9025 FoldingSetNodeID ID; 9026 ID.AddInteger(4U); 9027 ID.AddInteger(VT1.getRawBits()); 9028 ID.AddInteger(VT2.getRawBits()); 9029 ID.AddInteger(VT3.getRawBits()); 9030 ID.AddInteger(VT4.getRawBits()); 9031 9032 void *IP = nullptr; 9033 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9034 if (!Result) { 9035 EVT *Array = Allocator.Allocate<EVT>(4); 9036 Array[0] = VT1; 9037 Array[1] = VT2; 9038 Array[2] = VT3; 9039 Array[3] = VT4; 9040 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9041 VTListMap.InsertNode(Result, IP); 9042 } 9043 return Result->getSDVTList(); 9044 } 9045 9046 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9047 unsigned NumVTs = VTs.size(); 9048 FoldingSetNodeID ID; 9049 ID.AddInteger(NumVTs); 9050 for (unsigned index = 0; index < NumVTs; index++) { 9051 ID.AddInteger(VTs[index].getRawBits()); 9052 } 9053 9054 void *IP = nullptr; 9055 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9056 if (!Result) { 9057 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9058 llvm::copy(VTs, Array); 9059 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9060 VTListMap.InsertNode(Result, IP); 9061 } 9062 return Result->getSDVTList(); 9063 } 9064 9065 9066 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9067 /// specified operands. If the resultant node already exists in the DAG, 9068 /// this does not modify the specified node, instead it returns the node that 9069 /// already exists. If the resultant node does not exist in the DAG, the 9070 /// input node is returned. As a degenerate case, if you specify the same 9071 /// input operands as the node already has, the input node is returned. 9072 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9073 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9074 9075 // Check to see if there is no change. 9076 if (Op == N->getOperand(0)) return N; 9077 9078 // See if the modified node already exists. 9079 void *InsertPos = nullptr; 9080 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9081 return Existing; 9082 9083 // Nope it doesn't. Remove the node from its current place in the maps. 9084 if (InsertPos) 9085 if (!RemoveNodeFromCSEMaps(N)) 9086 InsertPos = nullptr; 9087 9088 // Now we update the operands. 9089 N->OperandList[0].set(Op); 9090 9091 updateDivergence(N); 9092 // If this gets put into a CSE map, add it. 9093 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9094 return N; 9095 } 9096 9097 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9098 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9099 9100 // Check to see if there is no change. 9101 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9102 return N; // No operands changed, just return the input node. 9103 9104 // See if the modified node already exists. 9105 void *InsertPos = nullptr; 9106 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9107 return Existing; 9108 9109 // Nope it doesn't. Remove the node from its current place in the maps. 9110 if (InsertPos) 9111 if (!RemoveNodeFromCSEMaps(N)) 9112 InsertPos = nullptr; 9113 9114 // Now we update the operands. 9115 if (N->OperandList[0] != Op1) 9116 N->OperandList[0].set(Op1); 9117 if (N->OperandList[1] != Op2) 9118 N->OperandList[1].set(Op2); 9119 9120 updateDivergence(N); 9121 // If this gets put into a CSE map, add it. 9122 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9123 return N; 9124 } 9125 9126 SDNode *SelectionDAG:: 9127 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9128 SDValue Ops[] = { Op1, Op2, Op3 }; 9129 return UpdateNodeOperands(N, Ops); 9130 } 9131 9132 SDNode *SelectionDAG:: 9133 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9134 SDValue Op3, SDValue Op4) { 9135 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9136 return UpdateNodeOperands(N, Ops); 9137 } 9138 9139 SDNode *SelectionDAG:: 9140 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9141 SDValue Op3, SDValue Op4, SDValue Op5) { 9142 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9143 return UpdateNodeOperands(N, Ops); 9144 } 9145 9146 SDNode *SelectionDAG:: 9147 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9148 unsigned NumOps = Ops.size(); 9149 assert(N->getNumOperands() == NumOps && 9150 "Update with wrong number of operands"); 9151 9152 // If no operands changed just return the input node. 9153 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9154 return N; 9155 9156 // See if the modified node already exists. 9157 void *InsertPos = nullptr; 9158 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9159 return Existing; 9160 9161 // Nope it doesn't. Remove the node from its current place in the maps. 9162 if (InsertPos) 9163 if (!RemoveNodeFromCSEMaps(N)) 9164 InsertPos = nullptr; 9165 9166 // Now we update the operands. 9167 for (unsigned i = 0; i != NumOps; ++i) 9168 if (N->OperandList[i] != Ops[i]) 9169 N->OperandList[i].set(Ops[i]); 9170 9171 updateDivergence(N); 9172 // If this gets put into a CSE map, add it. 9173 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9174 return N; 9175 } 9176 9177 /// DropOperands - Release the operands and set this node to have 9178 /// zero operands. 9179 void SDNode::DropOperands() { 9180 // Unlike the code in MorphNodeTo that does this, we don't need to 9181 // watch for dead nodes here. 9182 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9183 SDUse &Use = *I++; 9184 Use.set(SDValue()); 9185 } 9186 } 9187 9188 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9189 ArrayRef<MachineMemOperand *> NewMemRefs) { 9190 if (NewMemRefs.empty()) { 9191 N->clearMemRefs(); 9192 return; 9193 } 9194 9195 // Check if we can avoid allocating by storing a single reference directly. 9196 if (NewMemRefs.size() == 1) { 9197 N->MemRefs = NewMemRefs[0]; 9198 N->NumMemRefs = 1; 9199 return; 9200 } 9201 9202 MachineMemOperand **MemRefsBuffer = 9203 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 9204 llvm::copy(NewMemRefs, MemRefsBuffer); 9205 N->MemRefs = MemRefsBuffer; 9206 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 9207 } 9208 9209 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 9210 /// machine opcode. 9211 /// 9212 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9213 EVT VT) { 9214 SDVTList VTs = getVTList(VT); 9215 return SelectNodeTo(N, MachineOpc, VTs, None); 9216 } 9217 9218 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9219 EVT VT, SDValue Op1) { 9220 SDVTList VTs = getVTList(VT); 9221 SDValue Ops[] = { Op1 }; 9222 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9223 } 9224 9225 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9226 EVT VT, SDValue Op1, 9227 SDValue Op2) { 9228 SDVTList VTs = getVTList(VT); 9229 SDValue Ops[] = { Op1, Op2 }; 9230 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9231 } 9232 9233 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9234 EVT VT, SDValue Op1, 9235 SDValue Op2, SDValue Op3) { 9236 SDVTList VTs = getVTList(VT); 9237 SDValue Ops[] = { Op1, Op2, Op3 }; 9238 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9239 } 9240 9241 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9242 EVT VT, ArrayRef<SDValue> Ops) { 9243 SDVTList VTs = getVTList(VT); 9244 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9245 } 9246 9247 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9248 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 9249 SDVTList VTs = getVTList(VT1, VT2); 9250 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9251 } 9252 9253 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9254 EVT VT1, EVT VT2) { 9255 SDVTList VTs = getVTList(VT1, VT2); 9256 return SelectNodeTo(N, MachineOpc, VTs, None); 9257 } 9258 9259 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9260 EVT VT1, EVT VT2, EVT VT3, 9261 ArrayRef<SDValue> Ops) { 9262 SDVTList VTs = getVTList(VT1, VT2, VT3); 9263 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9264 } 9265 9266 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9267 EVT VT1, EVT VT2, 9268 SDValue Op1, SDValue Op2) { 9269 SDVTList VTs = getVTList(VT1, VT2); 9270 SDValue Ops[] = { Op1, Op2 }; 9271 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9272 } 9273 9274 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9275 SDVTList VTs,ArrayRef<SDValue> Ops) { 9276 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 9277 // Reset the NodeID to -1. 9278 New->setNodeId(-1); 9279 if (New != N) { 9280 ReplaceAllUsesWith(N, New); 9281 RemoveDeadNode(N); 9282 } 9283 return New; 9284 } 9285 9286 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 9287 /// the line number information on the merged node since it is not possible to 9288 /// preserve the information that operation is associated with multiple lines. 9289 /// This will make the debugger working better at -O0, were there is a higher 9290 /// probability having other instructions associated with that line. 9291 /// 9292 /// For IROrder, we keep the smaller of the two 9293 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 9294 DebugLoc NLoc = N->getDebugLoc(); 9295 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 9296 N->setDebugLoc(DebugLoc()); 9297 } 9298 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 9299 N->setIROrder(Order); 9300 return N; 9301 } 9302 9303 /// MorphNodeTo - This *mutates* the specified node to have the specified 9304 /// return type, opcode, and operands. 9305 /// 9306 /// Note that MorphNodeTo returns the resultant node. If there is already a 9307 /// node of the specified opcode and operands, it returns that node instead of 9308 /// the current one. Note that the SDLoc need not be the same. 9309 /// 9310 /// Using MorphNodeTo is faster than creating a new node and swapping it in 9311 /// with ReplaceAllUsesWith both because it often avoids allocating a new 9312 /// node, and because it doesn't require CSE recalculation for any of 9313 /// the node's users. 9314 /// 9315 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 9316 /// As a consequence it isn't appropriate to use from within the DAG combiner or 9317 /// the legalizer which maintain worklists that would need to be updated when 9318 /// deleting things. 9319 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 9320 SDVTList VTs, ArrayRef<SDValue> Ops) { 9321 // If an identical node already exists, use it. 9322 void *IP = nullptr; 9323 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 9324 FoldingSetNodeID ID; 9325 AddNodeIDNode(ID, Opc, VTs, Ops); 9326 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 9327 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 9328 } 9329 9330 if (!RemoveNodeFromCSEMaps(N)) 9331 IP = nullptr; 9332 9333 // Start the morphing. 9334 N->NodeType = Opc; 9335 N->ValueList = VTs.VTs; 9336 N->NumValues = VTs.NumVTs; 9337 9338 // Clear the operands list, updating used nodes to remove this from their 9339 // use list. Keep track of any operands that become dead as a result. 9340 SmallPtrSet<SDNode*, 16> DeadNodeSet; 9341 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 9342 SDUse &Use = *I++; 9343 SDNode *Used = Use.getNode(); 9344 Use.set(SDValue()); 9345 if (Used->use_empty()) 9346 DeadNodeSet.insert(Used); 9347 } 9348 9349 // For MachineNode, initialize the memory references information. 9350 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 9351 MN->clearMemRefs(); 9352 9353 // Swap for an appropriately sized array from the recycler. 9354 removeOperands(N); 9355 createOperands(N, Ops); 9356 9357 // Delete any nodes that are still dead after adding the uses for the 9358 // new operands. 9359 if (!DeadNodeSet.empty()) { 9360 SmallVector<SDNode *, 16> DeadNodes; 9361 for (SDNode *N : DeadNodeSet) 9362 if (N->use_empty()) 9363 DeadNodes.push_back(N); 9364 RemoveDeadNodes(DeadNodes); 9365 } 9366 9367 if (IP) 9368 CSEMap.InsertNode(N, IP); // Memoize the new node. 9369 return N; 9370 } 9371 9372 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9373 unsigned OrigOpc = Node->getOpcode(); 9374 unsigned NewOpc; 9375 switch (OrigOpc) { 9376 default: 9377 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9378 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9379 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9380 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9381 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9382 #include "llvm/IR/ConstrainedOps.def" 9383 } 9384 9385 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9386 9387 // We're taking this node out of the chain, so we need to re-link things. 9388 SDValue InputChain = Node->getOperand(0); 9389 SDValue OutputChain = SDValue(Node, 1); 9390 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9391 9392 SmallVector<SDValue, 3> Ops; 9393 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9394 Ops.push_back(Node->getOperand(i)); 9395 9396 SDVTList VTs = getVTList(Node->getValueType(0)); 9397 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9398 9399 // MorphNodeTo can operate in two ways: if an existing node with the 9400 // specified operands exists, it can just return it. Otherwise, it 9401 // updates the node in place to have the requested operands. 9402 if (Res == Node) { 9403 // If we updated the node in place, reset the node ID. To the isel, 9404 // this should be just like a newly allocated machine node. 9405 Res->setNodeId(-1); 9406 } else { 9407 ReplaceAllUsesWith(Node, Res); 9408 RemoveDeadNode(Node); 9409 } 9410 9411 return Res; 9412 } 9413 9414 /// getMachineNode - These are used for target selectors to create a new node 9415 /// with specified return type(s), MachineInstr opcode, and operands. 9416 /// 9417 /// Note that getMachineNode returns the resultant node. If there is already a 9418 /// node of the specified opcode and operands, it returns that node instead of 9419 /// the current one. 9420 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9421 EVT VT) { 9422 SDVTList VTs = getVTList(VT); 9423 return getMachineNode(Opcode, dl, VTs, None); 9424 } 9425 9426 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9427 EVT VT, SDValue Op1) { 9428 SDVTList VTs = getVTList(VT); 9429 SDValue Ops[] = { Op1 }; 9430 return getMachineNode(Opcode, dl, VTs, Ops); 9431 } 9432 9433 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9434 EVT VT, SDValue Op1, SDValue Op2) { 9435 SDVTList VTs = getVTList(VT); 9436 SDValue Ops[] = { Op1, Op2 }; 9437 return getMachineNode(Opcode, dl, VTs, Ops); 9438 } 9439 9440 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9441 EVT VT, SDValue Op1, SDValue Op2, 9442 SDValue Op3) { 9443 SDVTList VTs = getVTList(VT); 9444 SDValue Ops[] = { Op1, Op2, Op3 }; 9445 return getMachineNode(Opcode, dl, VTs, Ops); 9446 } 9447 9448 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9449 EVT VT, ArrayRef<SDValue> Ops) { 9450 SDVTList VTs = getVTList(VT); 9451 return getMachineNode(Opcode, dl, VTs, Ops); 9452 } 9453 9454 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9455 EVT VT1, EVT VT2, SDValue Op1, 9456 SDValue Op2) { 9457 SDVTList VTs = getVTList(VT1, VT2); 9458 SDValue Ops[] = { Op1, Op2 }; 9459 return getMachineNode(Opcode, dl, VTs, Ops); 9460 } 9461 9462 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9463 EVT VT1, EVT VT2, SDValue Op1, 9464 SDValue Op2, SDValue Op3) { 9465 SDVTList VTs = getVTList(VT1, VT2); 9466 SDValue Ops[] = { Op1, Op2, Op3 }; 9467 return getMachineNode(Opcode, dl, VTs, Ops); 9468 } 9469 9470 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9471 EVT VT1, EVT VT2, 9472 ArrayRef<SDValue> Ops) { 9473 SDVTList VTs = getVTList(VT1, VT2); 9474 return getMachineNode(Opcode, dl, VTs, Ops); 9475 } 9476 9477 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9478 EVT VT1, EVT VT2, EVT VT3, 9479 SDValue Op1, SDValue Op2) { 9480 SDVTList VTs = getVTList(VT1, VT2, VT3); 9481 SDValue Ops[] = { Op1, Op2 }; 9482 return getMachineNode(Opcode, dl, VTs, Ops); 9483 } 9484 9485 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9486 EVT VT1, EVT VT2, EVT VT3, 9487 SDValue Op1, SDValue Op2, 9488 SDValue Op3) { 9489 SDVTList VTs = getVTList(VT1, VT2, VT3); 9490 SDValue Ops[] = { Op1, Op2, Op3 }; 9491 return getMachineNode(Opcode, dl, VTs, Ops); 9492 } 9493 9494 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9495 EVT VT1, EVT VT2, EVT VT3, 9496 ArrayRef<SDValue> Ops) { 9497 SDVTList VTs = getVTList(VT1, VT2, VT3); 9498 return getMachineNode(Opcode, dl, VTs, Ops); 9499 } 9500 9501 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9502 ArrayRef<EVT> ResultTys, 9503 ArrayRef<SDValue> Ops) { 9504 SDVTList VTs = getVTList(ResultTys); 9505 return getMachineNode(Opcode, dl, VTs, Ops); 9506 } 9507 9508 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9509 SDVTList VTs, 9510 ArrayRef<SDValue> Ops) { 9511 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9512 MachineSDNode *N; 9513 void *IP = nullptr; 9514 9515 if (DoCSE) { 9516 FoldingSetNodeID ID; 9517 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9518 IP = nullptr; 9519 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9520 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9521 } 9522 } 9523 9524 // Allocate a new MachineSDNode. 9525 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9526 createOperands(N, Ops); 9527 9528 if (DoCSE) 9529 CSEMap.InsertNode(N, IP); 9530 9531 InsertNode(N); 9532 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9533 return N; 9534 } 9535 9536 /// getTargetExtractSubreg - A convenience function for creating 9537 /// TargetOpcode::EXTRACT_SUBREG nodes. 9538 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9539 SDValue Operand) { 9540 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9541 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9542 VT, Operand, SRIdxVal); 9543 return SDValue(Subreg, 0); 9544 } 9545 9546 /// getTargetInsertSubreg - A convenience function for creating 9547 /// TargetOpcode::INSERT_SUBREG nodes. 9548 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9549 SDValue Operand, SDValue Subreg) { 9550 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9551 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9552 VT, Operand, Subreg, SRIdxVal); 9553 return SDValue(Result, 0); 9554 } 9555 9556 /// getNodeIfExists - Get the specified node if it's already available, or 9557 /// else return NULL. 9558 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9559 ArrayRef<SDValue> Ops) { 9560 SDNodeFlags Flags; 9561 if (Inserter) 9562 Flags = Inserter->getFlags(); 9563 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9564 } 9565 9566 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9567 ArrayRef<SDValue> Ops, 9568 const SDNodeFlags Flags) { 9569 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9570 FoldingSetNodeID ID; 9571 AddNodeIDNode(ID, Opcode, VTList, Ops); 9572 void *IP = nullptr; 9573 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9574 E->intersectFlagsWith(Flags); 9575 return E; 9576 } 9577 } 9578 return nullptr; 9579 } 9580 9581 /// doesNodeExist - Check if a node exists without modifying its flags. 9582 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9583 ArrayRef<SDValue> Ops) { 9584 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9585 FoldingSetNodeID ID; 9586 AddNodeIDNode(ID, Opcode, VTList, Ops); 9587 void *IP = nullptr; 9588 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9589 return true; 9590 } 9591 return false; 9592 } 9593 9594 /// getDbgValue - Creates a SDDbgValue node. 9595 /// 9596 /// SDNode 9597 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9598 SDNode *N, unsigned R, bool IsIndirect, 9599 const DebugLoc &DL, unsigned O) { 9600 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9601 "Expected inlined-at fields to agree"); 9602 return new (DbgInfo->getAlloc()) 9603 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9604 {}, IsIndirect, DL, O, 9605 /*IsVariadic=*/false); 9606 } 9607 9608 /// Constant 9609 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9610 DIExpression *Expr, 9611 const Value *C, 9612 const DebugLoc &DL, unsigned O) { 9613 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9614 "Expected inlined-at fields to agree"); 9615 return new (DbgInfo->getAlloc()) 9616 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9617 /*IsIndirect=*/false, DL, O, 9618 /*IsVariadic=*/false); 9619 } 9620 9621 /// FrameIndex 9622 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9623 DIExpression *Expr, unsigned FI, 9624 bool IsIndirect, 9625 const DebugLoc &DL, 9626 unsigned O) { 9627 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9628 "Expected inlined-at fields to agree"); 9629 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9630 } 9631 9632 /// FrameIndex with dependencies 9633 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9634 DIExpression *Expr, unsigned FI, 9635 ArrayRef<SDNode *> Dependencies, 9636 bool IsIndirect, 9637 const DebugLoc &DL, 9638 unsigned O) { 9639 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9640 "Expected inlined-at fields to agree"); 9641 return new (DbgInfo->getAlloc()) 9642 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9643 Dependencies, IsIndirect, DL, O, 9644 /*IsVariadic=*/false); 9645 } 9646 9647 /// VReg 9648 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9649 unsigned VReg, bool IsIndirect, 9650 const DebugLoc &DL, unsigned O) { 9651 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9652 "Expected inlined-at fields to agree"); 9653 return new (DbgInfo->getAlloc()) 9654 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9655 {}, IsIndirect, DL, O, 9656 /*IsVariadic=*/false); 9657 } 9658 9659 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9660 ArrayRef<SDDbgOperand> Locs, 9661 ArrayRef<SDNode *> Dependencies, 9662 bool IsIndirect, const DebugLoc &DL, 9663 unsigned O, bool IsVariadic) { 9664 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9665 "Expected inlined-at fields to agree"); 9666 return new (DbgInfo->getAlloc()) 9667 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9668 DL, O, IsVariadic); 9669 } 9670 9671 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9672 unsigned OffsetInBits, unsigned SizeInBits, 9673 bool InvalidateDbg) { 9674 SDNode *FromNode = From.getNode(); 9675 SDNode *ToNode = To.getNode(); 9676 assert(FromNode && ToNode && "Can't modify dbg values"); 9677 9678 // PR35338 9679 // TODO: assert(From != To && "Redundant dbg value transfer"); 9680 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9681 if (From == To || FromNode == ToNode) 9682 return; 9683 9684 if (!FromNode->getHasDebugValue()) 9685 return; 9686 9687 SDDbgOperand FromLocOp = 9688 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9689 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9690 9691 SmallVector<SDDbgValue *, 2> ClonedDVs; 9692 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9693 if (Dbg->isInvalidated()) 9694 continue; 9695 9696 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9697 9698 // Create a new location ops vector that is equal to the old vector, but 9699 // with each instance of FromLocOp replaced with ToLocOp. 9700 bool Changed = false; 9701 auto NewLocOps = Dbg->copyLocationOps(); 9702 std::replace_if( 9703 NewLocOps.begin(), NewLocOps.end(), 9704 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9705 bool Match = Op == FromLocOp; 9706 Changed |= Match; 9707 return Match; 9708 }, 9709 ToLocOp); 9710 // Ignore this SDDbgValue if we didn't find a matching location. 9711 if (!Changed) 9712 continue; 9713 9714 DIVariable *Var = Dbg->getVariable(); 9715 auto *Expr = Dbg->getExpression(); 9716 // If a fragment is requested, update the expression. 9717 if (SizeInBits) { 9718 // When splitting a larger (e.g., sign-extended) value whose 9719 // lower bits are described with an SDDbgValue, do not attempt 9720 // to transfer the SDDbgValue to the upper bits. 9721 if (auto FI = Expr->getFragmentInfo()) 9722 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9723 continue; 9724 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9725 SizeInBits); 9726 if (!Fragment) 9727 continue; 9728 Expr = *Fragment; 9729 } 9730 9731 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9732 // Clone the SDDbgValue and move it to To. 9733 SDDbgValue *Clone = getDbgValueList( 9734 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9735 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9736 Dbg->isVariadic()); 9737 ClonedDVs.push_back(Clone); 9738 9739 if (InvalidateDbg) { 9740 // Invalidate value and indicate the SDDbgValue should not be emitted. 9741 Dbg->setIsInvalidated(); 9742 Dbg->setIsEmitted(); 9743 } 9744 } 9745 9746 for (SDDbgValue *Dbg : ClonedDVs) { 9747 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9748 "Transferred DbgValues should depend on the new SDNode"); 9749 AddDbgValue(Dbg, false); 9750 } 9751 } 9752 9753 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9754 if (!N.getHasDebugValue()) 9755 return; 9756 9757 SmallVector<SDDbgValue *, 2> ClonedDVs; 9758 for (auto DV : GetDbgValues(&N)) { 9759 if (DV->isInvalidated()) 9760 continue; 9761 switch (N.getOpcode()) { 9762 default: 9763 break; 9764 case ISD::ADD: 9765 SDValue N0 = N.getOperand(0); 9766 SDValue N1 = N.getOperand(1); 9767 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9768 isConstantIntBuildVectorOrConstantInt(N1)) { 9769 uint64_t Offset = N.getConstantOperandVal(1); 9770 9771 // Rewrite an ADD constant node into a DIExpression. Since we are 9772 // performing arithmetic to compute the variable's *value* in the 9773 // DIExpression, we need to mark the expression with a 9774 // DW_OP_stack_value. 9775 auto *DIExpr = DV->getExpression(); 9776 auto NewLocOps = DV->copyLocationOps(); 9777 bool Changed = false; 9778 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9779 // We're not given a ResNo to compare against because the whole 9780 // node is going away. We know that any ISD::ADD only has one 9781 // result, so we can assume any node match is using the result. 9782 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9783 NewLocOps[i].getSDNode() != &N) 9784 continue; 9785 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9786 SmallVector<uint64_t, 3> ExprOps; 9787 DIExpression::appendOffset(ExprOps, Offset); 9788 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9789 Changed = true; 9790 } 9791 (void)Changed; 9792 assert(Changed && "Salvage target doesn't use N"); 9793 9794 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9795 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9796 NewLocOps, AdditionalDependencies, 9797 DV->isIndirect(), DV->getDebugLoc(), 9798 DV->getOrder(), DV->isVariadic()); 9799 ClonedDVs.push_back(Clone); 9800 DV->setIsInvalidated(); 9801 DV->setIsEmitted(); 9802 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9803 N0.getNode()->dumprFull(this); 9804 dbgs() << " into " << *DIExpr << '\n'); 9805 } 9806 } 9807 } 9808 9809 for (SDDbgValue *Dbg : ClonedDVs) { 9810 assert(!Dbg->getSDNodes().empty() && 9811 "Salvaged DbgValue should depend on a new SDNode"); 9812 AddDbgValue(Dbg, false); 9813 } 9814 } 9815 9816 /// Creates a SDDbgLabel node. 9817 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9818 const DebugLoc &DL, unsigned O) { 9819 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9820 "Expected inlined-at fields to agree"); 9821 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9822 } 9823 9824 namespace { 9825 9826 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9827 /// pointed to by a use iterator is deleted, increment the use iterator 9828 /// so that it doesn't dangle. 9829 /// 9830 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9831 SDNode::use_iterator &UI; 9832 SDNode::use_iterator &UE; 9833 9834 void NodeDeleted(SDNode *N, SDNode *E) override { 9835 // Increment the iterator as needed. 9836 while (UI != UE && N == *UI) 9837 ++UI; 9838 } 9839 9840 public: 9841 RAUWUpdateListener(SelectionDAG &d, 9842 SDNode::use_iterator &ui, 9843 SDNode::use_iterator &ue) 9844 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9845 }; 9846 9847 } // end anonymous namespace 9848 9849 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9850 /// This can cause recursive merging of nodes in the DAG. 9851 /// 9852 /// This version assumes From has a single result value. 9853 /// 9854 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9855 SDNode *From = FromN.getNode(); 9856 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9857 "Cannot replace with this method!"); 9858 assert(From != To.getNode() && "Cannot replace uses of with self"); 9859 9860 // Preserve Debug Values 9861 transferDbgValues(FromN, To); 9862 9863 // Iterate over all the existing uses of From. New uses will be added 9864 // to the beginning of the use list, which we avoid visiting. 9865 // This specifically avoids visiting uses of From that arise while the 9866 // replacement is happening, because any such uses would be the result 9867 // of CSE: If an existing node looks like From after one of its operands 9868 // is replaced by To, we don't want to replace of all its users with To 9869 // too. See PR3018 for more info. 9870 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9871 RAUWUpdateListener Listener(*this, UI, UE); 9872 while (UI != UE) { 9873 SDNode *User = *UI; 9874 9875 // This node is about to morph, remove its old self from the CSE maps. 9876 RemoveNodeFromCSEMaps(User); 9877 9878 // A user can appear in a use list multiple times, and when this 9879 // happens the uses are usually next to each other in the list. 9880 // To help reduce the number of CSE recomputations, process all 9881 // the uses of this user that we can find this way. 9882 do { 9883 SDUse &Use = UI.getUse(); 9884 ++UI; 9885 Use.set(To); 9886 if (To->isDivergent() != From->isDivergent()) 9887 updateDivergence(User); 9888 } while (UI != UE && *UI == User); 9889 // Now that we have modified User, add it back to the CSE maps. If it 9890 // already exists there, recursively merge the results together. 9891 AddModifiedNodeToCSEMaps(User); 9892 } 9893 9894 // If we just RAUW'd the root, take note. 9895 if (FromN == getRoot()) 9896 setRoot(To); 9897 } 9898 9899 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9900 /// This can cause recursive merging of nodes in the DAG. 9901 /// 9902 /// This version assumes that for each value of From, there is a 9903 /// corresponding value in To in the same position with the same type. 9904 /// 9905 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9906 #ifndef NDEBUG 9907 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9908 assert((!From->hasAnyUseOfValue(i) || 9909 From->getValueType(i) == To->getValueType(i)) && 9910 "Cannot use this version of ReplaceAllUsesWith!"); 9911 #endif 9912 9913 // Handle the trivial case. 9914 if (From == To) 9915 return; 9916 9917 // Preserve Debug Info. Only do this if there's a use. 9918 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9919 if (From->hasAnyUseOfValue(i)) { 9920 assert((i < To->getNumValues()) && "Invalid To location"); 9921 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9922 } 9923 9924 // Iterate over just the existing users of From. See the comments in 9925 // the ReplaceAllUsesWith above. 9926 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9927 RAUWUpdateListener Listener(*this, UI, UE); 9928 while (UI != UE) { 9929 SDNode *User = *UI; 9930 9931 // This node is about to morph, remove its old self from the CSE maps. 9932 RemoveNodeFromCSEMaps(User); 9933 9934 // A user can appear in a use list multiple times, and when this 9935 // happens the uses are usually next to each other in the list. 9936 // To help reduce the number of CSE recomputations, process all 9937 // the uses of this user that we can find this way. 9938 do { 9939 SDUse &Use = UI.getUse(); 9940 ++UI; 9941 Use.setNode(To); 9942 if (To->isDivergent() != From->isDivergent()) 9943 updateDivergence(User); 9944 } while (UI != UE && *UI == User); 9945 9946 // Now that we have modified User, add it back to the CSE maps. If it 9947 // already exists there, recursively merge the results together. 9948 AddModifiedNodeToCSEMaps(User); 9949 } 9950 9951 // If we just RAUW'd the root, take note. 9952 if (From == getRoot().getNode()) 9953 setRoot(SDValue(To, getRoot().getResNo())); 9954 } 9955 9956 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9957 /// This can cause recursive merging of nodes in the DAG. 9958 /// 9959 /// This version can replace From with any result values. To must match the 9960 /// number and types of values returned by From. 9961 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9962 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9963 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9964 9965 // Preserve Debug Info. 9966 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9967 transferDbgValues(SDValue(From, i), To[i]); 9968 9969 // Iterate over just the existing users of From. See the comments in 9970 // the ReplaceAllUsesWith above. 9971 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9972 RAUWUpdateListener Listener(*this, UI, UE); 9973 while (UI != UE) { 9974 SDNode *User = *UI; 9975 9976 // This node is about to morph, remove its old self from the CSE maps. 9977 RemoveNodeFromCSEMaps(User); 9978 9979 // A user can appear in a use list multiple times, and when this happens the 9980 // uses are usually next to each other in the list. To help reduce the 9981 // number of CSE and divergence recomputations, process all the uses of this 9982 // user that we can find this way. 9983 bool To_IsDivergent = false; 9984 do { 9985 SDUse &Use = UI.getUse(); 9986 const SDValue &ToOp = To[Use.getResNo()]; 9987 ++UI; 9988 Use.set(ToOp); 9989 To_IsDivergent |= ToOp->isDivergent(); 9990 } while (UI != UE && *UI == User); 9991 9992 if (To_IsDivergent != From->isDivergent()) 9993 updateDivergence(User); 9994 9995 // Now that we have modified User, add it back to the CSE maps. If it 9996 // already exists there, recursively merge the results together. 9997 AddModifiedNodeToCSEMaps(User); 9998 } 9999 10000 // If we just RAUW'd the root, take note. 10001 if (From == getRoot().getNode()) 10002 setRoot(SDValue(To[getRoot().getResNo()])); 10003 } 10004 10005 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 10006 /// uses of other values produced by From.getNode() alone. The Deleted 10007 /// vector is handled the same way as for ReplaceAllUsesWith. 10008 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 10009 // Handle the really simple, really trivial case efficiently. 10010 if (From == To) return; 10011 10012 // Handle the simple, trivial, case efficiently. 10013 if (From.getNode()->getNumValues() == 1) { 10014 ReplaceAllUsesWith(From, To); 10015 return; 10016 } 10017 10018 // Preserve Debug Info. 10019 transferDbgValues(From, To); 10020 10021 // Iterate over just the existing users of From. See the comments in 10022 // the ReplaceAllUsesWith above. 10023 SDNode::use_iterator UI = From.getNode()->use_begin(), 10024 UE = From.getNode()->use_end(); 10025 RAUWUpdateListener Listener(*this, UI, UE); 10026 while (UI != UE) { 10027 SDNode *User = *UI; 10028 bool UserRemovedFromCSEMaps = false; 10029 10030 // A user can appear in a use list multiple times, and when this 10031 // happens the uses are usually next to each other in the list. 10032 // To help reduce the number of CSE recomputations, process all 10033 // the uses of this user that we can find this way. 10034 do { 10035 SDUse &Use = UI.getUse(); 10036 10037 // Skip uses of different values from the same node. 10038 if (Use.getResNo() != From.getResNo()) { 10039 ++UI; 10040 continue; 10041 } 10042 10043 // If this node hasn't been modified yet, it's still in the CSE maps, 10044 // so remove its old self from the CSE maps. 10045 if (!UserRemovedFromCSEMaps) { 10046 RemoveNodeFromCSEMaps(User); 10047 UserRemovedFromCSEMaps = true; 10048 } 10049 10050 ++UI; 10051 Use.set(To); 10052 if (To->isDivergent() != From->isDivergent()) 10053 updateDivergence(User); 10054 } while (UI != UE && *UI == User); 10055 // We are iterating over all uses of the From node, so if a use 10056 // doesn't use the specific value, no changes are made. 10057 if (!UserRemovedFromCSEMaps) 10058 continue; 10059 10060 // Now that we have modified User, add it back to the CSE maps. If it 10061 // already exists there, recursively merge the results together. 10062 AddModifiedNodeToCSEMaps(User); 10063 } 10064 10065 // If we just RAUW'd the root, take note. 10066 if (From == getRoot()) 10067 setRoot(To); 10068 } 10069 10070 namespace { 10071 10072 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10073 /// to record information about a use. 10074 struct UseMemo { 10075 SDNode *User; 10076 unsigned Index; 10077 SDUse *Use; 10078 }; 10079 10080 /// operator< - Sort Memos by User. 10081 bool operator<(const UseMemo &L, const UseMemo &R) { 10082 return (intptr_t)L.User < (intptr_t)R.User; 10083 } 10084 10085 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10086 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10087 /// the node already has been taken care of recursively. 10088 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10089 SmallVector<UseMemo, 4> &Uses; 10090 10091 void NodeDeleted(SDNode *N, SDNode *E) override { 10092 for (UseMemo &Memo : Uses) 10093 if (Memo.User == N) 10094 Memo.User = nullptr; 10095 } 10096 10097 public: 10098 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10099 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10100 }; 10101 10102 } // end anonymous namespace 10103 10104 bool SelectionDAG::calculateDivergence(SDNode *N) { 10105 if (TLI->isSDNodeAlwaysUniform(N)) { 10106 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 10107 "Conflicting divergence information!"); 10108 return false; 10109 } 10110 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 10111 return true; 10112 for (auto &Op : N->ops()) { 10113 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10114 return true; 10115 } 10116 return false; 10117 } 10118 10119 void SelectionDAG::updateDivergence(SDNode *N) { 10120 SmallVector<SDNode *, 16> Worklist(1, N); 10121 do { 10122 N = Worklist.pop_back_val(); 10123 bool IsDivergent = calculateDivergence(N); 10124 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10125 N->SDNodeBits.IsDivergent = IsDivergent; 10126 llvm::append_range(Worklist, N->uses()); 10127 } 10128 } while (!Worklist.empty()); 10129 } 10130 10131 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10132 DenseMap<SDNode *, unsigned> Degree; 10133 Order.reserve(AllNodes.size()); 10134 for (auto &N : allnodes()) { 10135 unsigned NOps = N.getNumOperands(); 10136 Degree[&N] = NOps; 10137 if (0 == NOps) 10138 Order.push_back(&N); 10139 } 10140 for (size_t I = 0; I != Order.size(); ++I) { 10141 SDNode *N = Order[I]; 10142 for (auto U : N->uses()) { 10143 unsigned &UnsortedOps = Degree[U]; 10144 if (0 == --UnsortedOps) 10145 Order.push_back(U); 10146 } 10147 } 10148 } 10149 10150 #ifndef NDEBUG 10151 void SelectionDAG::VerifyDAGDivergence() { 10152 std::vector<SDNode *> TopoOrder; 10153 CreateTopologicalOrder(TopoOrder); 10154 for (auto *N : TopoOrder) { 10155 assert(calculateDivergence(N) == N->isDivergent() && 10156 "Divergence bit inconsistency detected"); 10157 } 10158 } 10159 #endif 10160 10161 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10162 /// uses of other values produced by From.getNode() alone. The same value 10163 /// may appear in both the From and To list. The Deleted vector is 10164 /// handled the same way as for ReplaceAllUsesWith. 10165 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10166 const SDValue *To, 10167 unsigned Num){ 10168 // Handle the simple, trivial case efficiently. 10169 if (Num == 1) 10170 return ReplaceAllUsesOfValueWith(*From, *To); 10171 10172 transferDbgValues(*From, *To); 10173 10174 // Read up all the uses and make records of them. This helps 10175 // processing new uses that are introduced during the 10176 // replacement process. 10177 SmallVector<UseMemo, 4> Uses; 10178 for (unsigned i = 0; i != Num; ++i) { 10179 unsigned FromResNo = From[i].getResNo(); 10180 SDNode *FromNode = From[i].getNode(); 10181 for (SDNode::use_iterator UI = FromNode->use_begin(), 10182 E = FromNode->use_end(); UI != E; ++UI) { 10183 SDUse &Use = UI.getUse(); 10184 if (Use.getResNo() == FromResNo) { 10185 UseMemo Memo = { *UI, i, &Use }; 10186 Uses.push_back(Memo); 10187 } 10188 } 10189 } 10190 10191 // Sort the uses, so that all the uses from a given User are together. 10192 llvm::sort(Uses); 10193 RAUOVWUpdateListener Listener(*this, Uses); 10194 10195 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 10196 UseIndex != UseIndexEnd; ) { 10197 // We know that this user uses some value of From. If it is the right 10198 // value, update it. 10199 SDNode *User = Uses[UseIndex].User; 10200 // If the node has been deleted by recursive CSE updates when updating 10201 // another node, then just skip this entry. 10202 if (User == nullptr) { 10203 ++UseIndex; 10204 continue; 10205 } 10206 10207 // This node is about to morph, remove its old self from the CSE maps. 10208 RemoveNodeFromCSEMaps(User); 10209 10210 // The Uses array is sorted, so all the uses for a given User 10211 // are next to each other in the list. 10212 // To help reduce the number of CSE recomputations, process all 10213 // the uses of this user that we can find this way. 10214 do { 10215 unsigned i = Uses[UseIndex].Index; 10216 SDUse &Use = *Uses[UseIndex].Use; 10217 ++UseIndex; 10218 10219 Use.set(To[i]); 10220 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 10221 10222 // Now that we have modified User, add it back to the CSE maps. If it 10223 // already exists there, recursively merge the results together. 10224 AddModifiedNodeToCSEMaps(User); 10225 } 10226 } 10227 10228 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 10229 /// based on their topological order. It returns the maximum id and a vector 10230 /// of the SDNodes* in assigned order by reference. 10231 unsigned SelectionDAG::AssignTopologicalOrder() { 10232 unsigned DAGSize = 0; 10233 10234 // SortedPos tracks the progress of the algorithm. Nodes before it are 10235 // sorted, nodes after it are unsorted. When the algorithm completes 10236 // it is at the end of the list. 10237 allnodes_iterator SortedPos = allnodes_begin(); 10238 10239 // Visit all the nodes. Move nodes with no operands to the front of 10240 // the list immediately. Annotate nodes that do have operands with their 10241 // operand count. Before we do this, the Node Id fields of the nodes 10242 // may contain arbitrary values. After, the Node Id fields for nodes 10243 // before SortedPos will contain the topological sort index, and the 10244 // Node Id fields for nodes At SortedPos and after will contain the 10245 // count of outstanding operands. 10246 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 10247 checkForCycles(&N, this); 10248 unsigned Degree = N.getNumOperands(); 10249 if (Degree == 0) { 10250 // A node with no uses, add it to the result array immediately. 10251 N.setNodeId(DAGSize++); 10252 allnodes_iterator Q(&N); 10253 if (Q != SortedPos) 10254 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 10255 assert(SortedPos != AllNodes.end() && "Overran node list"); 10256 ++SortedPos; 10257 } else { 10258 // Temporarily use the Node Id as scratch space for the degree count. 10259 N.setNodeId(Degree); 10260 } 10261 } 10262 10263 // Visit all the nodes. As we iterate, move nodes into sorted order, 10264 // such that by the time the end is reached all nodes will be sorted. 10265 for (SDNode &Node : allnodes()) { 10266 SDNode *N = &Node; 10267 checkForCycles(N, this); 10268 // N is in sorted position, so all its uses have one less operand 10269 // that needs to be sorted. 10270 for (SDNode *P : N->uses()) { 10271 unsigned Degree = P->getNodeId(); 10272 assert(Degree != 0 && "Invalid node degree"); 10273 --Degree; 10274 if (Degree == 0) { 10275 // All of P's operands are sorted, so P may sorted now. 10276 P->setNodeId(DAGSize++); 10277 if (P->getIterator() != SortedPos) 10278 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 10279 assert(SortedPos != AllNodes.end() && "Overran node list"); 10280 ++SortedPos; 10281 } else { 10282 // Update P's outstanding operand count. 10283 P->setNodeId(Degree); 10284 } 10285 } 10286 if (Node.getIterator() == SortedPos) { 10287 #ifndef NDEBUG 10288 allnodes_iterator I(N); 10289 SDNode *S = &*++I; 10290 dbgs() << "Overran sorted position:\n"; 10291 S->dumprFull(this); dbgs() << "\n"; 10292 dbgs() << "Checking if this is due to cycles\n"; 10293 checkForCycles(this, true); 10294 #endif 10295 llvm_unreachable(nullptr); 10296 } 10297 } 10298 10299 assert(SortedPos == AllNodes.end() && 10300 "Topological sort incomplete!"); 10301 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 10302 "First node in topological sort is not the entry token!"); 10303 assert(AllNodes.front().getNodeId() == 0 && 10304 "First node in topological sort has non-zero id!"); 10305 assert(AllNodes.front().getNumOperands() == 0 && 10306 "First node in topological sort has operands!"); 10307 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 10308 "Last node in topologic sort has unexpected id!"); 10309 assert(AllNodes.back().use_empty() && 10310 "Last node in topologic sort has users!"); 10311 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 10312 return DAGSize; 10313 } 10314 10315 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 10316 /// value is produced by SD. 10317 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 10318 for (SDNode *SD : DB->getSDNodes()) { 10319 if (!SD) 10320 continue; 10321 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 10322 SD->setHasDebugValue(true); 10323 } 10324 DbgInfo->add(DB, isParameter); 10325 } 10326 10327 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 10328 10329 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 10330 SDValue NewMemOpChain) { 10331 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 10332 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 10333 // The new memory operation must have the same position as the old load in 10334 // terms of memory dependency. Create a TokenFactor for the old load and new 10335 // memory operation and update uses of the old load's output chain to use that 10336 // TokenFactor. 10337 if (OldChain == NewMemOpChain || OldChain.use_empty()) 10338 return NewMemOpChain; 10339 10340 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 10341 OldChain, NewMemOpChain); 10342 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 10343 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 10344 return TokenFactor; 10345 } 10346 10347 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 10348 SDValue NewMemOp) { 10349 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 10350 SDValue OldChain = SDValue(OldLoad, 1); 10351 SDValue NewMemOpChain = NewMemOp.getValue(1); 10352 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 10353 } 10354 10355 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 10356 Function **OutFunction) { 10357 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 10358 10359 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 10360 auto *Module = MF->getFunction().getParent(); 10361 auto *Function = Module->getFunction(Symbol); 10362 10363 if (OutFunction != nullptr) 10364 *OutFunction = Function; 10365 10366 if (Function != nullptr) { 10367 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 10368 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 10369 } 10370 10371 std::string ErrorStr; 10372 raw_string_ostream ErrorFormatter(ErrorStr); 10373 ErrorFormatter << "Undefined external symbol "; 10374 ErrorFormatter << '"' << Symbol << '"'; 10375 report_fatal_error(Twine(ErrorFormatter.str())); 10376 } 10377 10378 //===----------------------------------------------------------------------===// 10379 // SDNode Class 10380 //===----------------------------------------------------------------------===// 10381 10382 bool llvm::isNullConstant(SDValue V) { 10383 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10384 return Const != nullptr && Const->isZero(); 10385 } 10386 10387 bool llvm::isNullFPConstant(SDValue V) { 10388 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10389 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10390 } 10391 10392 bool llvm::isAllOnesConstant(SDValue V) { 10393 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10394 return Const != nullptr && Const->isAllOnes(); 10395 } 10396 10397 bool llvm::isOneConstant(SDValue V) { 10398 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10399 return Const != nullptr && Const->isOne(); 10400 } 10401 10402 bool llvm::isMinSignedConstant(SDValue V) { 10403 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10404 return Const != nullptr && Const->isMinSignedValue(); 10405 } 10406 10407 SDValue llvm::peekThroughBitcasts(SDValue V) { 10408 while (V.getOpcode() == ISD::BITCAST) 10409 V = V.getOperand(0); 10410 return V; 10411 } 10412 10413 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10414 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10415 V = V.getOperand(0); 10416 return V; 10417 } 10418 10419 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10420 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10421 V = V.getOperand(0); 10422 return V; 10423 } 10424 10425 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10426 if (V.getOpcode() != ISD::XOR) 10427 return false; 10428 V = peekThroughBitcasts(V.getOperand(1)); 10429 unsigned NumBits = V.getScalarValueSizeInBits(); 10430 ConstantSDNode *C = 10431 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10432 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10433 } 10434 10435 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10436 bool AllowTruncation) { 10437 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10438 return CN; 10439 10440 // SplatVectors can truncate their operands. Ignore that case here unless 10441 // AllowTruncation is set. 10442 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10443 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10444 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10445 EVT CVT = CN->getValueType(0); 10446 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10447 if (AllowTruncation || CVT == VecEltVT) 10448 return CN; 10449 } 10450 } 10451 10452 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10453 BitVector UndefElements; 10454 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10455 10456 // BuildVectors can truncate their operands. Ignore that case here unless 10457 // AllowTruncation is set. 10458 if (CN && (UndefElements.none() || AllowUndefs)) { 10459 EVT CVT = CN->getValueType(0); 10460 EVT NSVT = N.getValueType().getScalarType(); 10461 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10462 if (AllowTruncation || (CVT == NSVT)) 10463 return CN; 10464 } 10465 } 10466 10467 return nullptr; 10468 } 10469 10470 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10471 bool AllowUndefs, 10472 bool AllowTruncation) { 10473 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10474 return CN; 10475 10476 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10477 BitVector UndefElements; 10478 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10479 10480 // BuildVectors can truncate their operands. Ignore that case here unless 10481 // AllowTruncation is set. 10482 if (CN && (UndefElements.none() || AllowUndefs)) { 10483 EVT CVT = CN->getValueType(0); 10484 EVT NSVT = N.getValueType().getScalarType(); 10485 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10486 if (AllowTruncation || (CVT == NSVT)) 10487 return CN; 10488 } 10489 } 10490 10491 return nullptr; 10492 } 10493 10494 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10495 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10496 return CN; 10497 10498 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10499 BitVector UndefElements; 10500 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10501 if (CN && (UndefElements.none() || AllowUndefs)) 10502 return CN; 10503 } 10504 10505 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10506 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10507 return CN; 10508 10509 return nullptr; 10510 } 10511 10512 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10513 const APInt &DemandedElts, 10514 bool AllowUndefs) { 10515 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10516 return CN; 10517 10518 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10519 BitVector UndefElements; 10520 ConstantFPSDNode *CN = 10521 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10522 if (CN && (UndefElements.none() || AllowUndefs)) 10523 return CN; 10524 } 10525 10526 return nullptr; 10527 } 10528 10529 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10530 // TODO: may want to use peekThroughBitcast() here. 10531 ConstantSDNode *C = 10532 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10533 return C && C->isZero(); 10534 } 10535 10536 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10537 // TODO: may want to use peekThroughBitcast() here. 10538 unsigned BitWidth = N.getScalarValueSizeInBits(); 10539 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10540 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10541 } 10542 10543 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10544 N = peekThroughBitcasts(N); 10545 unsigned BitWidth = N.getScalarValueSizeInBits(); 10546 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10547 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10548 } 10549 10550 HandleSDNode::~HandleSDNode() { 10551 DropOperands(); 10552 } 10553 10554 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10555 const DebugLoc &DL, 10556 const GlobalValue *GA, EVT VT, 10557 int64_t o, unsigned TF) 10558 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10559 TheGlobal = GA; 10560 } 10561 10562 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10563 EVT VT, unsigned SrcAS, 10564 unsigned DestAS) 10565 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10566 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10567 10568 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10569 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10570 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10571 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10572 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10573 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10574 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10575 10576 // We check here that the size of the memory operand fits within the size of 10577 // the MMO. This is because the MMO might indicate only a possible address 10578 // range instead of specifying the affected memory addresses precisely. 10579 // TODO: Make MachineMemOperands aware of scalable vectors. 10580 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10581 "Size mismatch!"); 10582 } 10583 10584 /// Profile - Gather unique data for the node. 10585 /// 10586 void SDNode::Profile(FoldingSetNodeID &ID) const { 10587 AddNodeIDNode(ID, this); 10588 } 10589 10590 namespace { 10591 10592 struct EVTArray { 10593 std::vector<EVT> VTs; 10594 10595 EVTArray() { 10596 VTs.reserve(MVT::VALUETYPE_SIZE); 10597 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10598 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10599 } 10600 }; 10601 10602 } // end anonymous namespace 10603 10604 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10605 static ManagedStatic<EVTArray> SimpleVTArray; 10606 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10607 10608 /// getValueTypeList - Return a pointer to the specified value type. 10609 /// 10610 const EVT *SDNode::getValueTypeList(EVT VT) { 10611 if (VT.isExtended()) { 10612 sys::SmartScopedLock<true> Lock(*VTMutex); 10613 return &(*EVTs->insert(VT).first); 10614 } 10615 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10616 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10617 } 10618 10619 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10620 /// indicated value. This method ignores uses of other values defined by this 10621 /// operation. 10622 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10623 assert(Value < getNumValues() && "Bad value!"); 10624 10625 // TODO: Only iterate over uses of a given value of the node 10626 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10627 if (UI.getUse().getResNo() == Value) { 10628 if (NUses == 0) 10629 return false; 10630 --NUses; 10631 } 10632 } 10633 10634 // Found exactly the right number of uses? 10635 return NUses == 0; 10636 } 10637 10638 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10639 /// value. This method ignores uses of other values defined by this operation. 10640 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10641 assert(Value < getNumValues() && "Bad value!"); 10642 10643 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10644 if (UI.getUse().getResNo() == Value) 10645 return true; 10646 10647 return false; 10648 } 10649 10650 /// isOnlyUserOf - Return true if this node is the only use of N. 10651 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10652 bool Seen = false; 10653 for (const SDNode *User : N->uses()) { 10654 if (User == this) 10655 Seen = true; 10656 else 10657 return false; 10658 } 10659 10660 return Seen; 10661 } 10662 10663 /// Return true if the only users of N are contained in Nodes. 10664 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10665 bool Seen = false; 10666 for (const SDNode *User : N->uses()) { 10667 if (llvm::is_contained(Nodes, User)) 10668 Seen = true; 10669 else 10670 return false; 10671 } 10672 10673 return Seen; 10674 } 10675 10676 /// isOperand - Return true if this node is an operand of N. 10677 bool SDValue::isOperandOf(const SDNode *N) const { 10678 return is_contained(N->op_values(), *this); 10679 } 10680 10681 bool SDNode::isOperandOf(const SDNode *N) const { 10682 return any_of(N->op_values(), 10683 [this](SDValue Op) { return this == Op.getNode(); }); 10684 } 10685 10686 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10687 /// be a chain) reaches the specified operand without crossing any 10688 /// side-effecting instructions on any chain path. In practice, this looks 10689 /// through token factors and non-volatile loads. In order to remain efficient, 10690 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10691 /// 10692 /// Note that we only need to examine chains when we're searching for 10693 /// side-effects; SelectionDAG requires that all side-effects are represented 10694 /// by chains, even if another operand would force a specific ordering. This 10695 /// constraint is necessary to allow transformations like splitting loads. 10696 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10697 unsigned Depth) const { 10698 if (*this == Dest) return true; 10699 10700 // Don't search too deeply, we just want to be able to see through 10701 // TokenFactor's etc. 10702 if (Depth == 0) return false; 10703 10704 // If this is a token factor, all inputs to the TF happen in parallel. 10705 if (getOpcode() == ISD::TokenFactor) { 10706 // First, try a shallow search. 10707 if (is_contained((*this)->ops(), Dest)) { 10708 // We found the chain we want as an operand of this TokenFactor. 10709 // Essentially, we reach the chain without side-effects if we could 10710 // serialize the TokenFactor into a simple chain of operations with 10711 // Dest as the last operation. This is automatically true if the 10712 // chain has one use: there are no other ordering constraints. 10713 // If the chain has more than one use, we give up: some other 10714 // use of Dest might force a side-effect between Dest and the current 10715 // node. 10716 if (Dest.hasOneUse()) 10717 return true; 10718 } 10719 // Next, try a deep search: check whether every operand of the TokenFactor 10720 // reaches Dest. 10721 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10722 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10723 }); 10724 } 10725 10726 // Loads don't have side effects, look through them. 10727 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10728 if (Ld->isUnordered()) 10729 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10730 } 10731 return false; 10732 } 10733 10734 bool SDNode::hasPredecessor(const SDNode *N) const { 10735 SmallPtrSet<const SDNode *, 32> Visited; 10736 SmallVector<const SDNode *, 16> Worklist; 10737 Worklist.push_back(this); 10738 return hasPredecessorHelper(N, Visited, Worklist); 10739 } 10740 10741 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10742 this->Flags.intersectWith(Flags); 10743 } 10744 10745 SDValue 10746 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10747 ArrayRef<ISD::NodeType> CandidateBinOps, 10748 bool AllowPartials) { 10749 // The pattern must end in an extract from index 0. 10750 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10751 !isNullConstant(Extract->getOperand(1))) 10752 return SDValue(); 10753 10754 // Match against one of the candidate binary ops. 10755 SDValue Op = Extract->getOperand(0); 10756 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10757 return Op.getOpcode() == unsigned(BinOp); 10758 })) 10759 return SDValue(); 10760 10761 // Floating-point reductions may require relaxed constraints on the final step 10762 // of the reduction because they may reorder intermediate operations. 10763 unsigned CandidateBinOp = Op.getOpcode(); 10764 if (Op.getValueType().isFloatingPoint()) { 10765 SDNodeFlags Flags = Op->getFlags(); 10766 switch (CandidateBinOp) { 10767 case ISD::FADD: 10768 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10769 return SDValue(); 10770 break; 10771 default: 10772 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10773 } 10774 } 10775 10776 // Matching failed - attempt to see if we did enough stages that a partial 10777 // reduction from a subvector is possible. 10778 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10779 if (!AllowPartials || !Op) 10780 return SDValue(); 10781 EVT OpVT = Op.getValueType(); 10782 EVT OpSVT = OpVT.getScalarType(); 10783 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10784 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10785 return SDValue(); 10786 BinOp = (ISD::NodeType)CandidateBinOp; 10787 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10788 getVectorIdxConstant(0, SDLoc(Op))); 10789 }; 10790 10791 // At each stage, we're looking for something that looks like: 10792 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10793 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10794 // i32 undef, i32 undef, i32 undef, i32 undef> 10795 // %a = binop <8 x i32> %op, %s 10796 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10797 // we expect something like: 10798 // <4,5,6,7,u,u,u,u> 10799 // <2,3,u,u,u,u,u,u> 10800 // <1,u,u,u,u,u,u,u> 10801 // While a partial reduction match would be: 10802 // <2,3,u,u,u,u,u,u> 10803 // <1,u,u,u,u,u,u,u> 10804 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10805 SDValue PrevOp; 10806 for (unsigned i = 0; i < Stages; ++i) { 10807 unsigned MaskEnd = (1 << i); 10808 10809 if (Op.getOpcode() != CandidateBinOp) 10810 return PartialReduction(PrevOp, MaskEnd); 10811 10812 SDValue Op0 = Op.getOperand(0); 10813 SDValue Op1 = Op.getOperand(1); 10814 10815 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10816 if (Shuffle) { 10817 Op = Op1; 10818 } else { 10819 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10820 Op = Op0; 10821 } 10822 10823 // The first operand of the shuffle should be the same as the other operand 10824 // of the binop. 10825 if (!Shuffle || Shuffle->getOperand(0) != Op) 10826 return PartialReduction(PrevOp, MaskEnd); 10827 10828 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10829 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10830 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10831 return PartialReduction(PrevOp, MaskEnd); 10832 10833 PrevOp = Op; 10834 } 10835 10836 // Handle subvector reductions, which tend to appear after the shuffle 10837 // reduction stages. 10838 while (Op.getOpcode() == CandidateBinOp) { 10839 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10840 SDValue Op0 = Op.getOperand(0); 10841 SDValue Op1 = Op.getOperand(1); 10842 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10843 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10844 Op0.getOperand(0) != Op1.getOperand(0)) 10845 break; 10846 SDValue Src = Op0.getOperand(0); 10847 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10848 if (NumSrcElts != (2 * NumElts)) 10849 break; 10850 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10851 Op1.getConstantOperandAPInt(1) == NumElts) && 10852 !(Op1.getConstantOperandAPInt(1) == 0 && 10853 Op0.getConstantOperandAPInt(1) == NumElts)) 10854 break; 10855 Op = Src; 10856 } 10857 10858 BinOp = (ISD::NodeType)CandidateBinOp; 10859 return Op; 10860 } 10861 10862 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10863 assert(N->getNumValues() == 1 && 10864 "Can't unroll a vector with multiple results!"); 10865 10866 EVT VT = N->getValueType(0); 10867 unsigned NE = VT.getVectorNumElements(); 10868 EVT EltVT = VT.getVectorElementType(); 10869 SDLoc dl(N); 10870 10871 SmallVector<SDValue, 8> Scalars; 10872 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10873 10874 // If ResNE is 0, fully unroll the vector op. 10875 if (ResNE == 0) 10876 ResNE = NE; 10877 else if (NE > ResNE) 10878 NE = ResNE; 10879 10880 unsigned i; 10881 for (i= 0; i != NE; ++i) { 10882 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10883 SDValue Operand = N->getOperand(j); 10884 EVT OperandVT = Operand.getValueType(); 10885 if (OperandVT.isVector()) { 10886 // A vector operand; extract a single element. 10887 EVT OperandEltVT = OperandVT.getVectorElementType(); 10888 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10889 Operand, getVectorIdxConstant(i, dl)); 10890 } else { 10891 // A scalar operand; just use it as is. 10892 Operands[j] = Operand; 10893 } 10894 } 10895 10896 switch (N->getOpcode()) { 10897 default: { 10898 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10899 N->getFlags())); 10900 break; 10901 } 10902 case ISD::VSELECT: 10903 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10904 break; 10905 case ISD::SHL: 10906 case ISD::SRA: 10907 case ISD::SRL: 10908 case ISD::ROTL: 10909 case ISD::ROTR: 10910 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10911 getShiftAmountOperand(Operands[0].getValueType(), 10912 Operands[1]))); 10913 break; 10914 case ISD::SIGN_EXTEND_INREG: { 10915 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10916 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10917 Operands[0], 10918 getValueType(ExtVT))); 10919 } 10920 } 10921 } 10922 10923 for (; i < ResNE; ++i) 10924 Scalars.push_back(getUNDEF(EltVT)); 10925 10926 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10927 return getBuildVector(VecVT, dl, Scalars); 10928 } 10929 10930 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10931 SDNode *N, unsigned ResNE) { 10932 unsigned Opcode = N->getOpcode(); 10933 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10934 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10935 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10936 "Expected an overflow opcode"); 10937 10938 EVT ResVT = N->getValueType(0); 10939 EVT OvVT = N->getValueType(1); 10940 EVT ResEltVT = ResVT.getVectorElementType(); 10941 EVT OvEltVT = OvVT.getVectorElementType(); 10942 SDLoc dl(N); 10943 10944 // If ResNE is 0, fully unroll the vector op. 10945 unsigned NE = ResVT.getVectorNumElements(); 10946 if (ResNE == 0) 10947 ResNE = NE; 10948 else if (NE > ResNE) 10949 NE = ResNE; 10950 10951 SmallVector<SDValue, 8> LHSScalars; 10952 SmallVector<SDValue, 8> RHSScalars; 10953 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10954 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10955 10956 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10957 SDVTList VTs = getVTList(ResEltVT, SVT); 10958 SmallVector<SDValue, 8> ResScalars; 10959 SmallVector<SDValue, 8> OvScalars; 10960 for (unsigned i = 0; i < NE; ++i) { 10961 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10962 SDValue Ov = 10963 getSelect(dl, OvEltVT, Res.getValue(1), 10964 getBoolConstant(true, dl, OvEltVT, ResVT), 10965 getConstant(0, dl, OvEltVT)); 10966 10967 ResScalars.push_back(Res); 10968 OvScalars.push_back(Ov); 10969 } 10970 10971 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10972 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10973 10974 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10975 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10976 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10977 getBuildVector(NewOvVT, dl, OvScalars)); 10978 } 10979 10980 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10981 LoadSDNode *Base, 10982 unsigned Bytes, 10983 int Dist) const { 10984 if (LD->isVolatile() || Base->isVolatile()) 10985 return false; 10986 // TODO: probably too restrictive for atomics, revisit 10987 if (!LD->isSimple()) 10988 return false; 10989 if (LD->isIndexed() || Base->isIndexed()) 10990 return false; 10991 if (LD->getChain() != Base->getChain()) 10992 return false; 10993 EVT VT = LD->getValueType(0); 10994 if (VT.getSizeInBits() / 8 != Bytes) 10995 return false; 10996 10997 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10998 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10999 11000 int64_t Offset = 0; 11001 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 11002 return (Dist * Bytes == Offset); 11003 return false; 11004 } 11005 11006 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 11007 /// if it cannot be inferred. 11008 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 11009 // If this is a GlobalAddress + cst, return the alignment. 11010 const GlobalValue *GV = nullptr; 11011 int64_t GVOffset = 0; 11012 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 11013 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 11014 KnownBits Known(PtrWidth); 11015 llvm::computeKnownBits(GV, Known, getDataLayout()); 11016 unsigned AlignBits = Known.countMinTrailingZeros(); 11017 if (AlignBits) 11018 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11019 } 11020 11021 // If this is a direct reference to a stack slot, use information about the 11022 // stack slot's alignment. 11023 int FrameIdx = INT_MIN; 11024 int64_t FrameOffset = 0; 11025 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11026 FrameIdx = FI->getIndex(); 11027 } else if (isBaseWithConstantOffset(Ptr) && 11028 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11029 // Handle FI+Cst 11030 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11031 FrameOffset = Ptr.getConstantOperandVal(1); 11032 } 11033 11034 if (FrameIdx != INT_MIN) { 11035 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11036 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11037 } 11038 11039 return None; 11040 } 11041 11042 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11043 /// which is split (or expanded) into two not necessarily identical pieces. 11044 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11045 // Currently all types are split in half. 11046 EVT LoVT, HiVT; 11047 if (!VT.isVector()) 11048 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11049 else 11050 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11051 11052 return std::make_pair(LoVT, HiVT); 11053 } 11054 11055 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11056 /// type, dependent on an enveloping VT that has been split into two identical 11057 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11058 std::pair<EVT, EVT> 11059 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11060 bool *HiIsEmpty) const { 11061 EVT EltTp = VT.getVectorElementType(); 11062 // Examples: 11063 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11064 // custom VL=9 with enveloping VL=8/8 yields 8/1 11065 // custom VL=10 with enveloping VL=8/8 yields 8/2 11066 // etc. 11067 ElementCount VTNumElts = VT.getVectorElementCount(); 11068 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11069 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11070 "Mixing fixed width and scalable vectors when enveloping a type"); 11071 EVT LoVT, HiVT; 11072 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11073 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11074 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11075 *HiIsEmpty = false; 11076 } else { 11077 // Flag that hi type has zero storage size, but return split envelop type 11078 // (this would be easier if vector types with zero elements were allowed). 11079 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11080 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11081 *HiIsEmpty = true; 11082 } 11083 return std::make_pair(LoVT, HiVT); 11084 } 11085 11086 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11087 /// low/high part. 11088 std::pair<SDValue, SDValue> 11089 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11090 const EVT &HiVT) { 11091 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 11092 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 11093 "Splitting vector with an invalid mixture of fixed and scalable " 11094 "vector types"); 11095 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 11096 N.getValueType().getVectorMinNumElements() && 11097 "More vector elements requested than available!"); 11098 SDValue Lo, Hi; 11099 Lo = 11100 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 11101 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 11102 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 11103 // IDX with the runtime scaling factor of the result vector type. For 11104 // fixed-width result vectors, that runtime scaling factor is 1. 11105 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 11106 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 11107 return std::make_pair(Lo, Hi); 11108 } 11109 11110 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 11111 const SDLoc &DL) { 11112 // Split the vector length parameter. 11113 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 11114 EVT VT = N.getValueType(); 11115 assert(VecVT.getVectorElementCount().isKnownEven() && 11116 "Expecting the mask to be an evenly-sized vector"); 11117 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 11118 SDValue HalfNumElts = 11119 VecVT.isFixedLengthVector() 11120 ? getConstant(HalfMinNumElts, DL, VT) 11121 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 11122 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 11123 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 11124 return std::make_pair(Lo, Hi); 11125 } 11126 11127 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 11128 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 11129 EVT VT = N.getValueType(); 11130 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 11131 NextPowerOf2(VT.getVectorNumElements())); 11132 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 11133 getVectorIdxConstant(0, DL)); 11134 } 11135 11136 void SelectionDAG::ExtractVectorElements(SDValue Op, 11137 SmallVectorImpl<SDValue> &Args, 11138 unsigned Start, unsigned Count, 11139 EVT EltVT) { 11140 EVT VT = Op.getValueType(); 11141 if (Count == 0) 11142 Count = VT.getVectorNumElements(); 11143 if (EltVT == EVT()) 11144 EltVT = VT.getVectorElementType(); 11145 SDLoc SL(Op); 11146 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 11147 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 11148 getVectorIdxConstant(i, SL))); 11149 } 11150 } 11151 11152 // getAddressSpace - Return the address space this GlobalAddress belongs to. 11153 unsigned GlobalAddressSDNode::getAddressSpace() const { 11154 return getGlobal()->getType()->getAddressSpace(); 11155 } 11156 11157 Type *ConstantPoolSDNode::getType() const { 11158 if (isMachineConstantPoolEntry()) 11159 return Val.MachineCPVal->getType(); 11160 return Val.ConstVal->getType(); 11161 } 11162 11163 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 11164 unsigned &SplatBitSize, 11165 bool &HasAnyUndefs, 11166 unsigned MinSplatBits, 11167 bool IsBigEndian) const { 11168 EVT VT = getValueType(0); 11169 assert(VT.isVector() && "Expected a vector type"); 11170 unsigned VecWidth = VT.getSizeInBits(); 11171 if (MinSplatBits > VecWidth) 11172 return false; 11173 11174 // FIXME: The widths are based on this node's type, but build vectors can 11175 // truncate their operands. 11176 SplatValue = APInt(VecWidth, 0); 11177 SplatUndef = APInt(VecWidth, 0); 11178 11179 // Get the bits. Bits with undefined values (when the corresponding element 11180 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 11181 // in SplatValue. If any of the values are not constant, give up and return 11182 // false. 11183 unsigned int NumOps = getNumOperands(); 11184 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 11185 unsigned EltWidth = VT.getScalarSizeInBits(); 11186 11187 for (unsigned j = 0; j < NumOps; ++j) { 11188 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 11189 SDValue OpVal = getOperand(i); 11190 unsigned BitPos = j * EltWidth; 11191 11192 if (OpVal.isUndef()) 11193 SplatUndef.setBits(BitPos, BitPos + EltWidth); 11194 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 11195 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 11196 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 11197 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 11198 else 11199 return false; 11200 } 11201 11202 // The build_vector is all constants or undefs. Find the smallest element 11203 // size that splats the vector. 11204 HasAnyUndefs = (SplatUndef != 0); 11205 11206 // FIXME: This does not work for vectors with elements less than 8 bits. 11207 while (VecWidth > 8) { 11208 unsigned HalfSize = VecWidth / 2; 11209 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 11210 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 11211 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 11212 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 11213 11214 // If the two halves do not match (ignoring undef bits), stop here. 11215 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 11216 MinSplatBits > HalfSize) 11217 break; 11218 11219 SplatValue = HighValue | LowValue; 11220 SplatUndef = HighUndef & LowUndef; 11221 11222 VecWidth = HalfSize; 11223 } 11224 11225 SplatBitSize = VecWidth; 11226 return true; 11227 } 11228 11229 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 11230 BitVector *UndefElements) const { 11231 unsigned NumOps = getNumOperands(); 11232 if (UndefElements) { 11233 UndefElements->clear(); 11234 UndefElements->resize(NumOps); 11235 } 11236 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11237 if (!DemandedElts) 11238 return SDValue(); 11239 SDValue Splatted; 11240 for (unsigned i = 0; i != NumOps; ++i) { 11241 if (!DemandedElts[i]) 11242 continue; 11243 SDValue Op = getOperand(i); 11244 if (Op.isUndef()) { 11245 if (UndefElements) 11246 (*UndefElements)[i] = true; 11247 } else if (!Splatted) { 11248 Splatted = Op; 11249 } else if (Splatted != Op) { 11250 return SDValue(); 11251 } 11252 } 11253 11254 if (!Splatted) { 11255 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 11256 assert(getOperand(FirstDemandedIdx).isUndef() && 11257 "Can only have a splat without a constant for all undefs."); 11258 return getOperand(FirstDemandedIdx); 11259 } 11260 11261 return Splatted; 11262 } 11263 11264 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 11265 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11266 return getSplatValue(DemandedElts, UndefElements); 11267 } 11268 11269 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 11270 SmallVectorImpl<SDValue> &Sequence, 11271 BitVector *UndefElements) const { 11272 unsigned NumOps = getNumOperands(); 11273 Sequence.clear(); 11274 if (UndefElements) { 11275 UndefElements->clear(); 11276 UndefElements->resize(NumOps); 11277 } 11278 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11279 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 11280 return false; 11281 11282 // Set the undefs even if we don't find a sequence (like getSplatValue). 11283 if (UndefElements) 11284 for (unsigned I = 0; I != NumOps; ++I) 11285 if (DemandedElts[I] && getOperand(I).isUndef()) 11286 (*UndefElements)[I] = true; 11287 11288 // Iteratively widen the sequence length looking for repetitions. 11289 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 11290 Sequence.append(SeqLen, SDValue()); 11291 for (unsigned I = 0; I != NumOps; ++I) { 11292 if (!DemandedElts[I]) 11293 continue; 11294 SDValue &SeqOp = Sequence[I % SeqLen]; 11295 SDValue Op = getOperand(I); 11296 if (Op.isUndef()) { 11297 if (!SeqOp) 11298 SeqOp = Op; 11299 continue; 11300 } 11301 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 11302 Sequence.clear(); 11303 break; 11304 } 11305 SeqOp = Op; 11306 } 11307 if (!Sequence.empty()) 11308 return true; 11309 } 11310 11311 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 11312 return false; 11313 } 11314 11315 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 11316 BitVector *UndefElements) const { 11317 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11318 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 11319 } 11320 11321 ConstantSDNode * 11322 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 11323 BitVector *UndefElements) const { 11324 return dyn_cast_or_null<ConstantSDNode>( 11325 getSplatValue(DemandedElts, UndefElements)); 11326 } 11327 11328 ConstantSDNode * 11329 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 11330 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 11331 } 11332 11333 ConstantFPSDNode * 11334 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 11335 BitVector *UndefElements) const { 11336 return dyn_cast_or_null<ConstantFPSDNode>( 11337 getSplatValue(DemandedElts, UndefElements)); 11338 } 11339 11340 ConstantFPSDNode * 11341 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 11342 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 11343 } 11344 11345 int32_t 11346 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 11347 uint32_t BitWidth) const { 11348 if (ConstantFPSDNode *CN = 11349 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 11350 bool IsExact; 11351 APSInt IntVal(BitWidth); 11352 const APFloat &APF = CN->getValueAPF(); 11353 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 11354 APFloat::opOK || 11355 !IsExact) 11356 return -1; 11357 11358 return IntVal.exactLogBase2(); 11359 } 11360 return -1; 11361 } 11362 11363 bool BuildVectorSDNode::getConstantRawBits( 11364 bool IsLittleEndian, unsigned DstEltSizeInBits, 11365 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 11366 // Early-out if this contains anything but Undef/Constant/ConstantFP. 11367 if (!isConstant()) 11368 return false; 11369 11370 unsigned NumSrcOps = getNumOperands(); 11371 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 11372 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11373 "Invalid bitcast scale"); 11374 11375 // Extract raw src bits. 11376 SmallVector<APInt> SrcBitElements(NumSrcOps, 11377 APInt::getNullValue(SrcEltSizeInBits)); 11378 BitVector SrcUndeElements(NumSrcOps, false); 11379 11380 for (unsigned I = 0; I != NumSrcOps; ++I) { 11381 SDValue Op = getOperand(I); 11382 if (Op.isUndef()) { 11383 SrcUndeElements.set(I); 11384 continue; 11385 } 11386 auto *CInt = dyn_cast<ConstantSDNode>(Op); 11387 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 11388 assert((CInt || CFP) && "Unknown constant"); 11389 SrcBitElements[I] = 11390 CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits) 11391 : CFP->getValueAPF().bitcastToAPInt(); 11392 } 11393 11394 // Recast to dst width. 11395 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11396 SrcBitElements, UndefElements, SrcUndeElements); 11397 return true; 11398 } 11399 11400 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11401 unsigned DstEltSizeInBits, 11402 SmallVectorImpl<APInt> &DstBitElements, 11403 ArrayRef<APInt> SrcBitElements, 11404 BitVector &DstUndefElements, 11405 const BitVector &SrcUndefElements) { 11406 unsigned NumSrcOps = SrcBitElements.size(); 11407 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11408 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11409 "Invalid bitcast scale"); 11410 assert(NumSrcOps == SrcUndefElements.size() && 11411 "Vector size mismatch"); 11412 11413 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11414 DstUndefElements.clear(); 11415 DstUndefElements.resize(NumDstOps, false); 11416 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11417 11418 // Concatenate src elements constant bits together into dst element. 11419 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11420 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11421 for (unsigned I = 0; I != NumDstOps; ++I) { 11422 DstUndefElements.set(I); 11423 APInt &DstBits = DstBitElements[I]; 11424 for (unsigned J = 0; J != Scale; ++J) { 11425 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11426 if (SrcUndefElements[Idx]) 11427 continue; 11428 DstUndefElements.reset(I); 11429 const APInt &SrcBits = SrcBitElements[Idx]; 11430 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11431 "Illegal constant bitwidths"); 11432 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11433 } 11434 } 11435 return; 11436 } 11437 11438 // Split src element constant bits into dst elements. 11439 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11440 for (unsigned I = 0; I != NumSrcOps; ++I) { 11441 if (SrcUndefElements[I]) { 11442 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11443 continue; 11444 } 11445 const APInt &SrcBits = SrcBitElements[I]; 11446 for (unsigned J = 0; J != Scale; ++J) { 11447 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11448 APInt &DstBits = DstBitElements[Idx]; 11449 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11450 } 11451 } 11452 } 11453 11454 bool BuildVectorSDNode::isConstant() const { 11455 for (const SDValue &Op : op_values()) { 11456 unsigned Opc = Op.getOpcode(); 11457 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11458 return false; 11459 } 11460 return true; 11461 } 11462 11463 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11464 // Find the first non-undef value in the shuffle mask. 11465 unsigned i, e; 11466 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11467 /* search */; 11468 11469 // If all elements are undefined, this shuffle can be considered a splat 11470 // (although it should eventually get simplified away completely). 11471 if (i == e) 11472 return true; 11473 11474 // Make sure all remaining elements are either undef or the same as the first 11475 // non-undef value. 11476 for (int Idx = Mask[i]; i != e; ++i) 11477 if (Mask[i] >= 0 && Mask[i] != Idx) 11478 return false; 11479 return true; 11480 } 11481 11482 // Returns the SDNode if it is a constant integer BuildVector 11483 // or constant integer. 11484 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11485 if (isa<ConstantSDNode>(N)) 11486 return N.getNode(); 11487 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11488 return N.getNode(); 11489 // Treat a GlobalAddress supporting constant offset folding as a 11490 // constant integer. 11491 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11492 if (GA->getOpcode() == ISD::GlobalAddress && 11493 TLI->isOffsetFoldingLegal(GA)) 11494 return GA; 11495 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11496 isa<ConstantSDNode>(N.getOperand(0))) 11497 return N.getNode(); 11498 return nullptr; 11499 } 11500 11501 // Returns the SDNode if it is a constant float BuildVector 11502 // or constant float. 11503 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11504 if (isa<ConstantFPSDNode>(N)) 11505 return N.getNode(); 11506 11507 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11508 return N.getNode(); 11509 11510 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11511 isa<ConstantFPSDNode>(N.getOperand(0))) 11512 return N.getNode(); 11513 11514 return nullptr; 11515 } 11516 11517 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11518 assert(!Node->OperandList && "Node already has operands"); 11519 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11520 "too many operands to fit into SDNode"); 11521 SDUse *Ops = OperandRecycler.allocate( 11522 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11523 11524 bool IsDivergent = false; 11525 for (unsigned I = 0; I != Vals.size(); ++I) { 11526 Ops[I].setUser(Node); 11527 Ops[I].setInitial(Vals[I]); 11528 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11529 IsDivergent |= Ops[I].getNode()->isDivergent(); 11530 } 11531 Node->NumOperands = Vals.size(); 11532 Node->OperandList = Ops; 11533 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11534 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11535 Node->SDNodeBits.IsDivergent = IsDivergent; 11536 } 11537 checkForCycles(Node); 11538 } 11539 11540 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11541 SmallVectorImpl<SDValue> &Vals) { 11542 size_t Limit = SDNode::getMaxNumOperands(); 11543 while (Vals.size() > Limit) { 11544 unsigned SliceIdx = Vals.size() - Limit; 11545 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11546 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11547 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11548 Vals.emplace_back(NewTF); 11549 } 11550 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11551 } 11552 11553 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11554 EVT VT, SDNodeFlags Flags) { 11555 switch (Opcode) { 11556 default: 11557 return SDValue(); 11558 case ISD::ADD: 11559 case ISD::OR: 11560 case ISD::XOR: 11561 case ISD::UMAX: 11562 return getConstant(0, DL, VT); 11563 case ISD::MUL: 11564 return getConstant(1, DL, VT); 11565 case ISD::AND: 11566 case ISD::UMIN: 11567 return getAllOnesConstant(DL, VT); 11568 case ISD::SMAX: 11569 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11570 case ISD::SMIN: 11571 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11572 case ISD::FADD: 11573 return getConstantFP(-0.0, DL, VT); 11574 case ISD::FMUL: 11575 return getConstantFP(1.0, DL, VT); 11576 case ISD::FMINNUM: 11577 case ISD::FMAXNUM: { 11578 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11579 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11580 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11581 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11582 APFloat::getLargest(Semantics); 11583 if (Opcode == ISD::FMAXNUM) 11584 NeutralAF.changeSign(); 11585 11586 return getConstantFP(NeutralAF, DL, VT); 11587 } 11588 } 11589 } 11590 11591 #ifndef NDEBUG 11592 static void checkForCyclesHelper(const SDNode *N, 11593 SmallPtrSetImpl<const SDNode*> &Visited, 11594 SmallPtrSetImpl<const SDNode*> &Checked, 11595 const llvm::SelectionDAG *DAG) { 11596 // If this node has already been checked, don't check it again. 11597 if (Checked.count(N)) 11598 return; 11599 11600 // If a node has already been visited on this depth-first walk, reject it as 11601 // a cycle. 11602 if (!Visited.insert(N).second) { 11603 errs() << "Detected cycle in SelectionDAG\n"; 11604 dbgs() << "Offending node:\n"; 11605 N->dumprFull(DAG); dbgs() << "\n"; 11606 abort(); 11607 } 11608 11609 for (const SDValue &Op : N->op_values()) 11610 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11611 11612 Checked.insert(N); 11613 Visited.erase(N); 11614 } 11615 #endif 11616 11617 void llvm::checkForCycles(const llvm::SDNode *N, 11618 const llvm::SelectionDAG *DAG, 11619 bool force) { 11620 #ifndef NDEBUG 11621 bool check = force; 11622 #ifdef EXPENSIVE_CHECKS 11623 check = true; 11624 #endif // EXPENSIVE_CHECKS 11625 if (check) { 11626 assert(N && "Checking nonexistent SDNode"); 11627 SmallPtrSet<const SDNode*, 32> visited; 11628 SmallPtrSet<const SDNode*, 32> checked; 11629 checkForCyclesHelper(N, visited, checked, DAG); 11630 } 11631 #endif // !NDEBUG 11632 } 11633 11634 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11635 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11636 } 11637