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().trunc(EltSize); 145 return true; 146 } 147 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 148 SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(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::getVPLogicalNOT(const SDLoc &DL, SDValue Val, 1429 SDValue Mask, SDValue EVL, EVT VT) { 1430 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1431 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL); 1432 } 1433 1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1435 EVT OpVT) { 1436 if (!V) 1437 return getConstant(0, DL, VT); 1438 1439 switch (TLI->getBooleanContents(OpVT)) { 1440 case TargetLowering::ZeroOrOneBooleanContent: 1441 case TargetLowering::UndefinedBooleanContent: 1442 return getConstant(1, DL, VT); 1443 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1444 return getAllOnesConstant(DL, VT); 1445 } 1446 llvm_unreachable("Unexpected boolean content enum!"); 1447 } 1448 1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1450 bool isT, bool isO) { 1451 EVT EltVT = VT.getScalarType(); 1452 assert((EltVT.getSizeInBits() >= 64 || 1453 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1454 "getConstant with a uint64_t value that doesn't fit in the type!"); 1455 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1456 } 1457 1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1459 bool isT, bool isO) { 1460 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1461 } 1462 1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1464 EVT VT, bool isT, bool isO) { 1465 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1466 1467 EVT EltVT = VT.getScalarType(); 1468 const ConstantInt *Elt = &Val; 1469 1470 // In some cases the vector type is legal but the element type is illegal and 1471 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1472 // inserted value (the type does not need to match the vector element type). 1473 // Any extra bits introduced will be truncated away. 1474 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1475 TargetLowering::TypePromoteInteger) { 1476 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1477 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1478 Elt = ConstantInt::get(*getContext(), NewVal); 1479 } 1480 // In other cases the element type is illegal and needs to be expanded, for 1481 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1482 // the value into n parts and use a vector type with n-times the elements. 1483 // Then bitcast to the type requested. 1484 // Legalizing constants too early makes the DAGCombiner's job harder so we 1485 // only legalize if the DAG tells us we must produce legal types. 1486 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1487 TLI->getTypeAction(*getContext(), EltVT) == 1488 TargetLowering::TypeExpandInteger) { 1489 const APInt &NewVal = Elt->getValue(); 1490 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1491 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1492 1493 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1494 if (VT.isScalableVector()) { 1495 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1496 "Can only handle an even split!"); 1497 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1498 1499 SmallVector<SDValue, 2> ScalarParts; 1500 for (unsigned i = 0; i != Parts; ++i) 1501 ScalarParts.push_back(getConstant( 1502 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1503 ViaEltVT, isT, isO)); 1504 1505 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1506 } 1507 1508 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1509 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1510 1511 // Check the temporary vector is the correct size. If this fails then 1512 // getTypeToTransformTo() probably returned a type whose size (in bits) 1513 // isn't a power-of-2 factor of the requested type size. 1514 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1515 1516 SmallVector<SDValue, 2> EltParts; 1517 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1518 EltParts.push_back(getConstant( 1519 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1520 ViaEltVT, isT, isO)); 1521 1522 // EltParts is currently in little endian order. If we actually want 1523 // big-endian order then reverse it now. 1524 if (getDataLayout().isBigEndian()) 1525 std::reverse(EltParts.begin(), EltParts.end()); 1526 1527 // The elements must be reversed when the element order is different 1528 // to the endianness of the elements (because the BITCAST is itself a 1529 // vector shuffle in this situation). However, we do not need any code to 1530 // perform this reversal because getConstant() is producing a vector 1531 // splat. 1532 // This situation occurs in MIPS MSA. 1533 1534 SmallVector<SDValue, 8> Ops; 1535 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1536 llvm::append_range(Ops, EltParts); 1537 1538 SDValue V = 1539 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1540 return V; 1541 } 1542 1543 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1544 "APInt size does not match type size!"); 1545 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1546 FoldingSetNodeID ID; 1547 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1548 ID.AddPointer(Elt); 1549 ID.AddBoolean(isO); 1550 void *IP = nullptr; 1551 SDNode *N = nullptr; 1552 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1553 if (!VT.isVector()) 1554 return SDValue(N, 0); 1555 1556 if (!N) { 1557 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1558 CSEMap.InsertNode(N, IP); 1559 InsertNode(N); 1560 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1561 } 1562 1563 SDValue Result(N, 0); 1564 if (VT.isScalableVector()) 1565 Result = getSplatVector(VT, DL, Result); 1566 else if (VT.isVector()) 1567 Result = getSplatBuildVector(VT, DL, Result); 1568 1569 return Result; 1570 } 1571 1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1573 bool isTarget) { 1574 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1575 } 1576 1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1578 const SDLoc &DL, bool LegalTypes) { 1579 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1580 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1581 return getConstant(Val, DL, ShiftVT); 1582 } 1583 1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1585 bool isTarget) { 1586 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1587 } 1588 1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1590 bool isTarget) { 1591 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1592 } 1593 1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1595 EVT VT, bool isTarget) { 1596 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1597 1598 EVT EltVT = VT.getScalarType(); 1599 1600 // Do the map lookup using the actual bit pattern for the floating point 1601 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1602 // we don't have issues with SNANs. 1603 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1604 FoldingSetNodeID ID; 1605 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1606 ID.AddPointer(&V); 1607 void *IP = nullptr; 1608 SDNode *N = nullptr; 1609 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1610 if (!VT.isVector()) 1611 return SDValue(N, 0); 1612 1613 if (!N) { 1614 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1615 CSEMap.InsertNode(N, IP); 1616 InsertNode(N); 1617 } 1618 1619 SDValue Result(N, 0); 1620 if (VT.isScalableVector()) 1621 Result = getSplatVector(VT, DL, Result); 1622 else if (VT.isVector()) 1623 Result = getSplatBuildVector(VT, DL, Result); 1624 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1625 return Result; 1626 } 1627 1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1629 bool isTarget) { 1630 EVT EltVT = VT.getScalarType(); 1631 if (EltVT == MVT::f32) 1632 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1633 if (EltVT == MVT::f64) 1634 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1635 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1636 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1637 bool Ignored; 1638 APFloat APF = APFloat(Val); 1639 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1640 &Ignored); 1641 return getConstantFP(APF, DL, VT, isTarget); 1642 } 1643 llvm_unreachable("Unsupported type in getConstantFP"); 1644 } 1645 1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1647 EVT VT, int64_t Offset, bool isTargetGA, 1648 unsigned TargetFlags) { 1649 assert((TargetFlags == 0 || isTargetGA) && 1650 "Cannot set target flags on target-independent globals"); 1651 1652 // Truncate (with sign-extension) the offset value to the pointer size. 1653 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1654 if (BitWidth < 64) 1655 Offset = SignExtend64(Offset, BitWidth); 1656 1657 unsigned Opc; 1658 if (GV->isThreadLocal()) 1659 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1660 else 1661 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1662 1663 FoldingSetNodeID ID; 1664 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1665 ID.AddPointer(GV); 1666 ID.AddInteger(Offset); 1667 ID.AddInteger(TargetFlags); 1668 void *IP = nullptr; 1669 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1670 return SDValue(E, 0); 1671 1672 auto *N = newSDNode<GlobalAddressSDNode>( 1673 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1674 CSEMap.InsertNode(N, IP); 1675 InsertNode(N); 1676 return SDValue(N, 0); 1677 } 1678 1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1680 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1681 FoldingSetNodeID ID; 1682 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1683 ID.AddInteger(FI); 1684 void *IP = nullptr; 1685 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1686 return SDValue(E, 0); 1687 1688 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1689 CSEMap.InsertNode(N, IP); 1690 InsertNode(N); 1691 return SDValue(N, 0); 1692 } 1693 1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1695 unsigned TargetFlags) { 1696 assert((TargetFlags == 0 || isTarget) && 1697 "Cannot set target flags on target-independent jump tables"); 1698 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1699 FoldingSetNodeID ID; 1700 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1701 ID.AddInteger(JTI); 1702 ID.AddInteger(TargetFlags); 1703 void *IP = nullptr; 1704 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1705 return SDValue(E, 0); 1706 1707 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1708 CSEMap.InsertNode(N, IP); 1709 InsertNode(N); 1710 return SDValue(N, 0); 1711 } 1712 1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1714 MaybeAlign Alignment, int Offset, 1715 bool isTarget, unsigned TargetFlags) { 1716 assert((TargetFlags == 0 || isTarget) && 1717 "Cannot set target flags on target-independent globals"); 1718 if (!Alignment) 1719 Alignment = shouldOptForSize() 1720 ? getDataLayout().getABITypeAlign(C->getType()) 1721 : getDataLayout().getPrefTypeAlign(C->getType()); 1722 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1723 FoldingSetNodeID ID; 1724 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1725 ID.AddInteger(Alignment->value()); 1726 ID.AddInteger(Offset); 1727 ID.AddPointer(C); 1728 ID.AddInteger(TargetFlags); 1729 void *IP = nullptr; 1730 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1731 return SDValue(E, 0); 1732 1733 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1734 TargetFlags); 1735 CSEMap.InsertNode(N, IP); 1736 InsertNode(N); 1737 SDValue V = SDValue(N, 0); 1738 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1739 return V; 1740 } 1741 1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1743 MaybeAlign Alignment, int Offset, 1744 bool isTarget, unsigned TargetFlags) { 1745 assert((TargetFlags == 0 || isTarget) && 1746 "Cannot set target flags on target-independent globals"); 1747 if (!Alignment) 1748 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1749 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1750 FoldingSetNodeID ID; 1751 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1752 ID.AddInteger(Alignment->value()); 1753 ID.AddInteger(Offset); 1754 C->addSelectionDAGCSEId(ID); 1755 ID.AddInteger(TargetFlags); 1756 void *IP = nullptr; 1757 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1758 return SDValue(E, 0); 1759 1760 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1761 TargetFlags); 1762 CSEMap.InsertNode(N, IP); 1763 InsertNode(N); 1764 return SDValue(N, 0); 1765 } 1766 1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1768 unsigned TargetFlags) { 1769 FoldingSetNodeID ID; 1770 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1771 ID.AddInteger(Index); 1772 ID.AddInteger(Offset); 1773 ID.AddInteger(TargetFlags); 1774 void *IP = nullptr; 1775 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1776 return SDValue(E, 0); 1777 1778 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1779 CSEMap.InsertNode(N, IP); 1780 InsertNode(N); 1781 return SDValue(N, 0); 1782 } 1783 1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1785 FoldingSetNodeID ID; 1786 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1787 ID.AddPointer(MBB); 1788 void *IP = nullptr; 1789 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1790 return SDValue(E, 0); 1791 1792 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1793 CSEMap.InsertNode(N, IP); 1794 InsertNode(N); 1795 return SDValue(N, 0); 1796 } 1797 1798 SDValue SelectionDAG::getValueType(EVT VT) { 1799 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1800 ValueTypeNodes.size()) 1801 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1802 1803 SDNode *&N = VT.isExtended() ? 1804 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1805 1806 if (N) return SDValue(N, 0); 1807 N = newSDNode<VTSDNode>(VT); 1808 InsertNode(N); 1809 return SDValue(N, 0); 1810 } 1811 1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1813 SDNode *&N = ExternalSymbols[Sym]; 1814 if (N) return SDValue(N, 0); 1815 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1816 InsertNode(N); 1817 return SDValue(N, 0); 1818 } 1819 1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1821 SDNode *&N = MCSymbols[Sym]; 1822 if (N) 1823 return SDValue(N, 0); 1824 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1825 InsertNode(N); 1826 return SDValue(N, 0); 1827 } 1828 1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1830 unsigned TargetFlags) { 1831 SDNode *&N = 1832 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1833 if (N) return SDValue(N, 0); 1834 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1835 InsertNode(N); 1836 return SDValue(N, 0); 1837 } 1838 1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1840 if ((unsigned)Cond >= CondCodeNodes.size()) 1841 CondCodeNodes.resize(Cond+1); 1842 1843 if (!CondCodeNodes[Cond]) { 1844 auto *N = newSDNode<CondCodeSDNode>(Cond); 1845 CondCodeNodes[Cond] = N; 1846 InsertNode(N); 1847 } 1848 1849 return SDValue(CondCodeNodes[Cond], 0); 1850 } 1851 1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1853 APInt One(ResVT.getScalarSizeInBits(), 1); 1854 return getStepVector(DL, ResVT, One); 1855 } 1856 1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1858 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1859 if (ResVT.isScalableVector()) 1860 return getNode( 1861 ISD::STEP_VECTOR, DL, ResVT, 1862 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1863 1864 SmallVector<SDValue, 16> OpsStepConstants; 1865 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1866 OpsStepConstants.push_back( 1867 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1868 return getBuildVector(ResVT, DL, OpsStepConstants); 1869 } 1870 1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1874 std::swap(N1, N2); 1875 ShuffleVectorSDNode::commuteMask(M); 1876 } 1877 1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1879 SDValue N2, ArrayRef<int> Mask) { 1880 assert(VT.getVectorNumElements() == Mask.size() && 1881 "Must have the same number of vector elements as mask elements!"); 1882 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1883 "Invalid VECTOR_SHUFFLE"); 1884 1885 // Canonicalize shuffle undef, undef -> undef 1886 if (N1.isUndef() && N2.isUndef()) 1887 return getUNDEF(VT); 1888 1889 // Validate that all indices in Mask are within the range of the elements 1890 // input to the shuffle. 1891 int NElts = Mask.size(); 1892 assert(llvm::all_of(Mask, 1893 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1894 "Index out of range"); 1895 1896 // Copy the mask so we can do any needed cleanup. 1897 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1898 1899 // Canonicalize shuffle v, v -> v, undef 1900 if (N1 == N2) { 1901 N2 = getUNDEF(VT); 1902 for (int i = 0; i != NElts; ++i) 1903 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1904 } 1905 1906 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1907 if (N1.isUndef()) 1908 commuteShuffle(N1, N2, MaskVec); 1909 1910 if (TLI->hasVectorBlend()) { 1911 // If shuffling a splat, try to blend the splat instead. We do this here so 1912 // that even when this arises during lowering we don't have to re-handle it. 1913 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1914 BitVector UndefElements; 1915 SDValue Splat = BV->getSplatValue(&UndefElements); 1916 if (!Splat) 1917 return; 1918 1919 for (int i = 0; i < NElts; ++i) { 1920 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1921 continue; 1922 1923 // If this input comes from undef, mark it as such. 1924 if (UndefElements[MaskVec[i] - Offset]) { 1925 MaskVec[i] = -1; 1926 continue; 1927 } 1928 1929 // If we can blend a non-undef lane, use that instead. 1930 if (!UndefElements[i]) 1931 MaskVec[i] = i + Offset; 1932 } 1933 }; 1934 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1935 BlendSplat(N1BV, 0); 1936 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1937 BlendSplat(N2BV, NElts); 1938 } 1939 1940 // Canonicalize all index into lhs, -> shuffle lhs, undef 1941 // Canonicalize all index into rhs, -> shuffle rhs, undef 1942 bool AllLHS = true, AllRHS = true; 1943 bool N2Undef = N2.isUndef(); 1944 for (int i = 0; i != NElts; ++i) { 1945 if (MaskVec[i] >= NElts) { 1946 if (N2Undef) 1947 MaskVec[i] = -1; 1948 else 1949 AllLHS = false; 1950 } else if (MaskVec[i] >= 0) { 1951 AllRHS = false; 1952 } 1953 } 1954 if (AllLHS && AllRHS) 1955 return getUNDEF(VT); 1956 if (AllLHS && !N2Undef) 1957 N2 = getUNDEF(VT); 1958 if (AllRHS) { 1959 N1 = getUNDEF(VT); 1960 commuteShuffle(N1, N2, MaskVec); 1961 } 1962 // Reset our undef status after accounting for the mask. 1963 N2Undef = N2.isUndef(); 1964 // Re-check whether both sides ended up undef. 1965 if (N1.isUndef() && N2Undef) 1966 return getUNDEF(VT); 1967 1968 // If Identity shuffle return that node. 1969 bool Identity = true, AllSame = true; 1970 for (int i = 0; i != NElts; ++i) { 1971 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1972 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1973 } 1974 if (Identity && NElts) 1975 return N1; 1976 1977 // Shuffling a constant splat doesn't change the result. 1978 if (N2Undef) { 1979 SDValue V = N1; 1980 1981 // Look through any bitcasts. We check that these don't change the number 1982 // (and size) of elements and just changes their types. 1983 while (V.getOpcode() == ISD::BITCAST) 1984 V = V->getOperand(0); 1985 1986 // A splat should always show up as a build vector node. 1987 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1988 BitVector UndefElements; 1989 SDValue Splat = BV->getSplatValue(&UndefElements); 1990 // If this is a splat of an undef, shuffling it is also undef. 1991 if (Splat && Splat.isUndef()) 1992 return getUNDEF(VT); 1993 1994 bool SameNumElts = 1995 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1996 1997 // We only have a splat which can skip shuffles if there is a splatted 1998 // value and no undef lanes rearranged by the shuffle. 1999 if (Splat && UndefElements.none()) { 2000 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 2001 // number of elements match or the value splatted is a zero constant. 2002 if (SameNumElts) 2003 return N1; 2004 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 2005 if (C->isZero()) 2006 return N1; 2007 } 2008 2009 // If the shuffle itself creates a splat, build the vector directly. 2010 if (AllSame && SameNumElts) { 2011 EVT BuildVT = BV->getValueType(0); 2012 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2013 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2014 2015 // We may have jumped through bitcasts, so the type of the 2016 // BUILD_VECTOR may not match the type of the shuffle. 2017 if (BuildVT != VT) 2018 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2019 return NewBV; 2020 } 2021 } 2022 } 2023 2024 FoldingSetNodeID ID; 2025 SDValue Ops[2] = { N1, N2 }; 2026 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2027 for (int i = 0; i != NElts; ++i) 2028 ID.AddInteger(MaskVec[i]); 2029 2030 void* IP = nullptr; 2031 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2032 return SDValue(E, 0); 2033 2034 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2035 // SDNode doesn't have access to it. This memory will be "leaked" when 2036 // the node is deallocated, but recovered when the NodeAllocator is released. 2037 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2038 llvm::copy(MaskVec, MaskAlloc); 2039 2040 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2041 dl.getDebugLoc(), MaskAlloc); 2042 createOperands(N, Ops); 2043 2044 CSEMap.InsertNode(N, IP); 2045 InsertNode(N); 2046 SDValue V = SDValue(N, 0); 2047 NewSDValueDbgMsg(V, "Creating new node: ", this); 2048 return V; 2049 } 2050 2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2052 EVT VT = SV.getValueType(0); 2053 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2054 ShuffleVectorSDNode::commuteMask(MaskVec); 2055 2056 SDValue Op0 = SV.getOperand(0); 2057 SDValue Op1 = SV.getOperand(1); 2058 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2059 } 2060 2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2062 FoldingSetNodeID ID; 2063 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2064 ID.AddInteger(RegNo); 2065 void *IP = nullptr; 2066 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2067 return SDValue(E, 0); 2068 2069 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2070 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2071 CSEMap.InsertNode(N, IP); 2072 InsertNode(N); 2073 return SDValue(N, 0); 2074 } 2075 2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2077 FoldingSetNodeID ID; 2078 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2079 ID.AddPointer(RegMask); 2080 void *IP = nullptr; 2081 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2082 return SDValue(E, 0); 2083 2084 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2085 CSEMap.InsertNode(N, IP); 2086 InsertNode(N); 2087 return SDValue(N, 0); 2088 } 2089 2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2091 MCSymbol *Label) { 2092 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2093 } 2094 2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2096 SDValue Root, MCSymbol *Label) { 2097 FoldingSetNodeID ID; 2098 SDValue Ops[] = { Root }; 2099 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2100 ID.AddPointer(Label); 2101 void *IP = nullptr; 2102 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2103 return SDValue(E, 0); 2104 2105 auto *N = 2106 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2107 createOperands(N, Ops); 2108 2109 CSEMap.InsertNode(N, IP); 2110 InsertNode(N); 2111 return SDValue(N, 0); 2112 } 2113 2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2115 int64_t Offset, bool isTarget, 2116 unsigned TargetFlags) { 2117 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2118 2119 FoldingSetNodeID ID; 2120 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2121 ID.AddPointer(BA); 2122 ID.AddInteger(Offset); 2123 ID.AddInteger(TargetFlags); 2124 void *IP = nullptr; 2125 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2126 return SDValue(E, 0); 2127 2128 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2129 CSEMap.InsertNode(N, IP); 2130 InsertNode(N); 2131 return SDValue(N, 0); 2132 } 2133 2134 SDValue SelectionDAG::getSrcValue(const Value *V) { 2135 FoldingSetNodeID ID; 2136 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2137 ID.AddPointer(V); 2138 2139 void *IP = nullptr; 2140 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2141 return SDValue(E, 0); 2142 2143 auto *N = newSDNode<SrcValueSDNode>(V); 2144 CSEMap.InsertNode(N, IP); 2145 InsertNode(N); 2146 return SDValue(N, 0); 2147 } 2148 2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2150 FoldingSetNodeID ID; 2151 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2152 ID.AddPointer(MD); 2153 2154 void *IP = nullptr; 2155 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2156 return SDValue(E, 0); 2157 2158 auto *N = newSDNode<MDNodeSDNode>(MD); 2159 CSEMap.InsertNode(N, IP); 2160 InsertNode(N); 2161 return SDValue(N, 0); 2162 } 2163 2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2165 if (VT == V.getValueType()) 2166 return V; 2167 2168 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2169 } 2170 2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2172 unsigned SrcAS, unsigned DestAS) { 2173 SDValue Ops[] = {Ptr}; 2174 FoldingSetNodeID ID; 2175 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2176 ID.AddInteger(SrcAS); 2177 ID.AddInteger(DestAS); 2178 2179 void *IP = nullptr; 2180 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2181 return SDValue(E, 0); 2182 2183 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2184 VT, SrcAS, DestAS); 2185 createOperands(N, Ops); 2186 2187 CSEMap.InsertNode(N, IP); 2188 InsertNode(N); 2189 return SDValue(N, 0); 2190 } 2191 2192 SDValue SelectionDAG::getFreeze(SDValue V) { 2193 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2194 } 2195 2196 /// getShiftAmountOperand - Return the specified value casted to 2197 /// the target's desired shift amount type. 2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2199 EVT OpTy = Op.getValueType(); 2200 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2201 if (OpTy == ShTy || OpTy.isVector()) return Op; 2202 2203 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2204 } 2205 2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2207 SDLoc dl(Node); 2208 const TargetLowering &TLI = getTargetLoweringInfo(); 2209 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2210 EVT VT = Node->getValueType(0); 2211 SDValue Tmp1 = Node->getOperand(0); 2212 SDValue Tmp2 = Node->getOperand(1); 2213 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2214 2215 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2216 Tmp2, MachinePointerInfo(V)); 2217 SDValue VAList = VAListLoad; 2218 2219 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2220 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2221 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2222 2223 VAList = 2224 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2225 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2226 } 2227 2228 // Increment the pointer, VAList, to the next vaarg 2229 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2230 getConstant(getDataLayout().getTypeAllocSize( 2231 VT.getTypeForEVT(*getContext())), 2232 dl, VAList.getValueType())); 2233 // Store the incremented VAList to the legalized pointer 2234 Tmp1 = 2235 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2236 // Load the actual argument out of the pointer VAList 2237 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2238 } 2239 2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2241 SDLoc dl(Node); 2242 const TargetLowering &TLI = getTargetLoweringInfo(); 2243 // This defaults to loading a pointer from the input and storing it to the 2244 // output, returning the chain. 2245 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2246 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2247 SDValue Tmp1 = 2248 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2249 Node->getOperand(2), MachinePointerInfo(VS)); 2250 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2251 MachinePointerInfo(VD)); 2252 } 2253 2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2255 const DataLayout &DL = getDataLayout(); 2256 Type *Ty = VT.getTypeForEVT(*getContext()); 2257 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2258 2259 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2260 return RedAlign; 2261 2262 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2263 const Align StackAlign = TFI->getStackAlign(); 2264 2265 // See if we can choose a smaller ABI alignment in cases where it's an 2266 // illegal vector type that will get broken down. 2267 if (RedAlign > StackAlign) { 2268 EVT IntermediateVT; 2269 MVT RegisterVT; 2270 unsigned NumIntermediates; 2271 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2272 NumIntermediates, RegisterVT); 2273 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2274 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2275 if (RedAlign2 < RedAlign) 2276 RedAlign = RedAlign2; 2277 } 2278 2279 return RedAlign; 2280 } 2281 2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2283 MachineFrameInfo &MFI = MF->getFrameInfo(); 2284 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2285 int StackID = 0; 2286 if (Bytes.isScalable()) 2287 StackID = TFI->getStackIDForScalableVectors(); 2288 // The stack id gives an indication of whether the object is scalable or 2289 // not, so it's safe to pass in the minimum size here. 2290 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2291 false, nullptr, StackID); 2292 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2293 } 2294 2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2296 Type *Ty = VT.getTypeForEVT(*getContext()); 2297 Align StackAlign = 2298 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2299 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2300 } 2301 2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2303 TypeSize VT1Size = VT1.getStoreSize(); 2304 TypeSize VT2Size = VT2.getStoreSize(); 2305 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2306 "Don't know how to choose the maximum size when creating a stack " 2307 "temporary"); 2308 TypeSize Bytes = 2309 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2310 2311 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2312 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2313 const DataLayout &DL = getDataLayout(); 2314 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2315 return CreateStackTemporary(Bytes, Align); 2316 } 2317 2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2319 ISD::CondCode Cond, const SDLoc &dl) { 2320 EVT OpVT = N1.getValueType(); 2321 2322 // These setcc operations always fold. 2323 switch (Cond) { 2324 default: break; 2325 case ISD::SETFALSE: 2326 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2327 case ISD::SETTRUE: 2328 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2329 2330 case ISD::SETOEQ: 2331 case ISD::SETOGT: 2332 case ISD::SETOGE: 2333 case ISD::SETOLT: 2334 case ISD::SETOLE: 2335 case ISD::SETONE: 2336 case ISD::SETO: 2337 case ISD::SETUO: 2338 case ISD::SETUEQ: 2339 case ISD::SETUNE: 2340 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2341 break; 2342 } 2343 2344 if (OpVT.isInteger()) { 2345 // For EQ and NE, we can always pick a value for the undef to make the 2346 // predicate pass or fail, so we can return undef. 2347 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2348 // icmp eq/ne X, undef -> undef. 2349 if ((N1.isUndef() || N2.isUndef()) && 2350 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2351 return getUNDEF(VT); 2352 2353 // If both operands are undef, we can return undef for int comparison. 2354 // icmp undef, undef -> undef. 2355 if (N1.isUndef() && N2.isUndef()) 2356 return getUNDEF(VT); 2357 2358 // icmp X, X -> true/false 2359 // icmp X, undef -> true/false because undef could be X. 2360 if (N1 == N2) 2361 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2362 } 2363 2364 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2365 const APInt &C2 = N2C->getAPIntValue(); 2366 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2367 const APInt &C1 = N1C->getAPIntValue(); 2368 2369 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2370 dl, VT, OpVT); 2371 } 2372 } 2373 2374 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2375 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2376 2377 if (N1CFP && N2CFP) { 2378 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2379 switch (Cond) { 2380 default: break; 2381 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2382 return getUNDEF(VT); 2383 LLVM_FALLTHROUGH; 2384 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2385 OpVT); 2386 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2387 return getUNDEF(VT); 2388 LLVM_FALLTHROUGH; 2389 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2390 R==APFloat::cmpLessThan, dl, VT, 2391 OpVT); 2392 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2393 return getUNDEF(VT); 2394 LLVM_FALLTHROUGH; 2395 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2396 OpVT); 2397 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2398 return getUNDEF(VT); 2399 LLVM_FALLTHROUGH; 2400 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2401 VT, OpVT); 2402 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2403 return getUNDEF(VT); 2404 LLVM_FALLTHROUGH; 2405 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2406 R==APFloat::cmpEqual, dl, VT, 2407 OpVT); 2408 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2409 return getUNDEF(VT); 2410 LLVM_FALLTHROUGH; 2411 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2412 R==APFloat::cmpEqual, dl, VT, OpVT); 2413 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2414 OpVT); 2415 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2416 OpVT); 2417 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2418 R==APFloat::cmpEqual, dl, VT, 2419 OpVT); 2420 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2421 OpVT); 2422 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2423 R==APFloat::cmpLessThan, dl, VT, 2424 OpVT); 2425 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2426 R==APFloat::cmpUnordered, dl, VT, 2427 OpVT); 2428 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2429 VT, OpVT); 2430 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2431 OpVT); 2432 } 2433 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2434 // Ensure that the constant occurs on the RHS. 2435 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2436 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2437 return SDValue(); 2438 return getSetCC(dl, VT, N2, N1, SwappedCond); 2439 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2440 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2441 // If an operand is known to be a nan (or undef that could be a nan), we can 2442 // fold it. 2443 // Choosing NaN for the undef will always make unordered comparison succeed 2444 // and ordered comparison fails. 2445 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2446 switch (ISD::getUnorderedFlavor(Cond)) { 2447 default: 2448 llvm_unreachable("Unknown flavor!"); 2449 case 0: // Known false. 2450 return getBoolConstant(false, dl, VT, OpVT); 2451 case 1: // Known true. 2452 return getBoolConstant(true, dl, VT, OpVT); 2453 case 2: // Undefined. 2454 return getUNDEF(VT); 2455 } 2456 } 2457 2458 // Could not fold it. 2459 return SDValue(); 2460 } 2461 2462 /// See if the specified operand can be simplified with the knowledge that only 2463 /// the bits specified by DemandedBits are used. 2464 /// TODO: really we should be making this into the DAG equivalent of 2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2467 EVT VT = V.getValueType(); 2468 2469 if (VT.isScalableVector()) 2470 return SDValue(); 2471 2472 switch (V.getOpcode()) { 2473 default: 2474 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, *this); 2475 case ISD::Constant: { 2476 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2477 APInt NewVal = CVal & DemandedBits; 2478 if (NewVal != CVal) 2479 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2480 break; 2481 } 2482 case ISD::SRL: 2483 // Only look at single-use SRLs. 2484 if (!V.getNode()->hasOneUse()) 2485 break; 2486 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2487 // See if we can recursively simplify the LHS. 2488 unsigned Amt = RHSC->getZExtValue(); 2489 2490 // Watch out for shift count overflow though. 2491 if (Amt >= DemandedBits.getBitWidth()) 2492 break; 2493 APInt SrcDemandedBits = DemandedBits << Amt; 2494 if (SDValue SimplifyLHS = TLI->SimplifyMultipleUseDemandedBits( 2495 V.getOperand(0), SrcDemandedBits, *this)) 2496 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2497 V.getOperand(1)); 2498 } 2499 break; 2500 } 2501 return SDValue(); 2502 } 2503 2504 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2505 /// use this predicate to simplify operations downstream. 2506 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2507 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2508 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2509 } 2510 2511 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2512 /// this predicate to simplify operations downstream. Mask is known to be zero 2513 /// for bits that V cannot have. 2514 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2515 unsigned Depth) const { 2516 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2517 } 2518 2519 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2520 /// DemandedElts. We use this predicate to simplify operations downstream. 2521 /// Mask is known to be zero for bits that V cannot have. 2522 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2523 const APInt &DemandedElts, 2524 unsigned Depth) const { 2525 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2526 } 2527 2528 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in 2529 /// DemandedElts. We use this predicate to simplify operations downstream. 2530 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts, 2531 unsigned Depth /* = 0 */) const { 2532 APInt Mask = APInt::getAllOnes(V.getScalarValueSizeInBits()); 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.zext(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.zext(NumSrcElts); 2684 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2685 UndefElts = UndefSrcElts.trunc(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 2716 // Here we can't do "MatchAnyBits" operation merge for undef bits. 2717 // Because some operation only use part value of the source. 2718 // Take llvm.fshl.* for example: 2719 // t1: v4i32 = Constant:i32<12>, undef:i32, Constant:i32<12>, undef:i32 2720 // t2: v2i64 = bitcast t1 2721 // t5: v2i64 = fshl t3, t4, t2 2722 // We can not convert t2 to {i64 undef, i64 undef} 2723 UndefElts |= APIntOps::ScaleBitMask(SubUndefElts, NumElts, 2724 /*MatchAllBits=*/true); 2725 } 2726 return true; 2727 } 2728 break; 2729 } 2730 } 2731 2732 return false; 2733 } 2734 2735 /// Helper wrapper to main isSplatValue function. 2736 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2737 EVT VT = V.getValueType(); 2738 assert(VT.isVector() && "Vector type expected"); 2739 2740 APInt UndefElts; 2741 APInt DemandedElts; 2742 2743 // For now we don't support this with scalable vectors. 2744 if (!VT.isScalableVector()) 2745 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2746 return isSplatValue(V, DemandedElts, UndefElts) && 2747 (AllowUndefs || !UndefElts); 2748 } 2749 2750 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2751 V = peekThroughExtractSubvectors(V); 2752 2753 EVT VT = V.getValueType(); 2754 unsigned Opcode = V.getOpcode(); 2755 switch (Opcode) { 2756 default: { 2757 APInt UndefElts; 2758 APInt DemandedElts; 2759 2760 if (!VT.isScalableVector()) 2761 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2762 2763 if (isSplatValue(V, DemandedElts, UndefElts)) { 2764 if (VT.isScalableVector()) { 2765 // DemandedElts and UndefElts are ignored for scalable vectors, since 2766 // the only supported cases are SPLAT_VECTOR nodes. 2767 SplatIdx = 0; 2768 } else { 2769 // Handle case where all demanded elements are UNDEF. 2770 if (DemandedElts.isSubsetOf(UndefElts)) { 2771 SplatIdx = 0; 2772 return getUNDEF(VT); 2773 } 2774 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2775 } 2776 return V; 2777 } 2778 break; 2779 } 2780 case ISD::SPLAT_VECTOR: 2781 SplatIdx = 0; 2782 return V; 2783 case ISD::VECTOR_SHUFFLE: { 2784 if (VT.isScalableVector()) 2785 return SDValue(); 2786 2787 // Check if this is a shuffle node doing a splat. 2788 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2789 // getTargetVShiftNode currently struggles without the splat source. 2790 auto *SVN = cast<ShuffleVectorSDNode>(V); 2791 if (!SVN->isSplat()) 2792 break; 2793 int Idx = SVN->getSplatIndex(); 2794 int NumElts = V.getValueType().getVectorNumElements(); 2795 SplatIdx = Idx % NumElts; 2796 return V.getOperand(Idx / NumElts); 2797 } 2798 } 2799 2800 return SDValue(); 2801 } 2802 2803 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2804 int SplatIdx; 2805 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2806 EVT SVT = SrcVector.getValueType().getScalarType(); 2807 EVT LegalSVT = SVT; 2808 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2809 if (!SVT.isInteger()) 2810 return SDValue(); 2811 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2812 if (LegalSVT.bitsLT(SVT)) 2813 return SDValue(); 2814 } 2815 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2816 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2817 } 2818 return SDValue(); 2819 } 2820 2821 const APInt * 2822 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2823 const APInt &DemandedElts) const { 2824 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2825 V.getOpcode() == ISD::SRA) && 2826 "Unknown shift node"); 2827 unsigned BitWidth = V.getScalarValueSizeInBits(); 2828 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2829 // Shifting more than the bitwidth is not valid. 2830 const APInt &ShAmt = SA->getAPIntValue(); 2831 if (ShAmt.ult(BitWidth)) 2832 return &ShAmt; 2833 } 2834 return nullptr; 2835 } 2836 2837 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2838 SDValue V, const APInt &DemandedElts) const { 2839 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2840 V.getOpcode() == ISD::SRA) && 2841 "Unknown shift node"); 2842 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2843 return ValidAmt; 2844 unsigned BitWidth = V.getScalarValueSizeInBits(); 2845 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2846 if (!BV) 2847 return nullptr; 2848 const APInt *MinShAmt = nullptr; 2849 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2850 if (!DemandedElts[i]) 2851 continue; 2852 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2853 if (!SA) 2854 return nullptr; 2855 // Shifting more than the bitwidth is not valid. 2856 const APInt &ShAmt = SA->getAPIntValue(); 2857 if (ShAmt.uge(BitWidth)) 2858 return nullptr; 2859 if (MinShAmt && MinShAmt->ule(ShAmt)) 2860 continue; 2861 MinShAmt = &ShAmt; 2862 } 2863 return MinShAmt; 2864 } 2865 2866 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2867 SDValue V, const APInt &DemandedElts) const { 2868 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2869 V.getOpcode() == ISD::SRA) && 2870 "Unknown shift node"); 2871 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2872 return ValidAmt; 2873 unsigned BitWidth = V.getScalarValueSizeInBits(); 2874 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2875 if (!BV) 2876 return nullptr; 2877 const APInt *MaxShAmt = nullptr; 2878 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2879 if (!DemandedElts[i]) 2880 continue; 2881 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2882 if (!SA) 2883 return nullptr; 2884 // Shifting more than the bitwidth is not valid. 2885 const APInt &ShAmt = SA->getAPIntValue(); 2886 if (ShAmt.uge(BitWidth)) 2887 return nullptr; 2888 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2889 continue; 2890 MaxShAmt = &ShAmt; 2891 } 2892 return MaxShAmt; 2893 } 2894 2895 /// Determine which bits of Op are known to be either zero or one and return 2896 /// them in Known. For vectors, the known bits are those that are shared by 2897 /// every vector element. 2898 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2899 EVT VT = Op.getValueType(); 2900 2901 // TOOD: Until we have a plan for how to represent demanded elements for 2902 // scalable vectors, we can just bail out for now. 2903 if (Op.getValueType().isScalableVector()) { 2904 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2905 return KnownBits(BitWidth); 2906 } 2907 2908 APInt DemandedElts = VT.isVector() 2909 ? APInt::getAllOnes(VT.getVectorNumElements()) 2910 : APInt(1, 1); 2911 return computeKnownBits(Op, DemandedElts, Depth); 2912 } 2913 2914 /// Determine which bits of Op are known to be either zero or one and return 2915 /// them in Known. The DemandedElts argument allows us to only collect the known 2916 /// bits that are shared by the requested vector elements. 2917 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2918 unsigned Depth) const { 2919 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2920 2921 KnownBits Known(BitWidth); // Don't know anything. 2922 2923 // TOOD: Until we have a plan for how to represent demanded elements for 2924 // scalable vectors, we can just bail out for now. 2925 if (Op.getValueType().isScalableVector()) 2926 return Known; 2927 2928 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2929 // We know all of the bits for a constant! 2930 return KnownBits::makeConstant(C->getAPIntValue()); 2931 } 2932 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2933 // We know all of the bits for a constant fp! 2934 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2935 } 2936 2937 if (Depth >= MaxRecursionDepth) 2938 return Known; // Limit search depth. 2939 2940 KnownBits Known2; 2941 unsigned NumElts = DemandedElts.getBitWidth(); 2942 assert((!Op.getValueType().isVector() || 2943 NumElts == Op.getValueType().getVectorNumElements()) && 2944 "Unexpected vector size"); 2945 2946 if (!DemandedElts) 2947 return Known; // No demanded elts, better to assume we don't know anything. 2948 2949 unsigned Opcode = Op.getOpcode(); 2950 switch (Opcode) { 2951 case ISD::BUILD_VECTOR: 2952 // Collect the known bits that are shared by every demanded vector element. 2953 Known.Zero.setAllBits(); Known.One.setAllBits(); 2954 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2955 if (!DemandedElts[i]) 2956 continue; 2957 2958 SDValue SrcOp = Op.getOperand(i); 2959 Known2 = computeKnownBits(SrcOp, Depth + 1); 2960 2961 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2962 if (SrcOp.getValueSizeInBits() != BitWidth) { 2963 assert(SrcOp.getValueSizeInBits() > BitWidth && 2964 "Expected BUILD_VECTOR implicit truncation"); 2965 Known2 = Known2.trunc(BitWidth); 2966 } 2967 2968 // Known bits are the values that are shared by every demanded element. 2969 Known = KnownBits::commonBits(Known, Known2); 2970 2971 // If we don't know any bits, early out. 2972 if (Known.isUnknown()) 2973 break; 2974 } 2975 break; 2976 case ISD::VECTOR_SHUFFLE: { 2977 // Collect the known bits that are shared by every vector element referenced 2978 // by the shuffle. 2979 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2980 Known.Zero.setAllBits(); Known.One.setAllBits(); 2981 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2982 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2983 for (unsigned i = 0; i != NumElts; ++i) { 2984 if (!DemandedElts[i]) 2985 continue; 2986 2987 int M = SVN->getMaskElt(i); 2988 if (M < 0) { 2989 // For UNDEF elements, we don't know anything about the common state of 2990 // the shuffle result. 2991 Known.resetAll(); 2992 DemandedLHS.clearAllBits(); 2993 DemandedRHS.clearAllBits(); 2994 break; 2995 } 2996 2997 if ((unsigned)M < NumElts) 2998 DemandedLHS.setBit((unsigned)M % NumElts); 2999 else 3000 DemandedRHS.setBit((unsigned)M % NumElts); 3001 } 3002 // Known bits are the values that are shared by every demanded element. 3003 if (!!DemandedLHS) { 3004 SDValue LHS = Op.getOperand(0); 3005 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 3006 Known = KnownBits::commonBits(Known, Known2); 3007 } 3008 // If we don't know any bits, early out. 3009 if (Known.isUnknown()) 3010 break; 3011 if (!!DemandedRHS) { 3012 SDValue RHS = Op.getOperand(1); 3013 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3014 Known = KnownBits::commonBits(Known, Known2); 3015 } 3016 break; 3017 } 3018 case ISD::CONCAT_VECTORS: { 3019 // Split DemandedElts and test each of the demanded subvectors. 3020 Known.Zero.setAllBits(); Known.One.setAllBits(); 3021 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3022 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3023 unsigned NumSubVectors = Op.getNumOperands(); 3024 for (unsigned i = 0; i != NumSubVectors; ++i) { 3025 APInt DemandedSub = 3026 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3027 if (!!DemandedSub) { 3028 SDValue Sub = Op.getOperand(i); 3029 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3030 Known = KnownBits::commonBits(Known, Known2); 3031 } 3032 // If we don't know any bits, early out. 3033 if (Known.isUnknown()) 3034 break; 3035 } 3036 break; 3037 } 3038 case ISD::INSERT_SUBVECTOR: { 3039 // Demand any elements from the subvector and the remainder from the src its 3040 // inserted into. 3041 SDValue Src = Op.getOperand(0); 3042 SDValue Sub = Op.getOperand(1); 3043 uint64_t Idx = Op.getConstantOperandVal(2); 3044 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3045 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3046 APInt DemandedSrcElts = DemandedElts; 3047 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3048 3049 Known.One.setAllBits(); 3050 Known.Zero.setAllBits(); 3051 if (!!DemandedSubElts) { 3052 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3053 if (Known.isUnknown()) 3054 break; // early-out. 3055 } 3056 if (!!DemandedSrcElts) { 3057 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3058 Known = KnownBits::commonBits(Known, Known2); 3059 } 3060 break; 3061 } 3062 case ISD::EXTRACT_SUBVECTOR: { 3063 // Offset the demanded elts by the subvector index. 3064 SDValue Src = Op.getOperand(0); 3065 // Bail until we can represent demanded elements for scalable vectors. 3066 if (Src.getValueType().isScalableVector()) 3067 break; 3068 uint64_t Idx = Op.getConstantOperandVal(1); 3069 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3070 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3071 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3072 break; 3073 } 3074 case ISD::SCALAR_TO_VECTOR: { 3075 // We know about scalar_to_vector as much as we know about it source, 3076 // which becomes the first element of otherwise unknown vector. 3077 if (DemandedElts != 1) 3078 break; 3079 3080 SDValue N0 = Op.getOperand(0); 3081 Known = computeKnownBits(N0, Depth + 1); 3082 if (N0.getValueSizeInBits() != BitWidth) 3083 Known = Known.trunc(BitWidth); 3084 3085 break; 3086 } 3087 case ISD::BITCAST: { 3088 SDValue N0 = Op.getOperand(0); 3089 EVT SubVT = N0.getValueType(); 3090 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3091 3092 // Ignore bitcasts from unsupported types. 3093 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3094 break; 3095 3096 // Fast handling of 'identity' bitcasts. 3097 if (BitWidth == SubBitWidth) { 3098 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3099 break; 3100 } 3101 3102 bool IsLE = getDataLayout().isLittleEndian(); 3103 3104 // Bitcast 'small element' vector to 'large element' scalar/vector. 3105 if ((BitWidth % SubBitWidth) == 0) { 3106 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3107 3108 // Collect known bits for the (larger) output by collecting the known 3109 // bits from each set of sub elements and shift these into place. 3110 // We need to separately call computeKnownBits for each set of 3111 // sub elements as the knownbits for each is likely to be different. 3112 unsigned SubScale = BitWidth / SubBitWidth; 3113 APInt SubDemandedElts(NumElts * SubScale, 0); 3114 for (unsigned i = 0; i != NumElts; ++i) 3115 if (DemandedElts[i]) 3116 SubDemandedElts.setBit(i * SubScale); 3117 3118 for (unsigned i = 0; i != SubScale; ++i) { 3119 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3120 Depth + 1); 3121 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3122 Known.insertBits(Known2, SubBitWidth * Shifts); 3123 } 3124 } 3125 3126 // Bitcast 'large element' scalar/vector to 'small element' vector. 3127 if ((SubBitWidth % BitWidth) == 0) { 3128 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3129 3130 // Collect known bits for the (smaller) output by collecting the known 3131 // bits from the overlapping larger input elements and extracting the 3132 // sub sections we actually care about. 3133 unsigned SubScale = SubBitWidth / BitWidth; 3134 APInt SubDemandedElts = 3135 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3136 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3137 3138 Known.Zero.setAllBits(); Known.One.setAllBits(); 3139 for (unsigned i = 0; i != NumElts; ++i) 3140 if (DemandedElts[i]) { 3141 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3142 unsigned Offset = (Shifts % SubScale) * BitWidth; 3143 Known = KnownBits::commonBits(Known, 3144 Known2.extractBits(BitWidth, Offset)); 3145 // If we don't know any bits, early out. 3146 if (Known.isUnknown()) 3147 break; 3148 } 3149 } 3150 break; 3151 } 3152 case ISD::AND: 3153 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3154 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3155 3156 Known &= Known2; 3157 break; 3158 case ISD::OR: 3159 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3160 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3161 3162 Known |= Known2; 3163 break; 3164 case ISD::XOR: 3165 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3166 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3167 3168 Known ^= Known2; 3169 break; 3170 case ISD::MUL: { 3171 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3172 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3173 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3174 // TODO: SelfMultiply can be poison, but not undef. 3175 if (SelfMultiply) 3176 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3177 Op.getOperand(0), DemandedElts, false, Depth + 1); 3178 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3179 3180 // If the multiplication is known not to overflow, the product of a number 3181 // with itself is non-negative. Only do this if we didn't already computed 3182 // the opposite value for the sign bit. 3183 if (Op->getFlags().hasNoSignedWrap() && 3184 Op.getOperand(0) == Op.getOperand(1) && 3185 !Known.isNegative()) 3186 Known.makeNonNegative(); 3187 break; 3188 } 3189 case ISD::MULHU: { 3190 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3191 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3192 Known = KnownBits::mulhu(Known, Known2); 3193 break; 3194 } 3195 case ISD::MULHS: { 3196 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3197 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3198 Known = KnownBits::mulhs(Known, Known2); 3199 break; 3200 } 3201 case ISD::UMUL_LOHI: { 3202 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3203 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3204 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3205 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3206 if (Op.getResNo() == 0) 3207 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3208 else 3209 Known = KnownBits::mulhu(Known, Known2); 3210 break; 3211 } 3212 case ISD::SMUL_LOHI: { 3213 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3214 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3215 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3216 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3217 if (Op.getResNo() == 0) 3218 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3219 else 3220 Known = KnownBits::mulhs(Known, Known2); 3221 break; 3222 } 3223 case ISD::UDIV: { 3224 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3225 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3226 Known = KnownBits::udiv(Known, Known2); 3227 break; 3228 } 3229 case ISD::AVGCEILU: { 3230 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3231 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3232 Known = Known.zext(BitWidth + 1); 3233 Known2 = Known2.zext(BitWidth + 1); 3234 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3235 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3236 Known = Known.extractBits(BitWidth, 1); 3237 break; 3238 } 3239 case ISD::SELECT: 3240 case ISD::VSELECT: 3241 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3242 // If we don't know any bits, early out. 3243 if (Known.isUnknown()) 3244 break; 3245 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3246 3247 // Only known if known in both the LHS and RHS. 3248 Known = KnownBits::commonBits(Known, Known2); 3249 break; 3250 case ISD::SELECT_CC: 3251 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3252 // If we don't know any bits, early out. 3253 if (Known.isUnknown()) 3254 break; 3255 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3256 3257 // Only known if known in both the LHS and RHS. 3258 Known = KnownBits::commonBits(Known, Known2); 3259 break; 3260 case ISD::SMULO: 3261 case ISD::UMULO: 3262 if (Op.getResNo() != 1) 3263 break; 3264 // The boolean result conforms to getBooleanContents. 3265 // If we know the result of a setcc has the top bits zero, use this info. 3266 // We know that we have an integer-based boolean since these operations 3267 // are only available for integer. 3268 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3269 TargetLowering::ZeroOrOneBooleanContent && 3270 BitWidth > 1) 3271 Known.Zero.setBitsFrom(1); 3272 break; 3273 case ISD::SETCC: 3274 case ISD::STRICT_FSETCC: 3275 case ISD::STRICT_FSETCCS: { 3276 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3277 // If we know the result of a setcc has the top bits zero, use this info. 3278 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3279 TargetLowering::ZeroOrOneBooleanContent && 3280 BitWidth > 1) 3281 Known.Zero.setBitsFrom(1); 3282 break; 3283 } 3284 case ISD::SHL: 3285 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3286 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3287 Known = KnownBits::shl(Known, Known2); 3288 3289 // Minimum shift low bits are known zero. 3290 if (const APInt *ShMinAmt = 3291 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3292 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3293 break; 3294 case ISD::SRL: 3295 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3296 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3297 Known = KnownBits::lshr(Known, Known2); 3298 3299 // Minimum shift high bits are known zero. 3300 if (const APInt *ShMinAmt = 3301 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3302 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3303 break; 3304 case ISD::SRA: 3305 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3306 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3307 Known = KnownBits::ashr(Known, Known2); 3308 // TODO: Add minimum shift high known sign bits. 3309 break; 3310 case ISD::FSHL: 3311 case ISD::FSHR: 3312 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3313 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3314 3315 // For fshl, 0-shift returns the 1st arg. 3316 // For fshr, 0-shift returns the 2nd arg. 3317 if (Amt == 0) { 3318 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3319 DemandedElts, Depth + 1); 3320 break; 3321 } 3322 3323 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3324 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3325 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3326 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3327 if (Opcode == ISD::FSHL) { 3328 Known.One <<= Amt; 3329 Known.Zero <<= Amt; 3330 Known2.One.lshrInPlace(BitWidth - Amt); 3331 Known2.Zero.lshrInPlace(BitWidth - Amt); 3332 } else { 3333 Known.One <<= BitWidth - Amt; 3334 Known.Zero <<= BitWidth - Amt; 3335 Known2.One.lshrInPlace(Amt); 3336 Known2.Zero.lshrInPlace(Amt); 3337 } 3338 Known.One |= Known2.One; 3339 Known.Zero |= Known2.Zero; 3340 } 3341 break; 3342 case ISD::SIGN_EXTEND_INREG: { 3343 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3344 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3345 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3346 break; 3347 } 3348 case ISD::CTTZ: 3349 case ISD::CTTZ_ZERO_UNDEF: { 3350 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3351 // If we have a known 1, its position is our upper bound. 3352 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3353 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3354 Known.Zero.setBitsFrom(LowBits); 3355 break; 3356 } 3357 case ISD::CTLZ: 3358 case ISD::CTLZ_ZERO_UNDEF: { 3359 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3360 // If we have a known 1, its position is our upper bound. 3361 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3362 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3363 Known.Zero.setBitsFrom(LowBits); 3364 break; 3365 } 3366 case ISD::CTPOP: { 3367 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3368 // If we know some of the bits are zero, they can't be one. 3369 unsigned PossibleOnes = Known2.countMaxPopulation(); 3370 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3371 break; 3372 } 3373 case ISD::PARITY: { 3374 // Parity returns 0 everywhere but the LSB. 3375 Known.Zero.setBitsFrom(1); 3376 break; 3377 } 3378 case ISD::LOAD: { 3379 LoadSDNode *LD = cast<LoadSDNode>(Op); 3380 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3381 if (ISD::isNON_EXTLoad(LD) && Cst) { 3382 // Determine any common known bits from the loaded constant pool value. 3383 Type *CstTy = Cst->getType(); 3384 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3385 // If its a vector splat, then we can (quickly) reuse the scalar path. 3386 // NOTE: We assume all elements match and none are UNDEF. 3387 if (CstTy->isVectorTy()) { 3388 if (const Constant *Splat = Cst->getSplatValue()) { 3389 Cst = Splat; 3390 CstTy = Cst->getType(); 3391 } 3392 } 3393 // TODO - do we need to handle different bitwidths? 3394 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3395 // Iterate across all vector elements finding common known bits. 3396 Known.One.setAllBits(); 3397 Known.Zero.setAllBits(); 3398 for (unsigned i = 0; i != NumElts; ++i) { 3399 if (!DemandedElts[i]) 3400 continue; 3401 if (Constant *Elt = Cst->getAggregateElement(i)) { 3402 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3403 const APInt &Value = CInt->getValue(); 3404 Known.One &= Value; 3405 Known.Zero &= ~Value; 3406 continue; 3407 } 3408 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3409 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3410 Known.One &= Value; 3411 Known.Zero &= ~Value; 3412 continue; 3413 } 3414 } 3415 Known.One.clearAllBits(); 3416 Known.Zero.clearAllBits(); 3417 break; 3418 } 3419 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3420 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3421 Known = KnownBits::makeConstant(CInt->getValue()); 3422 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3423 Known = 3424 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3425 } 3426 } 3427 } 3428 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3429 // If this is a ZEXTLoad and we are looking at the loaded value. 3430 EVT VT = LD->getMemoryVT(); 3431 unsigned MemBits = VT.getScalarSizeInBits(); 3432 Known.Zero.setBitsFrom(MemBits); 3433 } else if (const MDNode *Ranges = LD->getRanges()) { 3434 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3435 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3436 } 3437 break; 3438 } 3439 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3440 EVT InVT = Op.getOperand(0).getValueType(); 3441 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3442 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3443 Known = Known.zext(BitWidth); 3444 break; 3445 } 3446 case ISD::ZERO_EXTEND: { 3447 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3448 Known = Known.zext(BitWidth); 3449 break; 3450 } 3451 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3452 EVT InVT = Op.getOperand(0).getValueType(); 3453 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3454 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3455 // If the sign bit is known to be zero or one, then sext will extend 3456 // it to the top bits, else it will just zext. 3457 Known = Known.sext(BitWidth); 3458 break; 3459 } 3460 case ISD::SIGN_EXTEND: { 3461 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3462 // If the sign bit is known to be zero or one, then sext will extend 3463 // it to the top bits, else it will just zext. 3464 Known = Known.sext(BitWidth); 3465 break; 3466 } 3467 case ISD::ANY_EXTEND_VECTOR_INREG: { 3468 EVT InVT = Op.getOperand(0).getValueType(); 3469 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3470 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3471 Known = Known.anyext(BitWidth); 3472 break; 3473 } 3474 case ISD::ANY_EXTEND: { 3475 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3476 Known = Known.anyext(BitWidth); 3477 break; 3478 } 3479 case ISD::TRUNCATE: { 3480 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3481 Known = Known.trunc(BitWidth); 3482 break; 3483 } 3484 case ISD::AssertZext: { 3485 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3486 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3487 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3488 Known.Zero |= (~InMask); 3489 Known.One &= (~Known.Zero); 3490 break; 3491 } 3492 case ISD::AssertAlign: { 3493 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3494 assert(LogOfAlign != 0); 3495 3496 // TODO: Should use maximum with source 3497 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3498 // well as clearing one bits. 3499 Known.Zero.setLowBits(LogOfAlign); 3500 Known.One.clearLowBits(LogOfAlign); 3501 break; 3502 } 3503 case ISD::FGETSIGN: 3504 // All bits are zero except the low bit. 3505 Known.Zero.setBitsFrom(1); 3506 break; 3507 case ISD::USUBO: 3508 case ISD::SSUBO: 3509 if (Op.getResNo() == 1) { 3510 // If we know the result of a setcc has the top bits zero, use this info. 3511 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3512 TargetLowering::ZeroOrOneBooleanContent && 3513 BitWidth > 1) 3514 Known.Zero.setBitsFrom(1); 3515 break; 3516 } 3517 LLVM_FALLTHROUGH; 3518 case ISD::SUB: 3519 case ISD::SUBC: { 3520 assert(Op.getResNo() == 0 && 3521 "We only compute knownbits for the difference here."); 3522 3523 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3524 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3525 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3526 Known, Known2); 3527 break; 3528 } 3529 case ISD::UADDO: 3530 case ISD::SADDO: 3531 case ISD::ADDCARRY: 3532 if (Op.getResNo() == 1) { 3533 // If we know the result of a setcc has the top bits zero, use this info. 3534 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3535 TargetLowering::ZeroOrOneBooleanContent && 3536 BitWidth > 1) 3537 Known.Zero.setBitsFrom(1); 3538 break; 3539 } 3540 LLVM_FALLTHROUGH; 3541 case ISD::ADD: 3542 case ISD::ADDC: 3543 case ISD::ADDE: { 3544 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3545 3546 // With ADDE and ADDCARRY, a carry bit may be added in. 3547 KnownBits Carry(1); 3548 if (Opcode == ISD::ADDE) 3549 // Can't track carry from glue, set carry to unknown. 3550 Carry.resetAll(); 3551 else if (Opcode == ISD::ADDCARRY) 3552 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3553 // the trouble (how often will we find a known carry bit). And I haven't 3554 // tested this very much yet, but something like this might work: 3555 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3556 // Carry = Carry.zextOrTrunc(1, false); 3557 Carry.resetAll(); 3558 else 3559 Carry.setAllZero(); 3560 3561 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3562 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3563 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3564 break; 3565 } 3566 case ISD::SREM: { 3567 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3568 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3569 Known = KnownBits::srem(Known, Known2); 3570 break; 3571 } 3572 case ISD::UREM: { 3573 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3574 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3575 Known = KnownBits::urem(Known, Known2); 3576 break; 3577 } 3578 case ISD::EXTRACT_ELEMENT: { 3579 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3580 const unsigned Index = Op.getConstantOperandVal(1); 3581 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3582 3583 // Remove low part of known bits mask 3584 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3585 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3586 3587 // Remove high part of known bit mask 3588 Known = Known.trunc(EltBitWidth); 3589 break; 3590 } 3591 case ISD::EXTRACT_VECTOR_ELT: { 3592 SDValue InVec = Op.getOperand(0); 3593 SDValue EltNo = Op.getOperand(1); 3594 EVT VecVT = InVec.getValueType(); 3595 // computeKnownBits not yet implemented for scalable vectors. 3596 if (VecVT.isScalableVector()) 3597 break; 3598 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3599 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3600 3601 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3602 // anything about the extended bits. 3603 if (BitWidth > EltBitWidth) 3604 Known = Known.trunc(EltBitWidth); 3605 3606 // If we know the element index, just demand that vector element, else for 3607 // an unknown element index, ignore DemandedElts and demand them all. 3608 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3609 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3610 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3611 DemandedSrcElts = 3612 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3613 3614 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3615 if (BitWidth > EltBitWidth) 3616 Known = Known.anyext(BitWidth); 3617 break; 3618 } 3619 case ISD::INSERT_VECTOR_ELT: { 3620 // If we know the element index, split the demand between the 3621 // source vector and the inserted element, otherwise assume we need 3622 // the original demanded vector elements and the value. 3623 SDValue InVec = Op.getOperand(0); 3624 SDValue InVal = Op.getOperand(1); 3625 SDValue EltNo = Op.getOperand(2); 3626 bool DemandedVal = true; 3627 APInt DemandedVecElts = DemandedElts; 3628 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3629 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3630 unsigned EltIdx = CEltNo->getZExtValue(); 3631 DemandedVal = !!DemandedElts[EltIdx]; 3632 DemandedVecElts.clearBit(EltIdx); 3633 } 3634 Known.One.setAllBits(); 3635 Known.Zero.setAllBits(); 3636 if (DemandedVal) { 3637 Known2 = computeKnownBits(InVal, Depth + 1); 3638 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3639 } 3640 if (!!DemandedVecElts) { 3641 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3642 Known = KnownBits::commonBits(Known, Known2); 3643 } 3644 break; 3645 } 3646 case ISD::BITREVERSE: { 3647 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3648 Known = Known2.reverseBits(); 3649 break; 3650 } 3651 case ISD::BSWAP: { 3652 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3653 Known = Known2.byteSwap(); 3654 break; 3655 } 3656 case ISD::ABS: { 3657 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3658 Known = Known2.abs(); 3659 break; 3660 } 3661 case ISD::USUBSAT: { 3662 // The result of usubsat will never be larger than the LHS. 3663 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3664 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3665 break; 3666 } 3667 case ISD::UMIN: { 3668 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3669 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3670 Known = KnownBits::umin(Known, Known2); 3671 break; 3672 } 3673 case ISD::UMAX: { 3674 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3675 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3676 Known = KnownBits::umax(Known, Known2); 3677 break; 3678 } 3679 case ISD::SMIN: 3680 case ISD::SMAX: { 3681 // If we have a clamp pattern, we know that the number of sign bits will be 3682 // the minimum of the clamp min/max range. 3683 bool IsMax = (Opcode == ISD::SMAX); 3684 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3685 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3686 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3687 CstHigh = 3688 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3689 if (CstLow && CstHigh) { 3690 if (!IsMax) 3691 std::swap(CstLow, CstHigh); 3692 3693 const APInt &ValueLow = CstLow->getAPIntValue(); 3694 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3695 if (ValueLow.sle(ValueHigh)) { 3696 unsigned LowSignBits = ValueLow.getNumSignBits(); 3697 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3698 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3699 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3700 Known.One.setHighBits(MinSignBits); 3701 break; 3702 } 3703 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3704 Known.Zero.setHighBits(MinSignBits); 3705 break; 3706 } 3707 } 3708 } 3709 3710 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3711 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3712 if (IsMax) 3713 Known = KnownBits::smax(Known, Known2); 3714 else 3715 Known = KnownBits::smin(Known, Known2); 3716 3717 // For SMAX, if CstLow is non-negative we know the result will be 3718 // non-negative and thus all sign bits are 0. 3719 // TODO: There's an equivalent of this for smin with negative constant for 3720 // known ones. 3721 if (IsMax && CstLow) { 3722 const APInt &ValueLow = CstLow->getAPIntValue(); 3723 if (ValueLow.isNonNegative()) { 3724 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3725 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits())); 3726 } 3727 } 3728 3729 break; 3730 } 3731 case ISD::FP_TO_UINT_SAT: { 3732 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3733 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3734 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3735 break; 3736 } 3737 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3738 if (Op.getResNo() == 1) { 3739 // The boolean result conforms to getBooleanContents. 3740 // If we know the result of a setcc has the top bits zero, use this info. 3741 // We know that we have an integer-based boolean since these operations 3742 // are only available for integer. 3743 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3744 TargetLowering::ZeroOrOneBooleanContent && 3745 BitWidth > 1) 3746 Known.Zero.setBitsFrom(1); 3747 break; 3748 } 3749 LLVM_FALLTHROUGH; 3750 case ISD::ATOMIC_CMP_SWAP: 3751 case ISD::ATOMIC_SWAP: 3752 case ISD::ATOMIC_LOAD_ADD: 3753 case ISD::ATOMIC_LOAD_SUB: 3754 case ISD::ATOMIC_LOAD_AND: 3755 case ISD::ATOMIC_LOAD_CLR: 3756 case ISD::ATOMIC_LOAD_OR: 3757 case ISD::ATOMIC_LOAD_XOR: 3758 case ISD::ATOMIC_LOAD_NAND: 3759 case ISD::ATOMIC_LOAD_MIN: 3760 case ISD::ATOMIC_LOAD_MAX: 3761 case ISD::ATOMIC_LOAD_UMIN: 3762 case ISD::ATOMIC_LOAD_UMAX: 3763 case ISD::ATOMIC_LOAD: { 3764 unsigned MemBits = 3765 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3766 // If we are looking at the loaded value. 3767 if (Op.getResNo() == 0) { 3768 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3769 Known.Zero.setBitsFrom(MemBits); 3770 } 3771 break; 3772 } 3773 case ISD::FrameIndex: 3774 case ISD::TargetFrameIndex: 3775 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3776 Known, getMachineFunction()); 3777 break; 3778 3779 default: 3780 if (Opcode < ISD::BUILTIN_OP_END) 3781 break; 3782 LLVM_FALLTHROUGH; 3783 case ISD::INTRINSIC_WO_CHAIN: 3784 case ISD::INTRINSIC_W_CHAIN: 3785 case ISD::INTRINSIC_VOID: 3786 // Allow the target to implement this method for its nodes. 3787 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3788 break; 3789 } 3790 3791 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3792 return Known; 3793 } 3794 3795 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3796 SDValue N1) const { 3797 // X + 0 never overflow 3798 if (isNullConstant(N1)) 3799 return OFK_Never; 3800 3801 KnownBits N1Known = computeKnownBits(N1); 3802 if (N1Known.Zero.getBoolValue()) { 3803 KnownBits N0Known = computeKnownBits(N0); 3804 3805 bool overflow; 3806 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3807 if (!overflow) 3808 return OFK_Never; 3809 } 3810 3811 // mulhi + 1 never overflow 3812 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3813 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3814 return OFK_Never; 3815 3816 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3817 KnownBits N0Known = computeKnownBits(N0); 3818 3819 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3820 return OFK_Never; 3821 } 3822 3823 return OFK_Sometime; 3824 } 3825 3826 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3827 EVT OpVT = Val.getValueType(); 3828 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3829 3830 // Is the constant a known power of 2? 3831 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3832 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3833 3834 // A left-shift of a constant one will have exactly one bit set because 3835 // shifting the bit off the end is undefined. 3836 if (Val.getOpcode() == ISD::SHL) { 3837 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3838 if (C && C->getAPIntValue() == 1) 3839 return true; 3840 } 3841 3842 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3843 // one bit set. 3844 if (Val.getOpcode() == ISD::SRL) { 3845 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3846 if (C && C->getAPIntValue().isSignMask()) 3847 return true; 3848 } 3849 3850 // Are all operands of a build vector constant powers of two? 3851 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3852 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3854 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3855 return false; 3856 })) 3857 return true; 3858 3859 // Is the operand of a splat vector a constant power of two? 3860 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3861 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3862 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3863 return true; 3864 3865 // More could be done here, though the above checks are enough 3866 // to handle some common cases. 3867 3868 // Fall back to computeKnownBits to catch other known cases. 3869 KnownBits Known = computeKnownBits(Val); 3870 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3871 } 3872 3873 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3874 EVT VT = Op.getValueType(); 3875 3876 // TODO: Assume we don't know anything for now. 3877 if (VT.isScalableVector()) 3878 return 1; 3879 3880 APInt DemandedElts = VT.isVector() 3881 ? APInt::getAllOnes(VT.getVectorNumElements()) 3882 : APInt(1, 1); 3883 return ComputeNumSignBits(Op, DemandedElts, Depth); 3884 } 3885 3886 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3887 unsigned Depth) const { 3888 EVT VT = Op.getValueType(); 3889 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3890 unsigned VTBits = VT.getScalarSizeInBits(); 3891 unsigned NumElts = DemandedElts.getBitWidth(); 3892 unsigned Tmp, Tmp2; 3893 unsigned FirstAnswer = 1; 3894 3895 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3896 const APInt &Val = C->getAPIntValue(); 3897 return Val.getNumSignBits(); 3898 } 3899 3900 if (Depth >= MaxRecursionDepth) 3901 return 1; // Limit search depth. 3902 3903 if (!DemandedElts || VT.isScalableVector()) 3904 return 1; // No demanded elts, better to assume we don't know anything. 3905 3906 unsigned Opcode = Op.getOpcode(); 3907 switch (Opcode) { 3908 default: break; 3909 case ISD::AssertSext: 3910 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3911 return VTBits-Tmp+1; 3912 case ISD::AssertZext: 3913 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3914 return VTBits-Tmp; 3915 3916 case ISD::BUILD_VECTOR: 3917 Tmp = VTBits; 3918 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3919 if (!DemandedElts[i]) 3920 continue; 3921 3922 SDValue SrcOp = Op.getOperand(i); 3923 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3924 3925 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3926 if (SrcOp.getValueSizeInBits() != VTBits) { 3927 assert(SrcOp.getValueSizeInBits() > VTBits && 3928 "Expected BUILD_VECTOR implicit truncation"); 3929 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3930 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3931 } 3932 Tmp = std::min(Tmp, Tmp2); 3933 } 3934 return Tmp; 3935 3936 case ISD::VECTOR_SHUFFLE: { 3937 // Collect the minimum number of sign bits that are shared by every vector 3938 // element referenced by the shuffle. 3939 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3940 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3941 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3942 for (unsigned i = 0; i != NumElts; ++i) { 3943 int M = SVN->getMaskElt(i); 3944 if (!DemandedElts[i]) 3945 continue; 3946 // For UNDEF elements, we don't know anything about the common state of 3947 // the shuffle result. 3948 if (M < 0) 3949 return 1; 3950 if ((unsigned)M < NumElts) 3951 DemandedLHS.setBit((unsigned)M % NumElts); 3952 else 3953 DemandedRHS.setBit((unsigned)M % NumElts); 3954 } 3955 Tmp = std::numeric_limits<unsigned>::max(); 3956 if (!!DemandedLHS) 3957 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3958 if (!!DemandedRHS) { 3959 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3960 Tmp = std::min(Tmp, Tmp2); 3961 } 3962 // If we don't know anything, early out and try computeKnownBits fall-back. 3963 if (Tmp == 1) 3964 break; 3965 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3966 return Tmp; 3967 } 3968 3969 case ISD::BITCAST: { 3970 SDValue N0 = Op.getOperand(0); 3971 EVT SrcVT = N0.getValueType(); 3972 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3973 3974 // Ignore bitcasts from unsupported types.. 3975 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3976 break; 3977 3978 // Fast handling of 'identity' bitcasts. 3979 if (VTBits == SrcBits) 3980 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3981 3982 bool IsLE = getDataLayout().isLittleEndian(); 3983 3984 // Bitcast 'large element' scalar/vector to 'small element' vector. 3985 if ((SrcBits % VTBits) == 0) { 3986 assert(VT.isVector() && "Expected bitcast to vector"); 3987 3988 unsigned Scale = SrcBits / VTBits; 3989 APInt SrcDemandedElts = 3990 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3991 3992 // Fast case - sign splat can be simply split across the small elements. 3993 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3994 if (Tmp == SrcBits) 3995 return VTBits; 3996 3997 // Slow case - determine how far the sign extends into each sub-element. 3998 Tmp2 = VTBits; 3999 for (unsigned i = 0; i != NumElts; ++i) 4000 if (DemandedElts[i]) { 4001 unsigned SubOffset = i % Scale; 4002 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 4003 SubOffset = SubOffset * VTBits; 4004 if (Tmp <= SubOffset) 4005 return 1; 4006 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 4007 } 4008 return Tmp2; 4009 } 4010 break; 4011 } 4012 4013 case ISD::FP_TO_SINT_SAT: 4014 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 4015 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4016 return VTBits - Tmp + 1; 4017 case ISD::SIGN_EXTEND: 4018 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 4019 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 4020 case ISD::SIGN_EXTEND_INREG: 4021 // Max of the input and what this extends. 4022 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4023 Tmp = VTBits-Tmp+1; 4024 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4025 return std::max(Tmp, Tmp2); 4026 case ISD::SIGN_EXTEND_VECTOR_INREG: { 4027 SDValue Src = Op.getOperand(0); 4028 EVT SrcVT = Src.getValueType(); 4029 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements()); 4030 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4031 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4032 } 4033 case ISD::SRA: 4034 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4035 // SRA X, C -> adds C sign bits. 4036 if (const APInt *ShAmt = 4037 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4038 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4039 return Tmp; 4040 case ISD::SHL: 4041 if (const APInt *ShAmt = 4042 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4043 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4044 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4045 if (ShAmt->ult(Tmp)) 4046 return Tmp - ShAmt->getZExtValue(); 4047 } 4048 break; 4049 case ISD::AND: 4050 case ISD::OR: 4051 case ISD::XOR: // NOT is handled here. 4052 // Logical binary ops preserve the number of sign bits at the worst. 4053 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4054 if (Tmp != 1) { 4055 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4056 FirstAnswer = std::min(Tmp, Tmp2); 4057 // We computed what we know about the sign bits as our first 4058 // answer. Now proceed to the generic code that uses 4059 // computeKnownBits, and pick whichever answer is better. 4060 } 4061 break; 4062 4063 case ISD::SELECT: 4064 case ISD::VSELECT: 4065 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4066 if (Tmp == 1) return 1; // Early out. 4067 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4068 return std::min(Tmp, Tmp2); 4069 case ISD::SELECT_CC: 4070 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4071 if (Tmp == 1) return 1; // Early out. 4072 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4073 return std::min(Tmp, Tmp2); 4074 4075 case ISD::SMIN: 4076 case ISD::SMAX: { 4077 // If we have a clamp pattern, we know that the number of sign bits will be 4078 // the minimum of the clamp min/max range. 4079 bool IsMax = (Opcode == ISD::SMAX); 4080 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4081 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4082 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4083 CstHigh = 4084 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4085 if (CstLow && CstHigh) { 4086 if (!IsMax) 4087 std::swap(CstLow, CstHigh); 4088 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4089 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4090 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4091 return std::min(Tmp, Tmp2); 4092 } 4093 } 4094 4095 // Fallback - just get the minimum number of sign bits of the operands. 4096 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4097 if (Tmp == 1) 4098 return 1; // Early out. 4099 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4100 return std::min(Tmp, Tmp2); 4101 } 4102 case ISD::UMIN: 4103 case ISD::UMAX: 4104 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4105 if (Tmp == 1) 4106 return 1; // Early out. 4107 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4108 return std::min(Tmp, Tmp2); 4109 case ISD::SADDO: 4110 case ISD::UADDO: 4111 case ISD::SSUBO: 4112 case ISD::USUBO: 4113 case ISD::SMULO: 4114 case ISD::UMULO: 4115 if (Op.getResNo() != 1) 4116 break; 4117 // The boolean result conforms to getBooleanContents. Fall through. 4118 // If setcc returns 0/-1, all bits are sign bits. 4119 // We know that we have an integer-based boolean since these operations 4120 // are only available for integer. 4121 if (TLI->getBooleanContents(VT.isVector(), false) == 4122 TargetLowering::ZeroOrNegativeOneBooleanContent) 4123 return VTBits; 4124 break; 4125 case ISD::SETCC: 4126 case ISD::STRICT_FSETCC: 4127 case ISD::STRICT_FSETCCS: { 4128 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4129 // If setcc returns 0/-1, all bits are sign bits. 4130 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4131 TargetLowering::ZeroOrNegativeOneBooleanContent) 4132 return VTBits; 4133 break; 4134 } 4135 case ISD::ROTL: 4136 case ISD::ROTR: 4137 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4138 4139 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4140 if (Tmp == VTBits) 4141 return VTBits; 4142 4143 if (ConstantSDNode *C = 4144 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4145 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4146 4147 // Handle rotate right by N like a rotate left by 32-N. 4148 if (Opcode == ISD::ROTR) 4149 RotAmt = (VTBits - RotAmt) % VTBits; 4150 4151 // If we aren't rotating out all of the known-in sign bits, return the 4152 // number that are left. This handles rotl(sext(x), 1) for example. 4153 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4154 } 4155 break; 4156 case ISD::ADD: 4157 case ISD::ADDC: 4158 // Add can have at most one carry bit. Thus we know that the output 4159 // is, at worst, one more bit than the inputs. 4160 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4161 if (Tmp == 1) return 1; // Early out. 4162 4163 // Special case decrementing a value (ADD X, -1): 4164 if (ConstantSDNode *CRHS = 4165 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4166 if (CRHS->isAllOnes()) { 4167 KnownBits Known = 4168 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4169 4170 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4171 // sign bits set. 4172 if ((Known.Zero | 1).isAllOnes()) 4173 return VTBits; 4174 4175 // If we are subtracting one from a positive number, there is no carry 4176 // out of the result. 4177 if (Known.isNonNegative()) 4178 return Tmp; 4179 } 4180 4181 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4182 if (Tmp2 == 1) return 1; // Early out. 4183 return std::min(Tmp, Tmp2) - 1; 4184 case ISD::SUB: 4185 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4186 if (Tmp2 == 1) return 1; // Early out. 4187 4188 // Handle NEG. 4189 if (ConstantSDNode *CLHS = 4190 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4191 if (CLHS->isZero()) { 4192 KnownBits Known = 4193 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4194 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4195 // sign bits set. 4196 if ((Known.Zero | 1).isAllOnes()) 4197 return VTBits; 4198 4199 // If the input is known to be positive (the sign bit is known clear), 4200 // the output of the NEG has the same number of sign bits as the input. 4201 if (Known.isNonNegative()) 4202 return Tmp2; 4203 4204 // Otherwise, we treat this like a SUB. 4205 } 4206 4207 // Sub can have at most one carry bit. Thus we know that the output 4208 // is, at worst, one more bit than the inputs. 4209 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4210 if (Tmp == 1) return 1; // Early out. 4211 return std::min(Tmp, Tmp2) - 1; 4212 case ISD::MUL: { 4213 // The output of the Mul can be at most twice the valid bits in the inputs. 4214 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4215 if (SignBitsOp0 == 1) 4216 break; 4217 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4218 if (SignBitsOp1 == 1) 4219 break; 4220 unsigned OutValidBits = 4221 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4222 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4223 } 4224 case ISD::SREM: 4225 // The sign bit is the LHS's sign bit, except when the result of the 4226 // remainder is zero. The magnitude of the result should be less than or 4227 // equal to the magnitude of the LHS. Therefore, the result should have 4228 // at least as many sign bits as the left hand side. 4229 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4230 case ISD::TRUNCATE: { 4231 // Check if the sign bits of source go down as far as the truncated value. 4232 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4233 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4234 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4235 return NumSrcSignBits - (NumSrcBits - VTBits); 4236 break; 4237 } 4238 case ISD::EXTRACT_ELEMENT: { 4239 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4240 const int BitWidth = Op.getValueSizeInBits(); 4241 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4242 4243 // Get reverse index (starting from 1), Op1 value indexes elements from 4244 // little end. Sign starts at big end. 4245 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4246 4247 // If the sign portion ends in our element the subtraction gives correct 4248 // result. Otherwise it gives either negative or > bitwidth result 4249 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4250 } 4251 case ISD::INSERT_VECTOR_ELT: { 4252 // If we know the element index, split the demand between the 4253 // source vector and the inserted element, otherwise assume we need 4254 // the original demanded vector elements and the value. 4255 SDValue InVec = Op.getOperand(0); 4256 SDValue InVal = Op.getOperand(1); 4257 SDValue EltNo = Op.getOperand(2); 4258 bool DemandedVal = true; 4259 APInt DemandedVecElts = DemandedElts; 4260 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4261 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4262 unsigned EltIdx = CEltNo->getZExtValue(); 4263 DemandedVal = !!DemandedElts[EltIdx]; 4264 DemandedVecElts.clearBit(EltIdx); 4265 } 4266 Tmp = std::numeric_limits<unsigned>::max(); 4267 if (DemandedVal) { 4268 // TODO - handle implicit truncation of inserted elements. 4269 if (InVal.getScalarValueSizeInBits() != VTBits) 4270 break; 4271 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4272 Tmp = std::min(Tmp, Tmp2); 4273 } 4274 if (!!DemandedVecElts) { 4275 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4276 Tmp = std::min(Tmp, Tmp2); 4277 } 4278 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4279 return Tmp; 4280 } 4281 case ISD::EXTRACT_VECTOR_ELT: { 4282 SDValue InVec = Op.getOperand(0); 4283 SDValue EltNo = Op.getOperand(1); 4284 EVT VecVT = InVec.getValueType(); 4285 // ComputeNumSignBits not yet implemented for scalable vectors. 4286 if (VecVT.isScalableVector()) 4287 break; 4288 const unsigned BitWidth = Op.getValueSizeInBits(); 4289 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4290 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4291 4292 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4293 // anything about sign bits. But if the sizes match we can derive knowledge 4294 // about sign bits from the vector operand. 4295 if (BitWidth != EltBitWidth) 4296 break; 4297 4298 // If we know the element index, just demand that vector element, else for 4299 // an unknown element index, ignore DemandedElts and demand them all. 4300 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4301 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4302 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4303 DemandedSrcElts = 4304 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4305 4306 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4307 } 4308 case ISD::EXTRACT_SUBVECTOR: { 4309 // Offset the demanded elts by the subvector index. 4310 SDValue Src = Op.getOperand(0); 4311 // Bail until we can represent demanded elements for scalable vectors. 4312 if (Src.getValueType().isScalableVector()) 4313 break; 4314 uint64_t Idx = Op.getConstantOperandVal(1); 4315 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4316 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 4317 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4318 } 4319 case ISD::CONCAT_VECTORS: { 4320 // Determine the minimum number of sign bits across all demanded 4321 // elts of the input vectors. Early out if the result is already 1. 4322 Tmp = std::numeric_limits<unsigned>::max(); 4323 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4324 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4325 unsigned NumSubVectors = Op.getNumOperands(); 4326 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4327 APInt DemandedSub = 4328 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4329 if (!DemandedSub) 4330 continue; 4331 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4332 Tmp = std::min(Tmp, Tmp2); 4333 } 4334 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4335 return Tmp; 4336 } 4337 case ISD::INSERT_SUBVECTOR: { 4338 // Demand any elements from the subvector and the remainder from the src its 4339 // inserted into. 4340 SDValue Src = Op.getOperand(0); 4341 SDValue Sub = Op.getOperand(1); 4342 uint64_t Idx = Op.getConstantOperandVal(2); 4343 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4344 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4345 APInt DemandedSrcElts = DemandedElts; 4346 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4347 4348 Tmp = std::numeric_limits<unsigned>::max(); 4349 if (!!DemandedSubElts) { 4350 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4351 if (Tmp == 1) 4352 return 1; // early-out 4353 } 4354 if (!!DemandedSrcElts) { 4355 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4356 Tmp = std::min(Tmp, Tmp2); 4357 } 4358 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4359 return Tmp; 4360 } 4361 case ISD::ATOMIC_CMP_SWAP: 4362 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4363 case ISD::ATOMIC_SWAP: 4364 case ISD::ATOMIC_LOAD_ADD: 4365 case ISD::ATOMIC_LOAD_SUB: 4366 case ISD::ATOMIC_LOAD_AND: 4367 case ISD::ATOMIC_LOAD_CLR: 4368 case ISD::ATOMIC_LOAD_OR: 4369 case ISD::ATOMIC_LOAD_XOR: 4370 case ISD::ATOMIC_LOAD_NAND: 4371 case ISD::ATOMIC_LOAD_MIN: 4372 case ISD::ATOMIC_LOAD_MAX: 4373 case ISD::ATOMIC_LOAD_UMIN: 4374 case ISD::ATOMIC_LOAD_UMAX: 4375 case ISD::ATOMIC_LOAD: { 4376 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4377 // If we are looking at the loaded value. 4378 if (Op.getResNo() == 0) { 4379 if (Tmp == VTBits) 4380 return 1; // early-out 4381 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4382 return VTBits - Tmp + 1; 4383 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4384 return VTBits - Tmp; 4385 } 4386 break; 4387 } 4388 } 4389 4390 // If we are looking at the loaded value of the SDNode. 4391 if (Op.getResNo() == 0) { 4392 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4393 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4394 unsigned ExtType = LD->getExtensionType(); 4395 switch (ExtType) { 4396 default: break; 4397 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4398 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4399 return VTBits - Tmp + 1; 4400 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4401 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4402 return VTBits - Tmp; 4403 case ISD::NON_EXTLOAD: 4404 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4405 // We only need to handle vectors - computeKnownBits should handle 4406 // scalar cases. 4407 Type *CstTy = Cst->getType(); 4408 if (CstTy->isVectorTy() && 4409 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4410 VTBits == CstTy->getScalarSizeInBits()) { 4411 Tmp = VTBits; 4412 for (unsigned i = 0; i != NumElts; ++i) { 4413 if (!DemandedElts[i]) 4414 continue; 4415 if (Constant *Elt = Cst->getAggregateElement(i)) { 4416 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4417 const APInt &Value = CInt->getValue(); 4418 Tmp = std::min(Tmp, Value.getNumSignBits()); 4419 continue; 4420 } 4421 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4422 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4423 Tmp = std::min(Tmp, Value.getNumSignBits()); 4424 continue; 4425 } 4426 } 4427 // Unknown type. Conservatively assume no bits match sign bit. 4428 return 1; 4429 } 4430 return Tmp; 4431 } 4432 } 4433 break; 4434 } 4435 } 4436 } 4437 4438 // Allow the target to implement this method for its nodes. 4439 if (Opcode >= ISD::BUILTIN_OP_END || 4440 Opcode == ISD::INTRINSIC_WO_CHAIN || 4441 Opcode == ISD::INTRINSIC_W_CHAIN || 4442 Opcode == ISD::INTRINSIC_VOID) { 4443 unsigned NumBits = 4444 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4445 if (NumBits > 1) 4446 FirstAnswer = std::max(FirstAnswer, NumBits); 4447 } 4448 4449 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4450 // use this information. 4451 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4452 return std::max(FirstAnswer, Known.countMinSignBits()); 4453 } 4454 4455 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4456 unsigned Depth) const { 4457 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4458 return Op.getScalarValueSizeInBits() - SignBits + 1; 4459 } 4460 4461 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4462 const APInt &DemandedElts, 4463 unsigned Depth) const { 4464 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4465 return Op.getScalarValueSizeInBits() - SignBits + 1; 4466 } 4467 4468 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4469 unsigned Depth) const { 4470 // Early out for FREEZE. 4471 if (Op.getOpcode() == ISD::FREEZE) 4472 return true; 4473 4474 // TODO: Assume we don't know anything for now. 4475 EVT VT = Op.getValueType(); 4476 if (VT.isScalableVector()) 4477 return false; 4478 4479 APInt DemandedElts = VT.isVector() 4480 ? APInt::getAllOnes(VT.getVectorNumElements()) 4481 : APInt(1, 1); 4482 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4483 } 4484 4485 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4486 const APInt &DemandedElts, 4487 bool PoisonOnly, 4488 unsigned Depth) const { 4489 unsigned Opcode = Op.getOpcode(); 4490 4491 // Early out for FREEZE. 4492 if (Opcode == ISD::FREEZE) 4493 return true; 4494 4495 if (Depth >= MaxRecursionDepth) 4496 return false; // Limit search depth. 4497 4498 if (isIntOrFPConstant(Op)) 4499 return true; 4500 4501 switch (Opcode) { 4502 case ISD::UNDEF: 4503 return PoisonOnly; 4504 4505 case ISD::BUILD_VECTOR: 4506 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4507 // this shouldn't affect the result. 4508 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4509 if (!DemandedElts[i]) 4510 continue; 4511 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4512 Depth + 1)) 4513 return false; 4514 } 4515 return true; 4516 4517 // TODO: Search for noundef attributes from library functions. 4518 4519 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4520 4521 default: 4522 // Allow the target to implement this method for its nodes. 4523 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4524 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4525 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4526 Op, DemandedElts, *this, PoisonOnly, Depth); 4527 break; 4528 } 4529 4530 return false; 4531 } 4532 4533 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4534 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4535 !isa<ConstantSDNode>(Op.getOperand(1))) 4536 return false; 4537 4538 if (Op.getOpcode() == ISD::OR && 4539 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4540 return false; 4541 4542 return true; 4543 } 4544 4545 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4546 // If we're told that NaNs won't happen, assume they won't. 4547 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4548 return true; 4549 4550 if (Depth >= MaxRecursionDepth) 4551 return false; // Limit search depth. 4552 4553 // TODO: Handle vectors. 4554 // If the value is a constant, we can obviously see if it is a NaN or not. 4555 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4556 return !C->getValueAPF().isNaN() || 4557 (SNaN && !C->getValueAPF().isSignaling()); 4558 } 4559 4560 unsigned Opcode = Op.getOpcode(); 4561 switch (Opcode) { 4562 case ISD::FADD: 4563 case ISD::FSUB: 4564 case ISD::FMUL: 4565 case ISD::FDIV: 4566 case ISD::FREM: 4567 case ISD::FSIN: 4568 case ISD::FCOS: { 4569 if (SNaN) 4570 return true; 4571 // TODO: Need isKnownNeverInfinity 4572 return false; 4573 } 4574 case ISD::FCANONICALIZE: 4575 case ISD::FEXP: 4576 case ISD::FEXP2: 4577 case ISD::FTRUNC: 4578 case ISD::FFLOOR: 4579 case ISD::FCEIL: 4580 case ISD::FROUND: 4581 case ISD::FROUNDEVEN: 4582 case ISD::FRINT: 4583 case ISD::FNEARBYINT: { 4584 if (SNaN) 4585 return true; 4586 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4587 } 4588 case ISD::FABS: 4589 case ISD::FNEG: 4590 case ISD::FCOPYSIGN: { 4591 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4592 } 4593 case ISD::SELECT: 4594 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4595 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4596 case ISD::FP_EXTEND: 4597 case ISD::FP_ROUND: { 4598 if (SNaN) 4599 return true; 4600 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4601 } 4602 case ISD::SINT_TO_FP: 4603 case ISD::UINT_TO_FP: 4604 return true; 4605 case ISD::FMA: 4606 case ISD::FMAD: { 4607 if (SNaN) 4608 return true; 4609 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4610 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4611 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4612 } 4613 case ISD::FSQRT: // Need is known positive 4614 case ISD::FLOG: 4615 case ISD::FLOG2: 4616 case ISD::FLOG10: 4617 case ISD::FPOWI: 4618 case ISD::FPOW: { 4619 if (SNaN) 4620 return true; 4621 // TODO: Refine on operand 4622 return false; 4623 } 4624 case ISD::FMINNUM: 4625 case ISD::FMAXNUM: { 4626 // Only one needs to be known not-nan, since it will be returned if the 4627 // other ends up being one. 4628 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4629 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4630 } 4631 case ISD::FMINNUM_IEEE: 4632 case ISD::FMAXNUM_IEEE: { 4633 if (SNaN) 4634 return true; 4635 // This can return a NaN if either operand is an sNaN, or if both operands 4636 // are NaN. 4637 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4638 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4639 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4640 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4641 } 4642 case ISD::FMINIMUM: 4643 case ISD::FMAXIMUM: { 4644 // TODO: Does this quiet or return the origina NaN as-is? 4645 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4646 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4647 } 4648 case ISD::EXTRACT_VECTOR_ELT: { 4649 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4650 } 4651 default: 4652 if (Opcode >= ISD::BUILTIN_OP_END || 4653 Opcode == ISD::INTRINSIC_WO_CHAIN || 4654 Opcode == ISD::INTRINSIC_W_CHAIN || 4655 Opcode == ISD::INTRINSIC_VOID) { 4656 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4657 } 4658 4659 return false; 4660 } 4661 } 4662 4663 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4664 assert(Op.getValueType().isFloatingPoint() && 4665 "Floating point type expected"); 4666 4667 // If the value is a constant, we can obviously see if it is a zero or not. 4668 // TODO: Add BuildVector support. 4669 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4670 return !C->isZero(); 4671 return false; 4672 } 4673 4674 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4675 assert(!Op.getValueType().isFloatingPoint() && 4676 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4677 4678 // If the value is a constant, we can obviously see if it is a zero or not. 4679 if (ISD::matchUnaryPredicate(Op, 4680 [](ConstantSDNode *C) { return !C->isZero(); })) 4681 return true; 4682 4683 // TODO: Recognize more cases here. 4684 switch (Op.getOpcode()) { 4685 default: break; 4686 case ISD::OR: 4687 if (isKnownNeverZero(Op.getOperand(1)) || 4688 isKnownNeverZero(Op.getOperand(0))) 4689 return true; 4690 break; 4691 } 4692 4693 return false; 4694 } 4695 4696 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4697 // Check the obvious case. 4698 if (A == B) return true; 4699 4700 // For for negative and positive zero. 4701 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4702 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4703 if (CA->isZero() && CB->isZero()) return true; 4704 4705 // Otherwise they may not be equal. 4706 return false; 4707 } 4708 4709 // Only bits set in Mask must be negated, other bits may be arbitrary. 4710 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) { 4711 if (isBitwiseNot(V, AllowUndefs)) 4712 return V.getOperand(0); 4713 4714 // Handle any_extend (not (truncate X)) pattern, where Mask only sets 4715 // bits in the non-extended part. 4716 ConstantSDNode *MaskC = isConstOrConstSplat(Mask); 4717 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND) 4718 return SDValue(); 4719 SDValue ExtArg = V.getOperand(0); 4720 if (ExtArg.getScalarValueSizeInBits() >= 4721 MaskC->getAPIntValue().getActiveBits() && 4722 isBitwiseNot(ExtArg, AllowUndefs) && 4723 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE && 4724 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType()) 4725 return ExtArg.getOperand(0).getOperand(0); 4726 return SDValue(); 4727 } 4728 4729 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) { 4730 // Match masked merge pattern (X & ~M) op (Y & M) 4731 // Including degenerate case (X & ~M) op M 4732 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask, 4733 SDValue Other) { 4734 if (SDValue NotOperand = 4735 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) { 4736 if (Other == NotOperand) 4737 return true; 4738 if (Other->getOpcode() == ISD::AND) 4739 return NotOperand == Other->getOperand(0) || 4740 NotOperand == Other->getOperand(1); 4741 } 4742 return false; 4743 }; 4744 if (A->getOpcode() == ISD::AND) 4745 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) || 4746 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B); 4747 return false; 4748 } 4749 4750 // FIXME: unify with llvm::haveNoCommonBitsSet. 4751 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4752 assert(A.getValueType() == B.getValueType() && 4753 "Values must have the same type"); 4754 if (haveNoCommonBitsSetCommutative(A, B) || 4755 haveNoCommonBitsSetCommutative(B, A)) 4756 return true; 4757 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4758 computeKnownBits(B)); 4759 } 4760 4761 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4762 SelectionDAG &DAG) { 4763 if (cast<ConstantSDNode>(Step)->isZero()) 4764 return DAG.getConstant(0, DL, VT); 4765 4766 return SDValue(); 4767 } 4768 4769 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4770 ArrayRef<SDValue> Ops, 4771 SelectionDAG &DAG) { 4772 int NumOps = Ops.size(); 4773 assert(NumOps != 0 && "Can't build an empty vector!"); 4774 assert(!VT.isScalableVector() && 4775 "BUILD_VECTOR cannot be used with scalable types"); 4776 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4777 "Incorrect element count in BUILD_VECTOR!"); 4778 4779 // BUILD_VECTOR of UNDEFs is UNDEF. 4780 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4781 return DAG.getUNDEF(VT); 4782 4783 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4784 SDValue IdentitySrc; 4785 bool IsIdentity = true; 4786 for (int i = 0; i != NumOps; ++i) { 4787 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4788 Ops[i].getOperand(0).getValueType() != VT || 4789 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4790 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4791 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4792 IsIdentity = false; 4793 break; 4794 } 4795 IdentitySrc = Ops[i].getOperand(0); 4796 } 4797 if (IsIdentity) 4798 return IdentitySrc; 4799 4800 return SDValue(); 4801 } 4802 4803 /// Try to simplify vector concatenation to an input value, undef, or build 4804 /// vector. 4805 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4806 ArrayRef<SDValue> Ops, 4807 SelectionDAG &DAG) { 4808 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4809 assert(llvm::all_of(Ops, 4810 [Ops](SDValue Op) { 4811 return Ops[0].getValueType() == Op.getValueType(); 4812 }) && 4813 "Concatenation of vectors with inconsistent value types!"); 4814 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4815 VT.getVectorElementCount() && 4816 "Incorrect element count in vector concatenation!"); 4817 4818 if (Ops.size() == 1) 4819 return Ops[0]; 4820 4821 // Concat of UNDEFs is UNDEF. 4822 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4823 return DAG.getUNDEF(VT); 4824 4825 // Scan the operands and look for extract operations from a single source 4826 // that correspond to insertion at the same location via this concatenation: 4827 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4828 SDValue IdentitySrc; 4829 bool IsIdentity = true; 4830 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4831 SDValue Op = Ops[i]; 4832 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4833 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4834 Op.getOperand(0).getValueType() != VT || 4835 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4836 Op.getConstantOperandVal(1) != IdentityIndex) { 4837 IsIdentity = false; 4838 break; 4839 } 4840 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4841 "Unexpected identity source vector for concat of extracts"); 4842 IdentitySrc = Op.getOperand(0); 4843 } 4844 if (IsIdentity) { 4845 assert(IdentitySrc && "Failed to set source vector of extracts"); 4846 return IdentitySrc; 4847 } 4848 4849 // The code below this point is only designed to work for fixed width 4850 // vectors, so we bail out for now. 4851 if (VT.isScalableVector()) 4852 return SDValue(); 4853 4854 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4855 // simplified to one big BUILD_VECTOR. 4856 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4857 EVT SVT = VT.getScalarType(); 4858 SmallVector<SDValue, 16> Elts; 4859 for (SDValue Op : Ops) { 4860 EVT OpVT = Op.getValueType(); 4861 if (Op.isUndef()) 4862 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4863 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4864 Elts.append(Op->op_begin(), Op->op_end()); 4865 else 4866 return SDValue(); 4867 } 4868 4869 // BUILD_VECTOR requires all inputs to be of the same type, find the 4870 // maximum type and extend them all. 4871 for (SDValue Op : Elts) 4872 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4873 4874 if (SVT.bitsGT(VT.getScalarType())) { 4875 for (SDValue &Op : Elts) { 4876 if (Op.isUndef()) 4877 Op = DAG.getUNDEF(SVT); 4878 else 4879 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4880 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4881 : DAG.getSExtOrTrunc(Op, DL, SVT); 4882 } 4883 } 4884 4885 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4886 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4887 return V; 4888 } 4889 4890 /// Gets or creates the specified node. 4891 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4892 FoldingSetNodeID ID; 4893 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4894 void *IP = nullptr; 4895 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4896 return SDValue(E, 0); 4897 4898 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4899 getVTList(VT)); 4900 CSEMap.InsertNode(N, IP); 4901 4902 InsertNode(N); 4903 SDValue V = SDValue(N, 0); 4904 NewSDValueDbgMsg(V, "Creating new node: ", this); 4905 return V; 4906 } 4907 4908 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4909 SDValue Operand) { 4910 SDNodeFlags Flags; 4911 if (Inserter) 4912 Flags = Inserter->getFlags(); 4913 return getNode(Opcode, DL, VT, Operand, Flags); 4914 } 4915 4916 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4917 SDValue Operand, const SDNodeFlags Flags) { 4918 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4919 "Operand is DELETED_NODE!"); 4920 // Constant fold unary operations with an integer constant operand. Even 4921 // opaque constant will be folded, because the folding of unary operations 4922 // doesn't create new constants with different values. Nevertheless, the 4923 // opaque flag is preserved during folding to prevent future folding with 4924 // other constants. 4925 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4926 const APInt &Val = C->getAPIntValue(); 4927 switch (Opcode) { 4928 default: break; 4929 case ISD::SIGN_EXTEND: 4930 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4931 C->isTargetOpcode(), C->isOpaque()); 4932 case ISD::TRUNCATE: 4933 if (C->isOpaque()) 4934 break; 4935 LLVM_FALLTHROUGH; 4936 case ISD::ZERO_EXTEND: 4937 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4938 C->isTargetOpcode(), C->isOpaque()); 4939 case ISD::ANY_EXTEND: 4940 // Some targets like RISCV prefer to sign extend some types. 4941 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4942 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4943 C->isTargetOpcode(), C->isOpaque()); 4944 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4945 C->isTargetOpcode(), C->isOpaque()); 4946 case ISD::UINT_TO_FP: 4947 case ISD::SINT_TO_FP: { 4948 APFloat apf(EVTToAPFloatSemantics(VT), 4949 APInt::getZero(VT.getSizeInBits())); 4950 (void)apf.convertFromAPInt(Val, 4951 Opcode==ISD::SINT_TO_FP, 4952 APFloat::rmNearestTiesToEven); 4953 return getConstantFP(apf, DL, VT); 4954 } 4955 case ISD::BITCAST: 4956 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4957 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4958 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4959 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4960 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4961 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4962 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4963 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4964 break; 4965 case ISD::ABS: 4966 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4967 C->isOpaque()); 4968 case ISD::BITREVERSE: 4969 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4970 C->isOpaque()); 4971 case ISD::BSWAP: 4972 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4973 C->isOpaque()); 4974 case ISD::CTPOP: 4975 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4976 C->isOpaque()); 4977 case ISD::CTLZ: 4978 case ISD::CTLZ_ZERO_UNDEF: 4979 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4980 C->isOpaque()); 4981 case ISD::CTTZ: 4982 case ISD::CTTZ_ZERO_UNDEF: 4983 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4984 C->isOpaque()); 4985 case ISD::FP16_TO_FP: 4986 case ISD::BF16_TO_FP: { 4987 bool Ignored; 4988 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf() 4989 : APFloat::BFloat(), 4990 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4991 4992 // This can return overflow, underflow, or inexact; we don't care. 4993 // FIXME need to be more flexible about rounding mode. 4994 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4995 APFloat::rmNearestTiesToEven, &Ignored); 4996 return getConstantFP(FPV, DL, VT); 4997 } 4998 case ISD::STEP_VECTOR: { 4999 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 5000 return V; 5001 break; 5002 } 5003 } 5004 } 5005 5006 // Constant fold unary operations with a floating point constant operand. 5007 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 5008 APFloat V = C->getValueAPF(); // make copy 5009 switch (Opcode) { 5010 case ISD::FNEG: 5011 V.changeSign(); 5012 return getConstantFP(V, DL, VT); 5013 case ISD::FABS: 5014 V.clearSign(); 5015 return getConstantFP(V, DL, VT); 5016 case ISD::FCEIL: { 5017 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 5018 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5019 return getConstantFP(V, DL, VT); 5020 break; 5021 } 5022 case ISD::FTRUNC: { 5023 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 5024 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5025 return getConstantFP(V, DL, VT); 5026 break; 5027 } 5028 case ISD::FFLOOR: { 5029 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 5030 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5031 return getConstantFP(V, DL, VT); 5032 break; 5033 } 5034 case ISD::FP_EXTEND: { 5035 bool ignored; 5036 // This can return overflow, underflow, or inexact; we don't care. 5037 // FIXME need to be more flexible about rounding mode. 5038 (void)V.convert(EVTToAPFloatSemantics(VT), 5039 APFloat::rmNearestTiesToEven, &ignored); 5040 return getConstantFP(V, DL, VT); 5041 } 5042 case ISD::FP_TO_SINT: 5043 case ISD::FP_TO_UINT: { 5044 bool ignored; 5045 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 5046 // FIXME need to be more flexible about rounding mode. 5047 APFloat::opStatus s = 5048 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 5049 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 5050 break; 5051 return getConstant(IntVal, DL, VT); 5052 } 5053 case ISD::BITCAST: 5054 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 5055 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5056 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 5057 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5058 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 5059 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5060 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 5061 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5062 break; 5063 case ISD::FP_TO_FP16: 5064 case ISD::FP_TO_BF16: { 5065 bool Ignored; 5066 // This can return overflow, underflow, or inexact; we don't care. 5067 // FIXME need to be more flexible about rounding mode. 5068 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf() 5069 : APFloat::BFloat(), 5070 APFloat::rmNearestTiesToEven, &Ignored); 5071 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5072 } 5073 } 5074 } 5075 5076 // Constant fold unary operations with a vector integer or float operand. 5077 switch (Opcode) { 5078 default: 5079 // FIXME: Entirely reasonable to perform folding of other unary 5080 // operations here as the need arises. 5081 break; 5082 case ISD::FNEG: 5083 case ISD::FABS: 5084 case ISD::FCEIL: 5085 case ISD::FTRUNC: 5086 case ISD::FFLOOR: 5087 case ISD::FP_EXTEND: 5088 case ISD::FP_TO_SINT: 5089 case ISD::FP_TO_UINT: 5090 case ISD::TRUNCATE: 5091 case ISD::ANY_EXTEND: 5092 case ISD::ZERO_EXTEND: 5093 case ISD::SIGN_EXTEND: 5094 case ISD::UINT_TO_FP: 5095 case ISD::SINT_TO_FP: 5096 case ISD::ABS: 5097 case ISD::BITREVERSE: 5098 case ISD::BSWAP: 5099 case ISD::CTLZ: 5100 case ISD::CTLZ_ZERO_UNDEF: 5101 case ISD::CTTZ: 5102 case ISD::CTTZ_ZERO_UNDEF: 5103 case ISD::CTPOP: { 5104 SDValue Ops = {Operand}; 5105 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5106 return Fold; 5107 } 5108 } 5109 5110 unsigned OpOpcode = Operand.getNode()->getOpcode(); 5111 switch (Opcode) { 5112 case ISD::STEP_VECTOR: 5113 assert(VT.isScalableVector() && 5114 "STEP_VECTOR can only be used with scalable types"); 5115 assert(OpOpcode == ISD::TargetConstant && 5116 VT.getVectorElementType() == Operand.getValueType() && 5117 "Unexpected step operand"); 5118 break; 5119 case ISD::FREEZE: 5120 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5121 if (isGuaranteedNotToBeUndefOrPoison(Operand)) 5122 return Operand; 5123 break; 5124 case ISD::TokenFactor: 5125 case ISD::MERGE_VALUES: 5126 case ISD::CONCAT_VECTORS: 5127 return Operand; // Factor, merge or concat of one node? No need. 5128 case ISD::BUILD_VECTOR: { 5129 // Attempt to simplify BUILD_VECTOR. 5130 SDValue Ops[] = {Operand}; 5131 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5132 return V; 5133 break; 5134 } 5135 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5136 case ISD::FP_EXTEND: 5137 assert(VT.isFloatingPoint() && 5138 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 5139 if (Operand.getValueType() == VT) return Operand; // noop conversion. 5140 assert((!VT.isVector() || 5141 VT.getVectorElementCount() == 5142 Operand.getValueType().getVectorElementCount()) && 5143 "Vector element count mismatch!"); 5144 assert(Operand.getValueType().bitsLT(VT) && 5145 "Invalid fpext node, dst < src!"); 5146 if (Operand.isUndef()) 5147 return getUNDEF(VT); 5148 break; 5149 case ISD::FP_TO_SINT: 5150 case ISD::FP_TO_UINT: 5151 if (Operand.isUndef()) 5152 return getUNDEF(VT); 5153 break; 5154 case ISD::SINT_TO_FP: 5155 case ISD::UINT_TO_FP: 5156 // [us]itofp(undef) = 0, because the result value is bounded. 5157 if (Operand.isUndef()) 5158 return getConstantFP(0.0, DL, VT); 5159 break; 5160 case ISD::SIGN_EXTEND: 5161 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5162 "Invalid SIGN_EXTEND!"); 5163 assert(VT.isVector() == Operand.getValueType().isVector() && 5164 "SIGN_EXTEND result type type should be vector iff the operand " 5165 "type is vector!"); 5166 if (Operand.getValueType() == VT) return Operand; // noop extension 5167 assert((!VT.isVector() || 5168 VT.getVectorElementCount() == 5169 Operand.getValueType().getVectorElementCount()) && 5170 "Vector element count mismatch!"); 5171 assert(Operand.getValueType().bitsLT(VT) && 5172 "Invalid sext node, dst < src!"); 5173 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5174 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5175 if (OpOpcode == ISD::UNDEF) 5176 // sext(undef) = 0, because the top bits will all be the same. 5177 return getConstant(0, DL, VT); 5178 break; 5179 case ISD::ZERO_EXTEND: 5180 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5181 "Invalid ZERO_EXTEND!"); 5182 assert(VT.isVector() == Operand.getValueType().isVector() && 5183 "ZERO_EXTEND result type type should be vector iff the operand " 5184 "type is vector!"); 5185 if (Operand.getValueType() == VT) return Operand; // noop extension 5186 assert((!VT.isVector() || 5187 VT.getVectorElementCount() == 5188 Operand.getValueType().getVectorElementCount()) && 5189 "Vector element count mismatch!"); 5190 assert(Operand.getValueType().bitsLT(VT) && 5191 "Invalid zext node, dst < src!"); 5192 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5193 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5194 if (OpOpcode == ISD::UNDEF) 5195 // zext(undef) = 0, because the top bits will be zero. 5196 return getConstant(0, DL, VT); 5197 break; 5198 case ISD::ANY_EXTEND: 5199 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5200 "Invalid ANY_EXTEND!"); 5201 assert(VT.isVector() == Operand.getValueType().isVector() && 5202 "ANY_EXTEND result type type should be vector iff the operand " 5203 "type is vector!"); 5204 if (Operand.getValueType() == VT) return Operand; // noop extension 5205 assert((!VT.isVector() || 5206 VT.getVectorElementCount() == 5207 Operand.getValueType().getVectorElementCount()) && 5208 "Vector element count mismatch!"); 5209 assert(Operand.getValueType().bitsLT(VT) && 5210 "Invalid anyext node, dst < src!"); 5211 5212 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5213 OpOpcode == ISD::ANY_EXTEND) 5214 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5215 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5216 if (OpOpcode == ISD::UNDEF) 5217 return getUNDEF(VT); 5218 5219 // (ext (trunc x)) -> x 5220 if (OpOpcode == ISD::TRUNCATE) { 5221 SDValue OpOp = Operand.getOperand(0); 5222 if (OpOp.getValueType() == VT) { 5223 transferDbgValues(Operand, OpOp); 5224 return OpOp; 5225 } 5226 } 5227 break; 5228 case ISD::TRUNCATE: 5229 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5230 "Invalid TRUNCATE!"); 5231 assert(VT.isVector() == Operand.getValueType().isVector() && 5232 "TRUNCATE result type type should be vector iff the operand " 5233 "type is vector!"); 5234 if (Operand.getValueType() == VT) return Operand; // noop truncate 5235 assert((!VT.isVector() || 5236 VT.getVectorElementCount() == 5237 Operand.getValueType().getVectorElementCount()) && 5238 "Vector element count mismatch!"); 5239 assert(Operand.getValueType().bitsGT(VT) && 5240 "Invalid truncate node, src < dst!"); 5241 if (OpOpcode == ISD::TRUNCATE) 5242 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5243 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5244 OpOpcode == ISD::ANY_EXTEND) { 5245 // If the source is smaller than the dest, we still need an extend. 5246 if (Operand.getOperand(0).getValueType().getScalarType() 5247 .bitsLT(VT.getScalarType())) 5248 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5249 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5250 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5251 return Operand.getOperand(0); 5252 } 5253 if (OpOpcode == ISD::UNDEF) 5254 return getUNDEF(VT); 5255 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5256 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5257 break; 5258 case ISD::ANY_EXTEND_VECTOR_INREG: 5259 case ISD::ZERO_EXTEND_VECTOR_INREG: 5260 case ISD::SIGN_EXTEND_VECTOR_INREG: 5261 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5262 assert(Operand.getValueType().bitsLE(VT) && 5263 "The input must be the same size or smaller than the result."); 5264 assert(VT.getVectorMinNumElements() < 5265 Operand.getValueType().getVectorMinNumElements() && 5266 "The destination vector type must have fewer lanes than the input."); 5267 break; 5268 case ISD::ABS: 5269 assert(VT.isInteger() && VT == Operand.getValueType() && 5270 "Invalid ABS!"); 5271 if (OpOpcode == ISD::UNDEF) 5272 return getConstant(0, DL, VT); 5273 break; 5274 case ISD::BSWAP: 5275 assert(VT.isInteger() && VT == Operand.getValueType() && 5276 "Invalid BSWAP!"); 5277 assert((VT.getScalarSizeInBits() % 16 == 0) && 5278 "BSWAP types must be a multiple of 16 bits!"); 5279 if (OpOpcode == ISD::UNDEF) 5280 return getUNDEF(VT); 5281 // bswap(bswap(X)) -> X. 5282 if (OpOpcode == ISD::BSWAP) 5283 return Operand.getOperand(0); 5284 break; 5285 case ISD::BITREVERSE: 5286 assert(VT.isInteger() && VT == Operand.getValueType() && 5287 "Invalid BITREVERSE!"); 5288 if (OpOpcode == ISD::UNDEF) 5289 return getUNDEF(VT); 5290 break; 5291 case ISD::BITCAST: 5292 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5293 "Cannot BITCAST between types of different sizes!"); 5294 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5295 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5296 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5297 if (OpOpcode == ISD::UNDEF) 5298 return getUNDEF(VT); 5299 break; 5300 case ISD::SCALAR_TO_VECTOR: 5301 assert(VT.isVector() && !Operand.getValueType().isVector() && 5302 (VT.getVectorElementType() == Operand.getValueType() || 5303 (VT.getVectorElementType().isInteger() && 5304 Operand.getValueType().isInteger() && 5305 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5306 "Illegal SCALAR_TO_VECTOR node!"); 5307 if (OpOpcode == ISD::UNDEF) 5308 return getUNDEF(VT); 5309 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5310 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5311 isa<ConstantSDNode>(Operand.getOperand(1)) && 5312 Operand.getConstantOperandVal(1) == 0 && 5313 Operand.getOperand(0).getValueType() == VT) 5314 return Operand.getOperand(0); 5315 break; 5316 case ISD::FNEG: 5317 // Negation of an unknown bag of bits is still completely undefined. 5318 if (OpOpcode == ISD::UNDEF) 5319 return getUNDEF(VT); 5320 5321 if (OpOpcode == ISD::FNEG) // --X -> X 5322 return Operand.getOperand(0); 5323 break; 5324 case ISD::FABS: 5325 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5326 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5327 break; 5328 case ISD::VSCALE: 5329 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5330 break; 5331 case ISD::CTPOP: 5332 if (Operand.getValueType().getScalarType() == MVT::i1) 5333 return Operand; 5334 break; 5335 case ISD::CTLZ: 5336 case ISD::CTTZ: 5337 if (Operand.getValueType().getScalarType() == MVT::i1) 5338 return getNOT(DL, Operand, Operand.getValueType()); 5339 break; 5340 case ISD::VECREDUCE_ADD: 5341 if (Operand.getValueType().getScalarType() == MVT::i1) 5342 return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand); 5343 break; 5344 case ISD::VECREDUCE_SMIN: 5345 case ISD::VECREDUCE_UMAX: 5346 if (Operand.getValueType().getScalarType() == MVT::i1) 5347 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5348 break; 5349 case ISD::VECREDUCE_SMAX: 5350 case ISD::VECREDUCE_UMIN: 5351 if (Operand.getValueType().getScalarType() == MVT::i1) 5352 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5353 break; 5354 } 5355 5356 SDNode *N; 5357 SDVTList VTs = getVTList(VT); 5358 SDValue Ops[] = {Operand}; 5359 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5360 FoldingSetNodeID ID; 5361 AddNodeIDNode(ID, Opcode, VTs, Ops); 5362 void *IP = nullptr; 5363 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5364 E->intersectFlagsWith(Flags); 5365 return SDValue(E, 0); 5366 } 5367 5368 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5369 N->setFlags(Flags); 5370 createOperands(N, Ops); 5371 CSEMap.InsertNode(N, IP); 5372 } else { 5373 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5374 createOperands(N, Ops); 5375 } 5376 5377 InsertNode(N); 5378 SDValue V = SDValue(N, 0); 5379 NewSDValueDbgMsg(V, "Creating new node: ", this); 5380 return V; 5381 } 5382 5383 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5384 const APInt &C2) { 5385 switch (Opcode) { 5386 case ISD::ADD: return C1 + C2; 5387 case ISD::SUB: return C1 - C2; 5388 case ISD::MUL: return C1 * C2; 5389 case ISD::AND: return C1 & C2; 5390 case ISD::OR: return C1 | C2; 5391 case ISD::XOR: return C1 ^ C2; 5392 case ISD::SHL: return C1 << C2; 5393 case ISD::SRL: return C1.lshr(C2); 5394 case ISD::SRA: return C1.ashr(C2); 5395 case ISD::ROTL: return C1.rotl(C2); 5396 case ISD::ROTR: return C1.rotr(C2); 5397 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5398 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5399 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5400 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5401 case ISD::SADDSAT: return C1.sadd_sat(C2); 5402 case ISD::UADDSAT: return C1.uadd_sat(C2); 5403 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5404 case ISD::USUBSAT: return C1.usub_sat(C2); 5405 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5406 case ISD::USHLSAT: return C1.ushl_sat(C2); 5407 case ISD::UDIV: 5408 if (!C2.getBoolValue()) 5409 break; 5410 return C1.udiv(C2); 5411 case ISD::UREM: 5412 if (!C2.getBoolValue()) 5413 break; 5414 return C1.urem(C2); 5415 case ISD::SDIV: 5416 if (!C2.getBoolValue()) 5417 break; 5418 return C1.sdiv(C2); 5419 case ISD::SREM: 5420 if (!C2.getBoolValue()) 5421 break; 5422 return C1.srem(C2); 5423 case ISD::MULHS: { 5424 unsigned FullWidth = C1.getBitWidth() * 2; 5425 APInt C1Ext = C1.sext(FullWidth); 5426 APInt C2Ext = C2.sext(FullWidth); 5427 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5428 } 5429 case ISD::MULHU: { 5430 unsigned FullWidth = C1.getBitWidth() * 2; 5431 APInt C1Ext = C1.zext(FullWidth); 5432 APInt C2Ext = C2.zext(FullWidth); 5433 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5434 } 5435 case ISD::AVGFLOORS: { 5436 unsigned FullWidth = C1.getBitWidth() + 1; 5437 APInt C1Ext = C1.sext(FullWidth); 5438 APInt C2Ext = C2.sext(FullWidth); 5439 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5440 } 5441 case ISD::AVGFLOORU: { 5442 unsigned FullWidth = C1.getBitWidth() + 1; 5443 APInt C1Ext = C1.zext(FullWidth); 5444 APInt C2Ext = C2.zext(FullWidth); 5445 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5446 } 5447 case ISD::AVGCEILS: { 5448 unsigned FullWidth = C1.getBitWidth() + 1; 5449 APInt C1Ext = C1.sext(FullWidth); 5450 APInt C2Ext = C2.sext(FullWidth); 5451 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5452 } 5453 case ISD::AVGCEILU: { 5454 unsigned FullWidth = C1.getBitWidth() + 1; 5455 APInt C1Ext = C1.zext(FullWidth); 5456 APInt C2Ext = C2.zext(FullWidth); 5457 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5458 } 5459 } 5460 return llvm::None; 5461 } 5462 5463 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5464 const GlobalAddressSDNode *GA, 5465 const SDNode *N2) { 5466 if (GA->getOpcode() != ISD::GlobalAddress) 5467 return SDValue(); 5468 if (!TLI->isOffsetFoldingLegal(GA)) 5469 return SDValue(); 5470 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5471 if (!C2) 5472 return SDValue(); 5473 int64_t Offset = C2->getSExtValue(); 5474 switch (Opcode) { 5475 case ISD::ADD: break; 5476 case ISD::SUB: Offset = -uint64_t(Offset); break; 5477 default: return SDValue(); 5478 } 5479 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5480 GA->getOffset() + uint64_t(Offset)); 5481 } 5482 5483 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5484 switch (Opcode) { 5485 case ISD::SDIV: 5486 case ISD::UDIV: 5487 case ISD::SREM: 5488 case ISD::UREM: { 5489 // If a divisor is zero/undef or any element of a divisor vector is 5490 // zero/undef, the whole op is undef. 5491 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5492 SDValue Divisor = Ops[1]; 5493 if (Divisor.isUndef() || isNullConstant(Divisor)) 5494 return true; 5495 5496 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5497 llvm::any_of(Divisor->op_values(), 5498 [](SDValue V) { return V.isUndef() || 5499 isNullConstant(V); }); 5500 // TODO: Handle signed overflow. 5501 } 5502 // TODO: Handle oversized shifts. 5503 default: 5504 return false; 5505 } 5506 } 5507 5508 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5509 EVT VT, ArrayRef<SDValue> Ops) { 5510 // If the opcode is a target-specific ISD node, there's nothing we can 5511 // do here and the operand rules may not line up with the below, so 5512 // bail early. 5513 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5514 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5515 // foldCONCAT_VECTORS in getNode before this is called. 5516 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5517 return SDValue(); 5518 5519 unsigned NumOps = Ops.size(); 5520 if (NumOps == 0) 5521 return SDValue(); 5522 5523 if (isUndef(Opcode, Ops)) 5524 return getUNDEF(VT); 5525 5526 // Handle binops special cases. 5527 if (NumOps == 2) { 5528 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5529 return CFP; 5530 5531 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5532 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5533 if (C1->isOpaque() || C2->isOpaque()) 5534 return SDValue(); 5535 5536 Optional<APInt> FoldAttempt = 5537 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5538 if (!FoldAttempt) 5539 return SDValue(); 5540 5541 SDValue Folded = getConstant(*FoldAttempt, DL, VT); 5542 assert((!Folded || !VT.isVector()) && 5543 "Can't fold vectors ops with scalar operands"); 5544 return Folded; 5545 } 5546 } 5547 5548 // fold (add Sym, c) -> Sym+c 5549 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5550 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5551 if (TLI->isCommutativeBinOp(Opcode)) 5552 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5553 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5554 } 5555 5556 // This is for vector folding only from here on. 5557 if (!VT.isVector()) 5558 return SDValue(); 5559 5560 ElementCount NumElts = VT.getVectorElementCount(); 5561 5562 // See if we can fold through bitcasted integer ops. 5563 // TODO: Can we handle undef elements? 5564 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5565 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5566 Ops[0].getOpcode() == ISD::BITCAST && 5567 Ops[1].getOpcode() == ISD::BITCAST) { 5568 SDValue N1 = peekThroughBitcasts(Ops[0]); 5569 SDValue N2 = peekThroughBitcasts(Ops[1]); 5570 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5571 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5572 EVT BVVT = N1.getValueType(); 5573 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5574 bool IsLE = getDataLayout().isLittleEndian(); 5575 unsigned EltBits = VT.getScalarSizeInBits(); 5576 SmallVector<APInt> RawBits1, RawBits2; 5577 BitVector UndefElts1, UndefElts2; 5578 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5579 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5580 UndefElts1.none() && UndefElts2.none()) { 5581 SmallVector<APInt> RawBits; 5582 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5583 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5584 if (!Fold) 5585 break; 5586 RawBits.push_back(*Fold); 5587 } 5588 if (RawBits.size() == NumElts.getFixedValue()) { 5589 // We have constant folded, but we need to cast this again back to 5590 // the original (possibly legalized) type. 5591 SmallVector<APInt> DstBits; 5592 BitVector DstUndefs; 5593 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5594 DstBits, RawBits, DstUndefs, 5595 BitVector(RawBits.size(), false)); 5596 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5597 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5598 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5599 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5600 if (DstUndefs[I]) 5601 continue; 5602 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT); 5603 } 5604 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5605 } 5606 } 5607 } 5608 } 5609 5610 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5611 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5612 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5613 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5614 APInt RHSVal; 5615 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5616 APInt NewStep = Opcode == ISD::MUL 5617 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5618 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5619 return getStepVector(DL, VT, NewStep); 5620 } 5621 } 5622 5623 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5624 return !Op.getValueType().isVector() || 5625 Op.getValueType().getVectorElementCount() == NumElts; 5626 }; 5627 5628 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5629 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5630 Op.getOpcode() == ISD::BUILD_VECTOR || 5631 Op.getOpcode() == ISD::SPLAT_VECTOR; 5632 }; 5633 5634 // All operands must be vector types with the same number of elements as 5635 // the result type and must be either UNDEF or a build/splat vector 5636 // or UNDEF scalars. 5637 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5638 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5639 return SDValue(); 5640 5641 // If we are comparing vectors, then the result needs to be a i1 boolean that 5642 // is then extended back to the legal result type depending on how booleans 5643 // are represented. 5644 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5645 ISD::NodeType ExtendCode = 5646 (Opcode == ISD::SETCC && SVT != VT.getScalarType()) 5647 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT)) 5648 : ISD::SIGN_EXTEND; 5649 5650 // Find legal integer scalar type for constant promotion and 5651 // ensure that its scalar size is at least as large as source. 5652 EVT LegalSVT = VT.getScalarType(); 5653 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5654 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5655 if (LegalSVT.bitsLT(VT.getScalarType())) 5656 return SDValue(); 5657 } 5658 5659 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5660 // only have one operand to check. For fixed-length vector types we may have 5661 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5662 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5663 5664 // Constant fold each scalar lane separately. 5665 SmallVector<SDValue, 4> ScalarResults; 5666 for (unsigned I = 0; I != NumVectorElts; I++) { 5667 SmallVector<SDValue, 4> ScalarOps; 5668 for (SDValue Op : Ops) { 5669 EVT InSVT = Op.getValueType().getScalarType(); 5670 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5671 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5672 if (Op.isUndef()) 5673 ScalarOps.push_back(getUNDEF(InSVT)); 5674 else 5675 ScalarOps.push_back(Op); 5676 continue; 5677 } 5678 5679 SDValue ScalarOp = 5680 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5681 EVT ScalarVT = ScalarOp.getValueType(); 5682 5683 // Build vector (integer) scalar operands may need implicit 5684 // truncation - do this before constant folding. 5685 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 5686 // Don't create illegally-typed nodes unless they're constants or undef 5687 // - if we fail to constant fold we can't guarantee the (dead) nodes 5688 // we're creating will be cleaned up before being visited for 5689 // legalization. 5690 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 5691 !isa<ConstantSDNode>(ScalarOp) && 5692 TLI->getTypeAction(*getContext(), InSVT) != 5693 TargetLowering::TypeLegal) 5694 return SDValue(); 5695 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5696 } 5697 5698 ScalarOps.push_back(ScalarOp); 5699 } 5700 5701 // Constant fold the scalar operands. 5702 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5703 5704 // Legalize the (integer) scalar constant if necessary. 5705 if (LegalSVT != SVT) 5706 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult); 5707 5708 // Scalar folding only succeeded if the result is a constant or UNDEF. 5709 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5710 ScalarResult.getOpcode() != ISD::ConstantFP) 5711 return SDValue(); 5712 ScalarResults.push_back(ScalarResult); 5713 } 5714 5715 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5716 : getBuildVector(VT, DL, ScalarResults); 5717 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5718 return V; 5719 } 5720 5721 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5722 EVT VT, SDValue N1, SDValue N2) { 5723 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5724 // should. That will require dealing with a potentially non-default 5725 // rounding mode, checking the "opStatus" return value from the APFloat 5726 // math calculations, and possibly other variations. 5727 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5728 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5729 if (N1CFP && N2CFP) { 5730 APFloat C1 = N1CFP->getValueAPF(); // make copy 5731 const APFloat &C2 = N2CFP->getValueAPF(); 5732 switch (Opcode) { 5733 case ISD::FADD: 5734 C1.add(C2, APFloat::rmNearestTiesToEven); 5735 return getConstantFP(C1, DL, VT); 5736 case ISD::FSUB: 5737 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5738 return getConstantFP(C1, DL, VT); 5739 case ISD::FMUL: 5740 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5741 return getConstantFP(C1, DL, VT); 5742 case ISD::FDIV: 5743 C1.divide(C2, APFloat::rmNearestTiesToEven); 5744 return getConstantFP(C1, DL, VT); 5745 case ISD::FREM: 5746 C1.mod(C2); 5747 return getConstantFP(C1, DL, VT); 5748 case ISD::FCOPYSIGN: 5749 C1.copySign(C2); 5750 return getConstantFP(C1, DL, VT); 5751 case ISD::FMINNUM: 5752 return getConstantFP(minnum(C1, C2), DL, VT); 5753 case ISD::FMAXNUM: 5754 return getConstantFP(maxnum(C1, C2), DL, VT); 5755 case ISD::FMINIMUM: 5756 return getConstantFP(minimum(C1, C2), DL, VT); 5757 case ISD::FMAXIMUM: 5758 return getConstantFP(maximum(C1, C2), DL, VT); 5759 default: break; 5760 } 5761 } 5762 if (N1CFP && Opcode == ISD::FP_ROUND) { 5763 APFloat C1 = N1CFP->getValueAPF(); // make copy 5764 bool Unused; 5765 // This can return overflow, underflow, or inexact; we don't care. 5766 // FIXME need to be more flexible about rounding mode. 5767 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5768 &Unused); 5769 return getConstantFP(C1, DL, VT); 5770 } 5771 5772 switch (Opcode) { 5773 case ISD::FSUB: 5774 // -0.0 - undef --> undef (consistent with "fneg undef") 5775 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5776 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5777 return getUNDEF(VT); 5778 LLVM_FALLTHROUGH; 5779 5780 case ISD::FADD: 5781 case ISD::FMUL: 5782 case ISD::FDIV: 5783 case ISD::FREM: 5784 // If both operands are undef, the result is undef. If 1 operand is undef, 5785 // the result is NaN. This should match the behavior of the IR optimizer. 5786 if (N1.isUndef() && N2.isUndef()) 5787 return getUNDEF(VT); 5788 if (N1.isUndef() || N2.isUndef()) 5789 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5790 } 5791 return SDValue(); 5792 } 5793 5794 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5795 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5796 5797 // There's no need to assert on a byte-aligned pointer. All pointers are at 5798 // least byte aligned. 5799 if (A == Align(1)) 5800 return Val; 5801 5802 FoldingSetNodeID ID; 5803 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5804 ID.AddInteger(A.value()); 5805 5806 void *IP = nullptr; 5807 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5808 return SDValue(E, 0); 5809 5810 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5811 Val.getValueType(), A); 5812 createOperands(N, {Val}); 5813 5814 CSEMap.InsertNode(N, IP); 5815 InsertNode(N); 5816 5817 SDValue V(N, 0); 5818 NewSDValueDbgMsg(V, "Creating new node: ", this); 5819 return V; 5820 } 5821 5822 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5823 SDValue N1, SDValue N2) { 5824 SDNodeFlags Flags; 5825 if (Inserter) 5826 Flags = Inserter->getFlags(); 5827 return getNode(Opcode, DL, VT, N1, N2, Flags); 5828 } 5829 5830 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5831 SDValue &N2) const { 5832 if (!TLI->isCommutativeBinOp(Opcode)) 5833 return; 5834 5835 // Canonicalize: 5836 // binop(const, nonconst) -> binop(nonconst, const) 5837 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5838 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5839 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5840 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5841 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5842 std::swap(N1, N2); 5843 5844 // Canonicalize: 5845 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5846 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5847 N2.getOpcode() == ISD::STEP_VECTOR) 5848 std::swap(N1, N2); 5849 } 5850 5851 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5852 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5853 assert(N1.getOpcode() != ISD::DELETED_NODE && 5854 N2.getOpcode() != ISD::DELETED_NODE && 5855 "Operand is DELETED_NODE!"); 5856 5857 canonicalizeCommutativeBinop(Opcode, N1, N2); 5858 5859 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5860 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5861 5862 // Don't allow undefs in vector splats - we might be returning N2 when folding 5863 // to zero etc. 5864 ConstantSDNode *N2CV = 5865 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5866 5867 switch (Opcode) { 5868 default: break; 5869 case ISD::TokenFactor: 5870 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5871 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5872 // Fold trivial token factors. 5873 if (N1.getOpcode() == ISD::EntryToken) return N2; 5874 if (N2.getOpcode() == ISD::EntryToken) return N1; 5875 if (N1 == N2) return N1; 5876 break; 5877 case ISD::BUILD_VECTOR: { 5878 // Attempt to simplify BUILD_VECTOR. 5879 SDValue Ops[] = {N1, N2}; 5880 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5881 return V; 5882 break; 5883 } 5884 case ISD::CONCAT_VECTORS: { 5885 SDValue Ops[] = {N1, N2}; 5886 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5887 return V; 5888 break; 5889 } 5890 case ISD::AND: 5891 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5892 assert(N1.getValueType() == N2.getValueType() && 5893 N1.getValueType() == VT && "Binary operator types must match!"); 5894 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5895 // worth handling here. 5896 if (N2CV && N2CV->isZero()) 5897 return N2; 5898 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5899 return N1; 5900 break; 5901 case ISD::OR: 5902 case ISD::XOR: 5903 case ISD::ADD: 5904 case ISD::SUB: 5905 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5906 assert(N1.getValueType() == N2.getValueType() && 5907 N1.getValueType() == VT && "Binary operator types must match!"); 5908 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5909 // it's worth handling here. 5910 if (N2CV && N2CV->isZero()) 5911 return N1; 5912 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5913 VT.getVectorElementType() == MVT::i1) 5914 return getNode(ISD::XOR, DL, VT, N1, N2); 5915 break; 5916 case ISD::MUL: 5917 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5918 assert(N1.getValueType() == N2.getValueType() && 5919 N1.getValueType() == VT && "Binary operator types must match!"); 5920 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5921 return getNode(ISD::AND, DL, VT, N1, N2); 5922 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5923 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5924 const APInt &N2CImm = N2C->getAPIntValue(); 5925 return getVScale(DL, VT, MulImm * N2CImm); 5926 } 5927 break; 5928 case ISD::UDIV: 5929 case ISD::UREM: 5930 case ISD::MULHU: 5931 case ISD::MULHS: 5932 case ISD::SDIV: 5933 case ISD::SREM: 5934 case ISD::SADDSAT: 5935 case ISD::SSUBSAT: 5936 case ISD::UADDSAT: 5937 case ISD::USUBSAT: 5938 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5939 assert(N1.getValueType() == N2.getValueType() && 5940 N1.getValueType() == VT && "Binary operator types must match!"); 5941 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5942 // fold (add_sat x, y) -> (or x, y) for bool types. 5943 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5944 return getNode(ISD::OR, DL, VT, N1, N2); 5945 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5946 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5947 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5948 } 5949 break; 5950 case ISD::SMIN: 5951 case ISD::UMAX: 5952 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5953 assert(N1.getValueType() == N2.getValueType() && 5954 N1.getValueType() == VT && "Binary operator types must match!"); 5955 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5956 return getNode(ISD::OR, DL, VT, N1, N2); 5957 break; 5958 case ISD::SMAX: 5959 case ISD::UMIN: 5960 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5961 assert(N1.getValueType() == N2.getValueType() && 5962 N1.getValueType() == VT && "Binary operator types must match!"); 5963 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5964 return getNode(ISD::AND, DL, VT, N1, N2); 5965 break; 5966 case ISD::FADD: 5967 case ISD::FSUB: 5968 case ISD::FMUL: 5969 case ISD::FDIV: 5970 case ISD::FREM: 5971 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5972 assert(N1.getValueType() == N2.getValueType() && 5973 N1.getValueType() == VT && "Binary operator types must match!"); 5974 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5975 return V; 5976 break; 5977 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5978 assert(N1.getValueType() == VT && 5979 N1.getValueType().isFloatingPoint() && 5980 N2.getValueType().isFloatingPoint() && 5981 "Invalid FCOPYSIGN!"); 5982 break; 5983 case ISD::SHL: 5984 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5985 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5986 const APInt &ShiftImm = N2C->getAPIntValue(); 5987 return getVScale(DL, VT, MulImm << ShiftImm); 5988 } 5989 LLVM_FALLTHROUGH; 5990 case ISD::SRA: 5991 case ISD::SRL: 5992 if (SDValue V = simplifyShift(N1, N2)) 5993 return V; 5994 LLVM_FALLTHROUGH; 5995 case ISD::ROTL: 5996 case ISD::ROTR: 5997 assert(VT == N1.getValueType() && 5998 "Shift operators return type must be the same as their first arg"); 5999 assert(VT.isInteger() && N2.getValueType().isInteger() && 6000 "Shifts only work on integers"); 6001 assert((!VT.isVector() || VT == N2.getValueType()) && 6002 "Vector shift amounts must be in the same as their first arg"); 6003 // Verify that the shift amount VT is big enough to hold valid shift 6004 // amounts. This catches things like trying to shift an i1024 value by an 6005 // i8, which is easy to fall into in generic code that uses 6006 // TLI.getShiftAmount(). 6007 assert(N2.getValueType().getScalarSizeInBits() >= 6008 Log2_32_Ceil(VT.getScalarSizeInBits()) && 6009 "Invalid use of small shift amount with oversized value!"); 6010 6011 // Always fold shifts of i1 values so the code generator doesn't need to 6012 // handle them. Since we know the size of the shift has to be less than the 6013 // size of the value, the shift/rotate count is guaranteed to be zero. 6014 if (VT == MVT::i1) 6015 return N1; 6016 if (N2CV && N2CV->isZero()) 6017 return N1; 6018 break; 6019 case ISD::FP_ROUND: 6020 assert(VT.isFloatingPoint() && 6021 N1.getValueType().isFloatingPoint() && 6022 VT.bitsLE(N1.getValueType()) && 6023 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 6024 "Invalid FP_ROUND!"); 6025 if (N1.getValueType() == VT) return N1; // noop conversion. 6026 break; 6027 case ISD::AssertSext: 6028 case ISD::AssertZext: { 6029 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6030 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6031 assert(VT.isInteger() && EVT.isInteger() && 6032 "Cannot *_EXTEND_INREG FP types"); 6033 assert(!EVT.isVector() && 6034 "AssertSExt/AssertZExt type should be the vector element type " 6035 "rather than the vector type!"); 6036 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 6037 if (VT.getScalarType() == EVT) return N1; // noop assertion. 6038 break; 6039 } 6040 case ISD::SIGN_EXTEND_INREG: { 6041 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6042 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6043 assert(VT.isInteger() && EVT.isInteger() && 6044 "Cannot *_EXTEND_INREG FP types"); 6045 assert(EVT.isVector() == VT.isVector() && 6046 "SIGN_EXTEND_INREG type should be vector iff the operand " 6047 "type is vector!"); 6048 assert((!EVT.isVector() || 6049 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 6050 "Vector element counts must match in SIGN_EXTEND_INREG"); 6051 assert(EVT.bitsLE(VT) && "Not extending!"); 6052 if (EVT == VT) return N1; // Not actually extending 6053 6054 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 6055 unsigned FromBits = EVT.getScalarSizeInBits(); 6056 Val <<= Val.getBitWidth() - FromBits; 6057 Val.ashrInPlace(Val.getBitWidth() - FromBits); 6058 return getConstant(Val, DL, ConstantVT); 6059 }; 6060 6061 if (N1C) { 6062 const APInt &Val = N1C->getAPIntValue(); 6063 return SignExtendInReg(Val, VT); 6064 } 6065 6066 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 6067 SmallVector<SDValue, 8> Ops; 6068 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 6069 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6070 SDValue Op = N1.getOperand(i); 6071 if (Op.isUndef()) { 6072 Ops.push_back(getUNDEF(OpVT)); 6073 continue; 6074 } 6075 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6076 APInt Val = C->getAPIntValue(); 6077 Ops.push_back(SignExtendInReg(Val, OpVT)); 6078 } 6079 return getBuildVector(VT, DL, Ops); 6080 } 6081 break; 6082 } 6083 case ISD::FP_TO_SINT_SAT: 6084 case ISD::FP_TO_UINT_SAT: { 6085 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6086 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6087 assert(N1.getValueType().isVector() == VT.isVector() && 6088 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6089 "vector!"); 6090 assert((!VT.isVector() || VT.getVectorNumElements() == 6091 N1.getValueType().getVectorNumElements()) && 6092 "Vector element counts must match in FP_TO_*INT_SAT"); 6093 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6094 "Type to saturate to must be a scalar."); 6095 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6096 "Not extending!"); 6097 break; 6098 } 6099 case ISD::EXTRACT_VECTOR_ELT: 6100 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6101 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6102 element type of the vector."); 6103 6104 // Extract from an undefined value or using an undefined index is undefined. 6105 if (N1.isUndef() || N2.isUndef()) 6106 return getUNDEF(VT); 6107 6108 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6109 // vectors. For scalable vectors we will provide appropriate support for 6110 // dealing with arbitrary indices. 6111 if (N2C && N1.getValueType().isFixedLengthVector() && 6112 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6113 return getUNDEF(VT); 6114 6115 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6116 // expanding copies of large vectors from registers. This only works for 6117 // fixed length vectors, since we need to know the exact number of 6118 // elements. 6119 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6120 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6121 unsigned Factor = 6122 N1.getOperand(0).getValueType().getVectorNumElements(); 6123 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6124 N1.getOperand(N2C->getZExtValue() / Factor), 6125 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6126 } 6127 6128 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6129 // lowering is expanding large vector constants. 6130 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6131 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6132 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6133 N1.getValueType().isFixedLengthVector()) && 6134 "BUILD_VECTOR used for scalable vectors"); 6135 unsigned Index = 6136 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6137 SDValue Elt = N1.getOperand(Index); 6138 6139 if (VT != Elt.getValueType()) 6140 // If the vector element type is not legal, the BUILD_VECTOR operands 6141 // are promoted and implicitly truncated, and the result implicitly 6142 // extended. Make that explicit here. 6143 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6144 6145 return Elt; 6146 } 6147 6148 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6149 // operations are lowered to scalars. 6150 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6151 // If the indices are the same, return the inserted element else 6152 // if the indices are known different, extract the element from 6153 // the original vector. 6154 SDValue N1Op2 = N1.getOperand(2); 6155 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6156 6157 if (N1Op2C && N2C) { 6158 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6159 if (VT == N1.getOperand(1).getValueType()) 6160 return N1.getOperand(1); 6161 if (VT.isFloatingPoint()) { 6162 assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits()); 6163 return getFPExtendOrRound(N1.getOperand(1), DL, VT); 6164 } 6165 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6166 } 6167 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6168 } 6169 } 6170 6171 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6172 // when vector types are scalarized and v1iX is legal. 6173 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6174 // Here we are completely ignoring the extract element index (N2), 6175 // which is fine for fixed width vectors, since any index other than 0 6176 // is undefined anyway. However, this cannot be ignored for scalable 6177 // vectors - in theory we could support this, but we don't want to do this 6178 // without a profitability check. 6179 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6180 N1.getValueType().isFixedLengthVector() && 6181 N1.getValueType().getVectorNumElements() == 1) { 6182 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6183 N1.getOperand(1)); 6184 } 6185 break; 6186 case ISD::EXTRACT_ELEMENT: 6187 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6188 assert(!N1.getValueType().isVector() && !VT.isVector() && 6189 (N1.getValueType().isInteger() == VT.isInteger()) && 6190 N1.getValueType() != VT && 6191 "Wrong types for EXTRACT_ELEMENT!"); 6192 6193 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6194 // 64-bit integers into 32-bit parts. Instead of building the extract of 6195 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6196 if (N1.getOpcode() == ISD::BUILD_PAIR) 6197 return N1.getOperand(N2C->getZExtValue()); 6198 6199 // EXTRACT_ELEMENT of a constant int is also very common. 6200 if (N1C) { 6201 unsigned ElementSize = VT.getSizeInBits(); 6202 unsigned Shift = ElementSize * N2C->getZExtValue(); 6203 const APInt &Val = N1C->getAPIntValue(); 6204 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6205 } 6206 break; 6207 case ISD::EXTRACT_SUBVECTOR: { 6208 EVT N1VT = N1.getValueType(); 6209 assert(VT.isVector() && N1VT.isVector() && 6210 "Extract subvector VTs must be vectors!"); 6211 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6212 "Extract subvector VTs must have the same element type!"); 6213 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6214 "Cannot extract a scalable vector from a fixed length vector!"); 6215 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6216 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6217 "Extract subvector must be from larger vector to smaller vector!"); 6218 assert(N2C && "Extract subvector index must be a constant"); 6219 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6220 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6221 N1VT.getVectorMinNumElements()) && 6222 "Extract subvector overflow!"); 6223 assert(N2C->getAPIntValue().getBitWidth() == 6224 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6225 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6226 6227 // Trivial extraction. 6228 if (VT == N1VT) 6229 return N1; 6230 6231 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6232 if (N1.isUndef()) 6233 return getUNDEF(VT); 6234 6235 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6236 // the concat have the same type as the extract. 6237 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6238 VT == N1.getOperand(0).getValueType()) { 6239 unsigned Factor = VT.getVectorMinNumElements(); 6240 return N1.getOperand(N2C->getZExtValue() / Factor); 6241 } 6242 6243 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6244 // during shuffle legalization. 6245 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6246 VT == N1.getOperand(1).getValueType()) 6247 return N1.getOperand(1); 6248 break; 6249 } 6250 } 6251 6252 // Perform trivial constant folding. 6253 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6254 return SV; 6255 6256 // Canonicalize an UNDEF to the RHS, even over a constant. 6257 if (N1.isUndef()) { 6258 if (TLI->isCommutativeBinOp(Opcode)) { 6259 std::swap(N1, N2); 6260 } else { 6261 switch (Opcode) { 6262 case ISD::SUB: 6263 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6264 case ISD::SIGN_EXTEND_INREG: 6265 case ISD::UDIV: 6266 case ISD::SDIV: 6267 case ISD::UREM: 6268 case ISD::SREM: 6269 case ISD::SSUBSAT: 6270 case ISD::USUBSAT: 6271 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6272 } 6273 } 6274 } 6275 6276 // Fold a bunch of operators when the RHS is undef. 6277 if (N2.isUndef()) { 6278 switch (Opcode) { 6279 case ISD::XOR: 6280 if (N1.isUndef()) 6281 // Handle undef ^ undef -> 0 special case. This is a common 6282 // idiom (misuse). 6283 return getConstant(0, DL, VT); 6284 LLVM_FALLTHROUGH; 6285 case ISD::ADD: 6286 case ISD::SUB: 6287 case ISD::UDIV: 6288 case ISD::SDIV: 6289 case ISD::UREM: 6290 case ISD::SREM: 6291 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6292 case ISD::MUL: 6293 case ISD::AND: 6294 case ISD::SSUBSAT: 6295 case ISD::USUBSAT: 6296 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6297 case ISD::OR: 6298 case ISD::SADDSAT: 6299 case ISD::UADDSAT: 6300 return getAllOnesConstant(DL, VT); 6301 } 6302 } 6303 6304 // Memoize this node if possible. 6305 SDNode *N; 6306 SDVTList VTs = getVTList(VT); 6307 SDValue Ops[] = {N1, N2}; 6308 if (VT != MVT::Glue) { 6309 FoldingSetNodeID ID; 6310 AddNodeIDNode(ID, Opcode, VTs, Ops); 6311 void *IP = nullptr; 6312 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6313 E->intersectFlagsWith(Flags); 6314 return SDValue(E, 0); 6315 } 6316 6317 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6318 N->setFlags(Flags); 6319 createOperands(N, Ops); 6320 CSEMap.InsertNode(N, IP); 6321 } else { 6322 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6323 createOperands(N, Ops); 6324 } 6325 6326 InsertNode(N); 6327 SDValue V = SDValue(N, 0); 6328 NewSDValueDbgMsg(V, "Creating new node: ", this); 6329 return V; 6330 } 6331 6332 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6333 SDValue N1, SDValue N2, SDValue N3) { 6334 SDNodeFlags Flags; 6335 if (Inserter) 6336 Flags = Inserter->getFlags(); 6337 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6338 } 6339 6340 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6341 SDValue N1, SDValue N2, SDValue N3, 6342 const SDNodeFlags Flags) { 6343 assert(N1.getOpcode() != ISD::DELETED_NODE && 6344 N2.getOpcode() != ISD::DELETED_NODE && 6345 N3.getOpcode() != ISD::DELETED_NODE && 6346 "Operand is DELETED_NODE!"); 6347 // Perform various simplifications. 6348 switch (Opcode) { 6349 case ISD::FMA: { 6350 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6351 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6352 N3.getValueType() == VT && "FMA types must match!"); 6353 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6354 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6355 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6356 if (N1CFP && N2CFP && N3CFP) { 6357 APFloat V1 = N1CFP->getValueAPF(); 6358 const APFloat &V2 = N2CFP->getValueAPF(); 6359 const APFloat &V3 = N3CFP->getValueAPF(); 6360 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6361 return getConstantFP(V1, DL, VT); 6362 } 6363 break; 6364 } 6365 case ISD::BUILD_VECTOR: { 6366 // Attempt to simplify BUILD_VECTOR. 6367 SDValue Ops[] = {N1, N2, N3}; 6368 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6369 return V; 6370 break; 6371 } 6372 case ISD::CONCAT_VECTORS: { 6373 SDValue Ops[] = {N1, N2, N3}; 6374 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6375 return V; 6376 break; 6377 } 6378 case ISD::SETCC: { 6379 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6380 assert(N1.getValueType() == N2.getValueType() && 6381 "SETCC operands must have the same type!"); 6382 assert(VT.isVector() == N1.getValueType().isVector() && 6383 "SETCC type should be vector iff the operand type is vector!"); 6384 assert((!VT.isVector() || VT.getVectorElementCount() == 6385 N1.getValueType().getVectorElementCount()) && 6386 "SETCC vector element counts must match!"); 6387 // Use FoldSetCC to simplify SETCC's. 6388 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6389 return V; 6390 // Vector constant folding. 6391 SDValue Ops[] = {N1, N2, N3}; 6392 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6393 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6394 return V; 6395 } 6396 break; 6397 } 6398 case ISD::SELECT: 6399 case ISD::VSELECT: 6400 if (SDValue V = simplifySelect(N1, N2, N3)) 6401 return V; 6402 break; 6403 case ISD::VECTOR_SHUFFLE: 6404 llvm_unreachable("should use getVectorShuffle constructor!"); 6405 case ISD::VECTOR_SPLICE: { 6406 if (cast<ConstantSDNode>(N3)->isNullValue()) 6407 return N1; 6408 break; 6409 } 6410 case ISD::INSERT_VECTOR_ELT: { 6411 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6412 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6413 // for scalable vectors where we will generate appropriate code to 6414 // deal with out-of-bounds cases correctly. 6415 if (N3C && N1.getValueType().isFixedLengthVector() && 6416 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6417 return getUNDEF(VT); 6418 6419 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6420 if (N3.isUndef()) 6421 return getUNDEF(VT); 6422 6423 // If the inserted element is an UNDEF, just use the input vector. 6424 if (N2.isUndef()) 6425 return N1; 6426 6427 break; 6428 } 6429 case ISD::INSERT_SUBVECTOR: { 6430 // Inserting undef into undef is still undef. 6431 if (N1.isUndef() && N2.isUndef()) 6432 return getUNDEF(VT); 6433 6434 EVT N2VT = N2.getValueType(); 6435 assert(VT == N1.getValueType() && 6436 "Dest and insert subvector source types must match!"); 6437 assert(VT.isVector() && N2VT.isVector() && 6438 "Insert subvector VTs must be vectors!"); 6439 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6440 "Cannot insert a scalable vector into a fixed length vector!"); 6441 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6442 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6443 "Insert subvector must be from smaller vector to larger vector!"); 6444 assert(isa<ConstantSDNode>(N3) && 6445 "Insert subvector index must be constant"); 6446 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6447 (N2VT.getVectorMinNumElements() + 6448 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6449 VT.getVectorMinNumElements()) && 6450 "Insert subvector overflow!"); 6451 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6452 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6453 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6454 6455 // Trivial insertion. 6456 if (VT == N2VT) 6457 return N2; 6458 6459 // If this is an insert of an extracted vector into an undef vector, we 6460 // can just use the input to the extract. 6461 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6462 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6463 return N2.getOperand(0); 6464 break; 6465 } 6466 case ISD::BITCAST: 6467 // Fold bit_convert nodes from a type to themselves. 6468 if (N1.getValueType() == VT) 6469 return N1; 6470 break; 6471 } 6472 6473 // Memoize node if it doesn't produce a flag. 6474 SDNode *N; 6475 SDVTList VTs = getVTList(VT); 6476 SDValue Ops[] = {N1, N2, N3}; 6477 if (VT != MVT::Glue) { 6478 FoldingSetNodeID ID; 6479 AddNodeIDNode(ID, Opcode, VTs, Ops); 6480 void *IP = nullptr; 6481 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6482 E->intersectFlagsWith(Flags); 6483 return SDValue(E, 0); 6484 } 6485 6486 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6487 N->setFlags(Flags); 6488 createOperands(N, Ops); 6489 CSEMap.InsertNode(N, IP); 6490 } else { 6491 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6492 createOperands(N, Ops); 6493 } 6494 6495 InsertNode(N); 6496 SDValue V = SDValue(N, 0); 6497 NewSDValueDbgMsg(V, "Creating new node: ", this); 6498 return V; 6499 } 6500 6501 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6502 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6503 SDValue Ops[] = { N1, N2, N3, N4 }; 6504 return getNode(Opcode, DL, VT, Ops); 6505 } 6506 6507 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6508 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6509 SDValue N5) { 6510 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6511 return getNode(Opcode, DL, VT, Ops); 6512 } 6513 6514 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6515 /// the incoming stack arguments to be loaded from the stack. 6516 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6517 SmallVector<SDValue, 8> ArgChains; 6518 6519 // Include the original chain at the beginning of the list. When this is 6520 // used by target LowerCall hooks, this helps legalize find the 6521 // CALLSEQ_BEGIN node. 6522 ArgChains.push_back(Chain); 6523 6524 // Add a chain value for each stack argument. 6525 for (SDNode *U : getEntryNode().getNode()->uses()) 6526 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6527 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6528 if (FI->getIndex() < 0) 6529 ArgChains.push_back(SDValue(L, 1)); 6530 6531 // Build a tokenfactor for all the chains. 6532 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6533 } 6534 6535 /// getMemsetValue - Vectorized representation of the memset value 6536 /// operand. 6537 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6538 const SDLoc &dl) { 6539 assert(!Value.isUndef()); 6540 6541 unsigned NumBits = VT.getScalarSizeInBits(); 6542 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6543 assert(C->getAPIntValue().getBitWidth() == 8); 6544 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6545 if (VT.isInteger()) { 6546 bool IsOpaque = VT.getSizeInBits() > 64 || 6547 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6548 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6549 } 6550 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6551 VT); 6552 } 6553 6554 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6555 EVT IntVT = VT.getScalarType(); 6556 if (!IntVT.isInteger()) 6557 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6558 6559 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6560 if (NumBits > 8) { 6561 // Use a multiplication with 0x010101... to extend the input to the 6562 // required length. 6563 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6564 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6565 DAG.getConstant(Magic, dl, IntVT)); 6566 } 6567 6568 if (VT != Value.getValueType() && !VT.isInteger()) 6569 Value = DAG.getBitcast(VT.getScalarType(), Value); 6570 if (VT != Value.getValueType()) 6571 Value = DAG.getSplatBuildVector(VT, dl, Value); 6572 6573 return Value; 6574 } 6575 6576 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6577 /// used when a memcpy is turned into a memset when the source is a constant 6578 /// string ptr. 6579 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6580 const TargetLowering &TLI, 6581 const ConstantDataArraySlice &Slice) { 6582 // Handle vector with all elements zero. 6583 if (Slice.Array == nullptr) { 6584 if (VT.isInteger()) 6585 return DAG.getConstant(0, dl, VT); 6586 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6587 return DAG.getConstantFP(0.0, dl, VT); 6588 if (VT.isVector()) { 6589 unsigned NumElts = VT.getVectorNumElements(); 6590 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6591 return DAG.getNode(ISD::BITCAST, dl, VT, 6592 DAG.getConstant(0, dl, 6593 EVT::getVectorVT(*DAG.getContext(), 6594 EltVT, NumElts))); 6595 } 6596 llvm_unreachable("Expected type!"); 6597 } 6598 6599 assert(!VT.isVector() && "Can't handle vector type here!"); 6600 unsigned NumVTBits = VT.getSizeInBits(); 6601 unsigned NumVTBytes = NumVTBits / 8; 6602 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6603 6604 APInt Val(NumVTBits, 0); 6605 if (DAG.getDataLayout().isLittleEndian()) { 6606 for (unsigned i = 0; i != NumBytes; ++i) 6607 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6608 } else { 6609 for (unsigned i = 0; i != NumBytes; ++i) 6610 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6611 } 6612 6613 // If the "cost" of materializing the integer immediate is less than the cost 6614 // of a load, then it is cost effective to turn the load into the immediate. 6615 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6616 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6617 return DAG.getConstant(Val, dl, VT); 6618 return SDValue(); 6619 } 6620 6621 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6622 const SDLoc &DL, 6623 const SDNodeFlags Flags) { 6624 EVT VT = Base.getValueType(); 6625 SDValue Index; 6626 6627 if (Offset.isScalable()) 6628 Index = getVScale(DL, Base.getValueType(), 6629 APInt(Base.getValueSizeInBits().getFixedSize(), 6630 Offset.getKnownMinSize())); 6631 else 6632 Index = getConstant(Offset.getFixedSize(), DL, VT); 6633 6634 return getMemBasePlusOffset(Base, Index, DL, Flags); 6635 } 6636 6637 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6638 const SDLoc &DL, 6639 const SDNodeFlags Flags) { 6640 assert(Offset.getValueType().isInteger()); 6641 EVT BasePtrVT = Ptr.getValueType(); 6642 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6643 } 6644 6645 /// Returns true if memcpy source is constant data. 6646 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6647 uint64_t SrcDelta = 0; 6648 GlobalAddressSDNode *G = nullptr; 6649 if (Src.getOpcode() == ISD::GlobalAddress) 6650 G = cast<GlobalAddressSDNode>(Src); 6651 else if (Src.getOpcode() == ISD::ADD && 6652 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6653 Src.getOperand(1).getOpcode() == ISD::Constant) { 6654 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6655 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6656 } 6657 if (!G) 6658 return false; 6659 6660 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6661 SrcDelta + G->getOffset()); 6662 } 6663 6664 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6665 SelectionDAG &DAG) { 6666 // On Darwin, -Os means optimize for size without hurting performance, so 6667 // only really optimize for size when -Oz (MinSize) is used. 6668 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6669 return MF.getFunction().hasMinSize(); 6670 return DAG.shouldOptForSize(); 6671 } 6672 6673 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6674 SmallVector<SDValue, 32> &OutChains, unsigned From, 6675 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6676 SmallVector<SDValue, 16> &OutStoreChains) { 6677 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6678 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6679 SmallVector<SDValue, 16> GluedLoadChains; 6680 for (unsigned i = From; i < To; ++i) { 6681 OutChains.push_back(OutLoadChains[i]); 6682 GluedLoadChains.push_back(OutLoadChains[i]); 6683 } 6684 6685 // Chain for all loads. 6686 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6687 GluedLoadChains); 6688 6689 for (unsigned i = From; i < To; ++i) { 6690 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6691 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6692 ST->getBasePtr(), ST->getMemoryVT(), 6693 ST->getMemOperand()); 6694 OutChains.push_back(NewStore); 6695 } 6696 } 6697 6698 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6699 SDValue Chain, SDValue Dst, SDValue Src, 6700 uint64_t Size, Align Alignment, 6701 bool isVol, bool AlwaysInline, 6702 MachinePointerInfo DstPtrInfo, 6703 MachinePointerInfo SrcPtrInfo, 6704 const AAMDNodes &AAInfo) { 6705 // Turn a memcpy of undef to nop. 6706 // FIXME: We need to honor volatile even is Src is undef. 6707 if (Src.isUndef()) 6708 return Chain; 6709 6710 // Expand memcpy to a series of load and store ops if the size operand falls 6711 // below a certain threshold. 6712 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6713 // rather than maybe a humongous number of loads and stores. 6714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6715 const DataLayout &DL = DAG.getDataLayout(); 6716 LLVMContext &C = *DAG.getContext(); 6717 std::vector<EVT> MemOps; 6718 bool DstAlignCanChange = false; 6719 MachineFunction &MF = DAG.getMachineFunction(); 6720 MachineFrameInfo &MFI = MF.getFrameInfo(); 6721 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6722 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6723 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6724 DstAlignCanChange = true; 6725 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6726 if (!SrcAlign || Alignment > *SrcAlign) 6727 SrcAlign = Alignment; 6728 assert(SrcAlign && "SrcAlign must be set"); 6729 ConstantDataArraySlice Slice; 6730 // If marked as volatile, perform a copy even when marked as constant. 6731 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6732 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6733 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6734 const MemOp Op = isZeroConstant 6735 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6736 /*IsZeroMemset*/ true, isVol) 6737 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6738 *SrcAlign, isVol, CopyFromConstant); 6739 if (!TLI.findOptimalMemOpLowering( 6740 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6741 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6742 return SDValue(); 6743 6744 if (DstAlignCanChange) { 6745 Type *Ty = MemOps[0].getTypeForEVT(C); 6746 Align NewAlign = DL.getABITypeAlign(Ty); 6747 6748 // Don't promote to an alignment that would require dynamic stack 6749 // realignment. 6750 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6751 if (!TRI->hasStackRealignment(MF)) 6752 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6753 NewAlign = NewAlign.previous(); 6754 6755 if (NewAlign > Alignment) { 6756 // Give the stack frame object a larger alignment if needed. 6757 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6758 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6759 Alignment = NewAlign; 6760 } 6761 } 6762 6763 // Prepare AAInfo for loads/stores after lowering this memcpy. 6764 AAMDNodes NewAAInfo = AAInfo; 6765 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6766 6767 MachineMemOperand::Flags MMOFlags = 6768 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6769 SmallVector<SDValue, 16> OutLoadChains; 6770 SmallVector<SDValue, 16> OutStoreChains; 6771 SmallVector<SDValue, 32> OutChains; 6772 unsigned NumMemOps = MemOps.size(); 6773 uint64_t SrcOff = 0, DstOff = 0; 6774 for (unsigned i = 0; i != NumMemOps; ++i) { 6775 EVT VT = MemOps[i]; 6776 unsigned VTSize = VT.getSizeInBits() / 8; 6777 SDValue Value, Store; 6778 6779 if (VTSize > Size) { 6780 // Issuing an unaligned load / store pair that overlaps with the previous 6781 // pair. Adjust the offset accordingly. 6782 assert(i == NumMemOps-1 && i != 0); 6783 SrcOff -= VTSize - Size; 6784 DstOff -= VTSize - Size; 6785 } 6786 6787 if (CopyFromConstant && 6788 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6789 // It's unlikely a store of a vector immediate can be done in a single 6790 // instruction. It would require a load from a constantpool first. 6791 // We only handle zero vectors here. 6792 // FIXME: Handle other cases where store of vector immediate is done in 6793 // a single instruction. 6794 ConstantDataArraySlice SubSlice; 6795 if (SrcOff < Slice.Length) { 6796 SubSlice = Slice; 6797 SubSlice.move(SrcOff); 6798 } else { 6799 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6800 SubSlice.Array = nullptr; 6801 SubSlice.Offset = 0; 6802 SubSlice.Length = VTSize; 6803 } 6804 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6805 if (Value.getNode()) { 6806 Store = DAG.getStore( 6807 Chain, dl, Value, 6808 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6809 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6810 OutChains.push_back(Store); 6811 } 6812 } 6813 6814 if (!Store.getNode()) { 6815 // The type might not be legal for the target. This should only happen 6816 // if the type is smaller than a legal type, as on PPC, so the right 6817 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6818 // to Load/Store if NVT==VT. 6819 // FIXME does the case above also need this? 6820 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6821 assert(NVT.bitsGE(VT)); 6822 6823 bool isDereferenceable = 6824 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6825 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6826 if (isDereferenceable) 6827 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6828 6829 Value = DAG.getExtLoad( 6830 ISD::EXTLOAD, dl, NVT, Chain, 6831 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6832 SrcPtrInfo.getWithOffset(SrcOff), VT, 6833 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6834 OutLoadChains.push_back(Value.getValue(1)); 6835 6836 Store = DAG.getTruncStore( 6837 Chain, dl, Value, 6838 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6839 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6840 OutStoreChains.push_back(Store); 6841 } 6842 SrcOff += VTSize; 6843 DstOff += VTSize; 6844 Size -= VTSize; 6845 } 6846 6847 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6848 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6849 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6850 6851 if (NumLdStInMemcpy) { 6852 // It may be that memcpy might be converted to memset if it's memcpy 6853 // of constants. In such a case, we won't have loads and stores, but 6854 // just stores. In the absence of loads, there is nothing to gang up. 6855 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6856 // If target does not care, just leave as it. 6857 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6858 OutChains.push_back(OutLoadChains[i]); 6859 OutChains.push_back(OutStoreChains[i]); 6860 } 6861 } else { 6862 // Ld/St less than/equal limit set by target. 6863 if (NumLdStInMemcpy <= GluedLdStLimit) { 6864 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6865 NumLdStInMemcpy, OutLoadChains, 6866 OutStoreChains); 6867 } else { 6868 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6869 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6870 unsigned GlueIter = 0; 6871 6872 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6873 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6874 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6875 6876 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6877 OutLoadChains, OutStoreChains); 6878 GlueIter += GluedLdStLimit; 6879 } 6880 6881 // Residual ld/st. 6882 if (RemainingLdStInMemcpy) { 6883 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6884 RemainingLdStInMemcpy, OutLoadChains, 6885 OutStoreChains); 6886 } 6887 } 6888 } 6889 } 6890 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6891 } 6892 6893 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6894 SDValue Chain, SDValue Dst, SDValue Src, 6895 uint64_t Size, Align Alignment, 6896 bool isVol, bool AlwaysInline, 6897 MachinePointerInfo DstPtrInfo, 6898 MachinePointerInfo SrcPtrInfo, 6899 const AAMDNodes &AAInfo) { 6900 // Turn a memmove of undef to nop. 6901 // FIXME: We need to honor volatile even is Src is undef. 6902 if (Src.isUndef()) 6903 return Chain; 6904 6905 // Expand memmove to a series of load and store ops if the size operand falls 6906 // below a certain threshold. 6907 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6908 const DataLayout &DL = DAG.getDataLayout(); 6909 LLVMContext &C = *DAG.getContext(); 6910 std::vector<EVT> MemOps; 6911 bool DstAlignCanChange = false; 6912 MachineFunction &MF = DAG.getMachineFunction(); 6913 MachineFrameInfo &MFI = MF.getFrameInfo(); 6914 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6915 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6916 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6917 DstAlignCanChange = true; 6918 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6919 if (!SrcAlign || Alignment > *SrcAlign) 6920 SrcAlign = Alignment; 6921 assert(SrcAlign && "SrcAlign must be set"); 6922 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6923 if (!TLI.findOptimalMemOpLowering( 6924 MemOps, Limit, 6925 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6926 /*IsVolatile*/ true), 6927 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6928 MF.getFunction().getAttributes())) 6929 return SDValue(); 6930 6931 if (DstAlignCanChange) { 6932 Type *Ty = MemOps[0].getTypeForEVT(C); 6933 Align NewAlign = DL.getABITypeAlign(Ty); 6934 if (NewAlign > Alignment) { 6935 // Give the stack frame object a larger alignment if needed. 6936 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6937 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6938 Alignment = NewAlign; 6939 } 6940 } 6941 6942 // Prepare AAInfo for loads/stores after lowering this memmove. 6943 AAMDNodes NewAAInfo = AAInfo; 6944 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6945 6946 MachineMemOperand::Flags MMOFlags = 6947 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6948 uint64_t SrcOff = 0, DstOff = 0; 6949 SmallVector<SDValue, 8> LoadValues; 6950 SmallVector<SDValue, 8> LoadChains; 6951 SmallVector<SDValue, 8> OutChains; 6952 unsigned NumMemOps = MemOps.size(); 6953 for (unsigned i = 0; i < NumMemOps; i++) { 6954 EVT VT = MemOps[i]; 6955 unsigned VTSize = VT.getSizeInBits() / 8; 6956 SDValue Value; 6957 6958 bool isDereferenceable = 6959 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6960 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6961 if (isDereferenceable) 6962 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6963 6964 Value = DAG.getLoad( 6965 VT, dl, Chain, 6966 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6967 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6968 LoadValues.push_back(Value); 6969 LoadChains.push_back(Value.getValue(1)); 6970 SrcOff += VTSize; 6971 } 6972 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6973 OutChains.clear(); 6974 for (unsigned i = 0; i < NumMemOps; i++) { 6975 EVT VT = MemOps[i]; 6976 unsigned VTSize = VT.getSizeInBits() / 8; 6977 SDValue Store; 6978 6979 Store = DAG.getStore( 6980 Chain, dl, LoadValues[i], 6981 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6982 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6983 OutChains.push_back(Store); 6984 DstOff += VTSize; 6985 } 6986 6987 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6988 } 6989 6990 /// Lower the call to 'memset' intrinsic function into a series of store 6991 /// operations. 6992 /// 6993 /// \param DAG Selection DAG where lowered code is placed. 6994 /// \param dl Link to corresponding IR location. 6995 /// \param Chain Control flow dependency. 6996 /// \param Dst Pointer to destination memory location. 6997 /// \param Src Value of byte to write into the memory. 6998 /// \param Size Number of bytes to write. 6999 /// \param Alignment Alignment of the destination in bytes. 7000 /// \param isVol True if destination is volatile. 7001 /// \param AlwaysInline Makes sure no function call is generated. 7002 /// \param DstPtrInfo IR information on the memory pointer. 7003 /// \returns New head in the control flow, if lowering was successful, empty 7004 /// SDValue otherwise. 7005 /// 7006 /// The function tries to replace 'llvm.memset' intrinsic with several store 7007 /// operations and value calculation code. This is usually profitable for small 7008 /// memory size or when the semantic requires inlining. 7009 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 7010 SDValue Chain, SDValue Dst, SDValue Src, 7011 uint64_t Size, Align Alignment, bool isVol, 7012 bool AlwaysInline, MachinePointerInfo DstPtrInfo, 7013 const AAMDNodes &AAInfo) { 7014 // Turn a memset of undef to nop. 7015 // FIXME: We need to honor volatile even is Src is undef. 7016 if (Src.isUndef()) 7017 return Chain; 7018 7019 // Expand memset to a series of load/store ops if the size operand 7020 // falls below a certain threshold. 7021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7022 std::vector<EVT> MemOps; 7023 bool DstAlignCanChange = false; 7024 MachineFunction &MF = DAG.getMachineFunction(); 7025 MachineFrameInfo &MFI = MF.getFrameInfo(); 7026 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7027 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7028 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7029 DstAlignCanChange = true; 7030 bool IsZeroVal = 7031 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 7032 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize); 7033 7034 if (!TLI.findOptimalMemOpLowering( 7035 MemOps, Limit, 7036 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 7037 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 7038 return SDValue(); 7039 7040 if (DstAlignCanChange) { 7041 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 7042 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 7043 if (NewAlign > Alignment) { 7044 // Give the stack frame object a larger alignment if needed. 7045 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7046 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7047 Alignment = NewAlign; 7048 } 7049 } 7050 7051 SmallVector<SDValue, 8> OutChains; 7052 uint64_t DstOff = 0; 7053 unsigned NumMemOps = MemOps.size(); 7054 7055 // Find the largest store and generate the bit pattern for it. 7056 EVT LargestVT = MemOps[0]; 7057 for (unsigned i = 1; i < NumMemOps; i++) 7058 if (MemOps[i].bitsGT(LargestVT)) 7059 LargestVT = MemOps[i]; 7060 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 7061 7062 // Prepare AAInfo for loads/stores after lowering this memset. 7063 AAMDNodes NewAAInfo = AAInfo; 7064 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7065 7066 for (unsigned i = 0; i < NumMemOps; i++) { 7067 EVT VT = MemOps[i]; 7068 unsigned VTSize = VT.getSizeInBits() / 8; 7069 if (VTSize > Size) { 7070 // Issuing an unaligned load / store pair that overlaps with the previous 7071 // pair. Adjust the offset accordingly. 7072 assert(i == NumMemOps-1 && i != 0); 7073 DstOff -= VTSize - Size; 7074 } 7075 7076 // If this store is smaller than the largest store see whether we can get 7077 // the smaller value for free with a truncate. 7078 SDValue Value = MemSetValue; 7079 if (VT.bitsLT(LargestVT)) { 7080 if (!LargestVT.isVector() && !VT.isVector() && 7081 TLI.isTruncateFree(LargestVT, VT)) 7082 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7083 else 7084 Value = getMemsetValue(Src, VT, DAG, dl); 7085 } 7086 assert(Value.getValueType() == VT && "Value with wrong type."); 7087 SDValue Store = DAG.getStore( 7088 Chain, dl, Value, 7089 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7090 DstPtrInfo.getWithOffset(DstOff), Alignment, 7091 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7092 NewAAInfo); 7093 OutChains.push_back(Store); 7094 DstOff += VT.getSizeInBits() / 8; 7095 Size -= VTSize; 7096 } 7097 7098 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7099 } 7100 7101 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7102 unsigned AS) { 7103 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7104 // pointer operands can be losslessly bitcasted to pointers of address space 0 7105 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7106 report_fatal_error("cannot lower memory intrinsic in address space " + 7107 Twine(AS)); 7108 } 7109 } 7110 7111 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7112 SDValue Src, SDValue Size, Align Alignment, 7113 bool isVol, bool AlwaysInline, bool isTailCall, 7114 MachinePointerInfo DstPtrInfo, 7115 MachinePointerInfo SrcPtrInfo, 7116 const AAMDNodes &AAInfo) { 7117 // Check to see if we should lower the memcpy to loads and stores first. 7118 // For cases within the target-specified limits, this is the best choice. 7119 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7120 if (ConstantSize) { 7121 // Memcpy with size zero? Just return the original chain. 7122 if (ConstantSize->isZero()) 7123 return Chain; 7124 7125 SDValue Result = getMemcpyLoadsAndStores( 7126 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7127 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7128 if (Result.getNode()) 7129 return Result; 7130 } 7131 7132 // Then check to see if we should lower the memcpy with target-specific 7133 // code. If the target chooses to do this, this is the next best. 7134 if (TSI) { 7135 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7136 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7137 DstPtrInfo, SrcPtrInfo); 7138 if (Result.getNode()) 7139 return Result; 7140 } 7141 7142 // If we really need inline code and the target declined to provide it, 7143 // use a (potentially long) sequence of loads and stores. 7144 if (AlwaysInline) { 7145 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7146 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 7147 ConstantSize->getZExtValue(), Alignment, 7148 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 7149 } 7150 7151 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7152 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7153 7154 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7155 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7156 // respect volatile, so they may do things like read or write memory 7157 // beyond the given memory regions. But fixing this isn't easy, and most 7158 // people don't care. 7159 7160 // Emit a library call. 7161 TargetLowering::ArgListTy Args; 7162 TargetLowering::ArgListEntry Entry; 7163 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7164 Entry.Node = Dst; Args.push_back(Entry); 7165 Entry.Node = Src; Args.push_back(Entry); 7166 7167 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7168 Entry.Node = Size; Args.push_back(Entry); 7169 // FIXME: pass in SDLoc 7170 TargetLowering::CallLoweringInfo CLI(*this); 7171 CLI.setDebugLoc(dl) 7172 .setChain(Chain) 7173 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7174 Dst.getValueType().getTypeForEVT(*getContext()), 7175 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7176 TLI->getPointerTy(getDataLayout())), 7177 std::move(Args)) 7178 .setDiscardResult() 7179 .setTailCall(isTailCall); 7180 7181 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7182 return CallResult.second; 7183 } 7184 7185 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7186 SDValue Dst, SDValue Src, SDValue Size, 7187 Type *SizeTy, unsigned ElemSz, 7188 bool isTailCall, 7189 MachinePointerInfo DstPtrInfo, 7190 MachinePointerInfo SrcPtrInfo) { 7191 // Emit a library call. 7192 TargetLowering::ArgListTy Args; 7193 TargetLowering::ArgListEntry Entry; 7194 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7195 Entry.Node = Dst; 7196 Args.push_back(Entry); 7197 7198 Entry.Node = Src; 7199 Args.push_back(Entry); 7200 7201 Entry.Ty = SizeTy; 7202 Entry.Node = Size; 7203 Args.push_back(Entry); 7204 7205 RTLIB::Libcall LibraryCall = 7206 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7207 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7208 report_fatal_error("Unsupported element size"); 7209 7210 TargetLowering::CallLoweringInfo CLI(*this); 7211 CLI.setDebugLoc(dl) 7212 .setChain(Chain) 7213 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7214 Type::getVoidTy(*getContext()), 7215 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7216 TLI->getPointerTy(getDataLayout())), 7217 std::move(Args)) 7218 .setDiscardResult() 7219 .setTailCall(isTailCall); 7220 7221 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7222 return CallResult.second; 7223 } 7224 7225 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7226 SDValue Src, SDValue Size, Align Alignment, 7227 bool isVol, bool isTailCall, 7228 MachinePointerInfo DstPtrInfo, 7229 MachinePointerInfo SrcPtrInfo, 7230 const AAMDNodes &AAInfo) { 7231 // Check to see if we should lower the memmove to loads and stores first. 7232 // For cases within the target-specified limits, this is the best choice. 7233 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7234 if (ConstantSize) { 7235 // Memmove with size zero? Just return the original chain. 7236 if (ConstantSize->isZero()) 7237 return Chain; 7238 7239 SDValue Result = getMemmoveLoadsAndStores( 7240 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7241 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7242 if (Result.getNode()) 7243 return Result; 7244 } 7245 7246 // Then check to see if we should lower the memmove with target-specific 7247 // code. If the target chooses to do this, this is the next best. 7248 if (TSI) { 7249 SDValue Result = 7250 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7251 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7252 if (Result.getNode()) 7253 return Result; 7254 } 7255 7256 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7257 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7258 7259 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7260 // not be safe. See memcpy above for more details. 7261 7262 // Emit a library call. 7263 TargetLowering::ArgListTy Args; 7264 TargetLowering::ArgListEntry Entry; 7265 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7266 Entry.Node = Dst; Args.push_back(Entry); 7267 Entry.Node = Src; Args.push_back(Entry); 7268 7269 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7270 Entry.Node = Size; Args.push_back(Entry); 7271 // FIXME: pass in SDLoc 7272 TargetLowering::CallLoweringInfo CLI(*this); 7273 CLI.setDebugLoc(dl) 7274 .setChain(Chain) 7275 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7276 Dst.getValueType().getTypeForEVT(*getContext()), 7277 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7278 TLI->getPointerTy(getDataLayout())), 7279 std::move(Args)) 7280 .setDiscardResult() 7281 .setTailCall(isTailCall); 7282 7283 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7284 return CallResult.second; 7285 } 7286 7287 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7288 SDValue Dst, SDValue Src, SDValue Size, 7289 Type *SizeTy, unsigned ElemSz, 7290 bool isTailCall, 7291 MachinePointerInfo DstPtrInfo, 7292 MachinePointerInfo SrcPtrInfo) { 7293 // Emit a library call. 7294 TargetLowering::ArgListTy Args; 7295 TargetLowering::ArgListEntry Entry; 7296 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7297 Entry.Node = Dst; 7298 Args.push_back(Entry); 7299 7300 Entry.Node = Src; 7301 Args.push_back(Entry); 7302 7303 Entry.Ty = SizeTy; 7304 Entry.Node = Size; 7305 Args.push_back(Entry); 7306 7307 RTLIB::Libcall LibraryCall = 7308 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7309 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7310 report_fatal_error("Unsupported element size"); 7311 7312 TargetLowering::CallLoweringInfo CLI(*this); 7313 CLI.setDebugLoc(dl) 7314 .setChain(Chain) 7315 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7316 Type::getVoidTy(*getContext()), 7317 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7318 TLI->getPointerTy(getDataLayout())), 7319 std::move(Args)) 7320 .setDiscardResult() 7321 .setTailCall(isTailCall); 7322 7323 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7324 return CallResult.second; 7325 } 7326 7327 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7328 SDValue Src, SDValue Size, Align Alignment, 7329 bool isVol, bool AlwaysInline, bool isTailCall, 7330 MachinePointerInfo DstPtrInfo, 7331 const AAMDNodes &AAInfo) { 7332 // Check to see if we should lower the memset to stores first. 7333 // For cases within the target-specified limits, this is the best choice. 7334 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7335 if (ConstantSize) { 7336 // Memset with size zero? Just return the original chain. 7337 if (ConstantSize->isZero()) 7338 return Chain; 7339 7340 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7341 ConstantSize->getZExtValue(), Alignment, 7342 isVol, false, DstPtrInfo, AAInfo); 7343 7344 if (Result.getNode()) 7345 return Result; 7346 } 7347 7348 // Then check to see if we should lower the memset with target-specific 7349 // code. If the target chooses to do this, this is the next best. 7350 if (TSI) { 7351 SDValue Result = TSI->EmitTargetCodeForMemset( 7352 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo); 7353 if (Result.getNode()) 7354 return Result; 7355 } 7356 7357 // If we really need inline code and the target declined to provide it, 7358 // use a (potentially long) sequence of loads and stores. 7359 if (AlwaysInline) { 7360 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7361 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7362 ConstantSize->getZExtValue(), Alignment, 7363 isVol, true, DstPtrInfo, AAInfo); 7364 assert(Result && 7365 "getMemsetStores must return a valid sequence when AlwaysInline"); 7366 return Result; 7367 } 7368 7369 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7370 7371 // Emit a library call. 7372 auto &Ctx = *getContext(); 7373 const auto& DL = getDataLayout(); 7374 7375 TargetLowering::CallLoweringInfo CLI(*this); 7376 // FIXME: pass in SDLoc 7377 CLI.setDebugLoc(dl).setChain(Chain); 7378 7379 ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src); 7380 const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero(); 7381 const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO); 7382 7383 // Helper function to create an Entry from Node and Type. 7384 const auto CreateEntry = [](SDValue Node, Type *Ty) { 7385 TargetLowering::ArgListEntry Entry; 7386 Entry.Node = Node; 7387 Entry.Ty = Ty; 7388 return Entry; 7389 }; 7390 7391 // If zeroing out and bzero is present, use it. 7392 if (SrcIsZero && BzeroName) { 7393 TargetLowering::ArgListTy Args; 7394 Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx))); 7395 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 7396 CLI.setLibCallee( 7397 TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx), 7398 getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args)); 7399 } else { 7400 TargetLowering::ArgListTy Args; 7401 Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx))); 7402 Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx))); 7403 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 7404 CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7405 Dst.getValueType().getTypeForEVT(Ctx), 7406 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7407 TLI->getPointerTy(DL)), 7408 std::move(Args)); 7409 } 7410 7411 CLI.setDiscardResult().setTailCall(isTailCall); 7412 7413 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7414 return CallResult.second; 7415 } 7416 7417 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7418 SDValue Dst, SDValue Value, SDValue Size, 7419 Type *SizeTy, unsigned ElemSz, 7420 bool isTailCall, 7421 MachinePointerInfo DstPtrInfo) { 7422 // Emit a library call. 7423 TargetLowering::ArgListTy Args; 7424 TargetLowering::ArgListEntry Entry; 7425 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7426 Entry.Node = Dst; 7427 Args.push_back(Entry); 7428 7429 Entry.Ty = Type::getInt8Ty(*getContext()); 7430 Entry.Node = Value; 7431 Args.push_back(Entry); 7432 7433 Entry.Ty = SizeTy; 7434 Entry.Node = Size; 7435 Args.push_back(Entry); 7436 7437 RTLIB::Libcall LibraryCall = 7438 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7439 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7440 report_fatal_error("Unsupported element size"); 7441 7442 TargetLowering::CallLoweringInfo CLI(*this); 7443 CLI.setDebugLoc(dl) 7444 .setChain(Chain) 7445 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7446 Type::getVoidTy(*getContext()), 7447 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7448 TLI->getPointerTy(getDataLayout())), 7449 std::move(Args)) 7450 .setDiscardResult() 7451 .setTailCall(isTailCall); 7452 7453 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7454 return CallResult.second; 7455 } 7456 7457 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7458 SDVTList VTList, ArrayRef<SDValue> Ops, 7459 MachineMemOperand *MMO) { 7460 FoldingSetNodeID ID; 7461 ID.AddInteger(MemVT.getRawBits()); 7462 AddNodeIDNode(ID, Opcode, VTList, Ops); 7463 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7464 ID.AddInteger(MMO->getFlags()); 7465 void* IP = nullptr; 7466 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7467 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7468 return SDValue(E, 0); 7469 } 7470 7471 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7472 VTList, MemVT, MMO); 7473 createOperands(N, Ops); 7474 7475 CSEMap.InsertNode(N, IP); 7476 InsertNode(N); 7477 return SDValue(N, 0); 7478 } 7479 7480 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7481 EVT MemVT, SDVTList VTs, SDValue Chain, 7482 SDValue Ptr, SDValue Cmp, SDValue Swp, 7483 MachineMemOperand *MMO) { 7484 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7485 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7486 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7487 7488 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7489 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7490 } 7491 7492 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7493 SDValue Chain, SDValue Ptr, SDValue Val, 7494 MachineMemOperand *MMO) { 7495 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7496 Opcode == ISD::ATOMIC_LOAD_SUB || 7497 Opcode == ISD::ATOMIC_LOAD_AND || 7498 Opcode == ISD::ATOMIC_LOAD_CLR || 7499 Opcode == ISD::ATOMIC_LOAD_OR || 7500 Opcode == ISD::ATOMIC_LOAD_XOR || 7501 Opcode == ISD::ATOMIC_LOAD_NAND || 7502 Opcode == ISD::ATOMIC_LOAD_MIN || 7503 Opcode == ISD::ATOMIC_LOAD_MAX || 7504 Opcode == ISD::ATOMIC_LOAD_UMIN || 7505 Opcode == ISD::ATOMIC_LOAD_UMAX || 7506 Opcode == ISD::ATOMIC_LOAD_FADD || 7507 Opcode == ISD::ATOMIC_LOAD_FSUB || 7508 Opcode == ISD::ATOMIC_SWAP || 7509 Opcode == ISD::ATOMIC_STORE) && 7510 "Invalid Atomic Op"); 7511 7512 EVT VT = Val.getValueType(); 7513 7514 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7515 getVTList(VT, MVT::Other); 7516 SDValue Ops[] = {Chain, Ptr, Val}; 7517 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7518 } 7519 7520 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7521 EVT VT, SDValue Chain, SDValue Ptr, 7522 MachineMemOperand *MMO) { 7523 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7524 7525 SDVTList VTs = getVTList(VT, MVT::Other); 7526 SDValue Ops[] = {Chain, Ptr}; 7527 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7528 } 7529 7530 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7531 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7532 if (Ops.size() == 1) 7533 return Ops[0]; 7534 7535 SmallVector<EVT, 4> VTs; 7536 VTs.reserve(Ops.size()); 7537 for (const SDValue &Op : Ops) 7538 VTs.push_back(Op.getValueType()); 7539 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7540 } 7541 7542 SDValue SelectionDAG::getMemIntrinsicNode( 7543 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7544 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7545 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7546 if (!Size && MemVT.isScalableVector()) 7547 Size = MemoryLocation::UnknownSize; 7548 else if (!Size) 7549 Size = MemVT.getStoreSize(); 7550 7551 MachineFunction &MF = getMachineFunction(); 7552 MachineMemOperand *MMO = 7553 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7554 7555 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7556 } 7557 7558 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7559 SDVTList VTList, 7560 ArrayRef<SDValue> Ops, EVT MemVT, 7561 MachineMemOperand *MMO) { 7562 assert((Opcode == ISD::INTRINSIC_VOID || 7563 Opcode == ISD::INTRINSIC_W_CHAIN || 7564 Opcode == ISD::PREFETCH || 7565 ((int)Opcode <= std::numeric_limits<int>::max() && 7566 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7567 "Opcode is not a memory-accessing opcode!"); 7568 7569 // Memoize the node unless it returns a flag. 7570 MemIntrinsicSDNode *N; 7571 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7572 FoldingSetNodeID ID; 7573 AddNodeIDNode(ID, Opcode, VTList, Ops); 7574 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7575 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7576 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7577 ID.AddInteger(MMO->getFlags()); 7578 void *IP = nullptr; 7579 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7580 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7581 return SDValue(E, 0); 7582 } 7583 7584 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7585 VTList, MemVT, MMO); 7586 createOperands(N, Ops); 7587 7588 CSEMap.InsertNode(N, IP); 7589 } else { 7590 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7591 VTList, MemVT, MMO); 7592 createOperands(N, Ops); 7593 } 7594 InsertNode(N); 7595 SDValue V(N, 0); 7596 NewSDValueDbgMsg(V, "Creating new node: ", this); 7597 return V; 7598 } 7599 7600 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7601 SDValue Chain, int FrameIndex, 7602 int64_t Size, int64_t Offset) { 7603 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7604 const auto VTs = getVTList(MVT::Other); 7605 SDValue Ops[2] = { 7606 Chain, 7607 getFrameIndex(FrameIndex, 7608 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7609 true)}; 7610 7611 FoldingSetNodeID ID; 7612 AddNodeIDNode(ID, Opcode, VTs, Ops); 7613 ID.AddInteger(FrameIndex); 7614 ID.AddInteger(Size); 7615 ID.AddInteger(Offset); 7616 void *IP = nullptr; 7617 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7618 return SDValue(E, 0); 7619 7620 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7621 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7622 createOperands(N, Ops); 7623 CSEMap.InsertNode(N, IP); 7624 InsertNode(N); 7625 SDValue V(N, 0); 7626 NewSDValueDbgMsg(V, "Creating new node: ", this); 7627 return V; 7628 } 7629 7630 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7631 uint64_t Guid, uint64_t Index, 7632 uint32_t Attr) { 7633 const unsigned Opcode = ISD::PSEUDO_PROBE; 7634 const auto VTs = getVTList(MVT::Other); 7635 SDValue Ops[] = {Chain}; 7636 FoldingSetNodeID ID; 7637 AddNodeIDNode(ID, Opcode, VTs, Ops); 7638 ID.AddInteger(Guid); 7639 ID.AddInteger(Index); 7640 void *IP = nullptr; 7641 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7642 return SDValue(E, 0); 7643 7644 auto *N = newSDNode<PseudoProbeSDNode>( 7645 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7646 createOperands(N, Ops); 7647 CSEMap.InsertNode(N, IP); 7648 InsertNode(N); 7649 SDValue V(N, 0); 7650 NewSDValueDbgMsg(V, "Creating new node: ", this); 7651 return V; 7652 } 7653 7654 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7655 /// MachinePointerInfo record from it. This is particularly useful because the 7656 /// code generator has many cases where it doesn't bother passing in a 7657 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7658 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7659 SelectionDAG &DAG, SDValue Ptr, 7660 int64_t Offset = 0) { 7661 // If this is FI+Offset, we can model it. 7662 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7663 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7664 FI->getIndex(), Offset); 7665 7666 // If this is (FI+Offset1)+Offset2, we can model it. 7667 if (Ptr.getOpcode() != ISD::ADD || 7668 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7669 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7670 return Info; 7671 7672 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7673 return MachinePointerInfo::getFixedStack( 7674 DAG.getMachineFunction(), FI, 7675 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7676 } 7677 7678 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7679 /// MachinePointerInfo record from it. This is particularly useful because the 7680 /// code generator has many cases where it doesn't bother passing in a 7681 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7682 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7683 SelectionDAG &DAG, SDValue Ptr, 7684 SDValue OffsetOp) { 7685 // If the 'Offset' value isn't a constant, we can't handle this. 7686 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7687 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7688 if (OffsetOp.isUndef()) 7689 return InferPointerInfo(Info, DAG, Ptr); 7690 return Info; 7691 } 7692 7693 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7694 EVT VT, const SDLoc &dl, SDValue Chain, 7695 SDValue Ptr, SDValue Offset, 7696 MachinePointerInfo PtrInfo, EVT MemVT, 7697 Align Alignment, 7698 MachineMemOperand::Flags MMOFlags, 7699 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7700 assert(Chain.getValueType() == MVT::Other && 7701 "Invalid chain type"); 7702 7703 MMOFlags |= MachineMemOperand::MOLoad; 7704 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7705 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7706 // clients. 7707 if (PtrInfo.V.isNull()) 7708 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7709 7710 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7711 MachineFunction &MF = getMachineFunction(); 7712 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7713 Alignment, AAInfo, Ranges); 7714 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7715 } 7716 7717 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7718 EVT VT, const SDLoc &dl, SDValue Chain, 7719 SDValue Ptr, SDValue Offset, EVT MemVT, 7720 MachineMemOperand *MMO) { 7721 if (VT == MemVT) { 7722 ExtType = ISD::NON_EXTLOAD; 7723 } else if (ExtType == ISD::NON_EXTLOAD) { 7724 assert(VT == MemVT && "Non-extending load from different memory type!"); 7725 } else { 7726 // Extending load. 7727 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7728 "Should only be an extending load, not truncating!"); 7729 assert(VT.isInteger() == MemVT.isInteger() && 7730 "Cannot convert from FP to Int or Int -> FP!"); 7731 assert(VT.isVector() == MemVT.isVector() && 7732 "Cannot use an ext load to convert to or from a vector!"); 7733 assert((!VT.isVector() || 7734 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7735 "Cannot use an ext load to change the number of vector elements!"); 7736 } 7737 7738 bool Indexed = AM != ISD::UNINDEXED; 7739 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7740 7741 SDVTList VTs = Indexed ? 7742 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7743 SDValue Ops[] = { Chain, Ptr, Offset }; 7744 FoldingSetNodeID ID; 7745 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7746 ID.AddInteger(MemVT.getRawBits()); 7747 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7748 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7749 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7750 ID.AddInteger(MMO->getFlags()); 7751 void *IP = nullptr; 7752 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7753 cast<LoadSDNode>(E)->refineAlignment(MMO); 7754 return SDValue(E, 0); 7755 } 7756 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7757 ExtType, MemVT, MMO); 7758 createOperands(N, Ops); 7759 7760 CSEMap.InsertNode(N, IP); 7761 InsertNode(N); 7762 SDValue V(N, 0); 7763 NewSDValueDbgMsg(V, "Creating new node: ", this); 7764 return V; 7765 } 7766 7767 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7768 SDValue Ptr, MachinePointerInfo PtrInfo, 7769 MaybeAlign Alignment, 7770 MachineMemOperand::Flags MMOFlags, 7771 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7772 SDValue Undef = getUNDEF(Ptr.getValueType()); 7773 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7774 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7775 } 7776 7777 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7778 SDValue Ptr, MachineMemOperand *MMO) { 7779 SDValue Undef = getUNDEF(Ptr.getValueType()); 7780 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7781 VT, MMO); 7782 } 7783 7784 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7785 EVT VT, SDValue Chain, SDValue Ptr, 7786 MachinePointerInfo PtrInfo, EVT MemVT, 7787 MaybeAlign Alignment, 7788 MachineMemOperand::Flags MMOFlags, 7789 const AAMDNodes &AAInfo) { 7790 SDValue Undef = getUNDEF(Ptr.getValueType()); 7791 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7792 MemVT, Alignment, MMOFlags, AAInfo); 7793 } 7794 7795 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7796 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7797 MachineMemOperand *MMO) { 7798 SDValue Undef = getUNDEF(Ptr.getValueType()); 7799 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7800 MemVT, MMO); 7801 } 7802 7803 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7804 SDValue Base, SDValue Offset, 7805 ISD::MemIndexedMode AM) { 7806 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7807 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7808 // Don't propagate the invariant or dereferenceable flags. 7809 auto MMOFlags = 7810 LD->getMemOperand()->getFlags() & 7811 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7812 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7813 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7814 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7815 } 7816 7817 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7818 SDValue Ptr, MachinePointerInfo PtrInfo, 7819 Align Alignment, 7820 MachineMemOperand::Flags MMOFlags, 7821 const AAMDNodes &AAInfo) { 7822 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7823 7824 MMOFlags |= MachineMemOperand::MOStore; 7825 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7826 7827 if (PtrInfo.V.isNull()) 7828 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7829 7830 MachineFunction &MF = getMachineFunction(); 7831 uint64_t Size = 7832 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7833 MachineMemOperand *MMO = 7834 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7835 return getStore(Chain, dl, Val, Ptr, MMO); 7836 } 7837 7838 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7839 SDValue Ptr, MachineMemOperand *MMO) { 7840 assert(Chain.getValueType() == MVT::Other && 7841 "Invalid chain type"); 7842 EVT VT = Val.getValueType(); 7843 SDVTList VTs = getVTList(MVT::Other); 7844 SDValue Undef = getUNDEF(Ptr.getValueType()); 7845 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7846 FoldingSetNodeID ID; 7847 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7848 ID.AddInteger(VT.getRawBits()); 7849 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7850 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7851 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7852 ID.AddInteger(MMO->getFlags()); 7853 void *IP = nullptr; 7854 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7855 cast<StoreSDNode>(E)->refineAlignment(MMO); 7856 return SDValue(E, 0); 7857 } 7858 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7859 ISD::UNINDEXED, false, VT, MMO); 7860 createOperands(N, Ops); 7861 7862 CSEMap.InsertNode(N, IP); 7863 InsertNode(N); 7864 SDValue V(N, 0); 7865 NewSDValueDbgMsg(V, "Creating new node: ", this); 7866 return V; 7867 } 7868 7869 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7870 SDValue Ptr, MachinePointerInfo PtrInfo, 7871 EVT SVT, Align Alignment, 7872 MachineMemOperand::Flags MMOFlags, 7873 const AAMDNodes &AAInfo) { 7874 assert(Chain.getValueType() == MVT::Other && 7875 "Invalid chain type"); 7876 7877 MMOFlags |= MachineMemOperand::MOStore; 7878 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7879 7880 if (PtrInfo.V.isNull()) 7881 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7882 7883 MachineFunction &MF = getMachineFunction(); 7884 MachineMemOperand *MMO = MF.getMachineMemOperand( 7885 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7886 Alignment, AAInfo); 7887 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7888 } 7889 7890 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7891 SDValue Ptr, EVT SVT, 7892 MachineMemOperand *MMO) { 7893 EVT VT = Val.getValueType(); 7894 7895 assert(Chain.getValueType() == MVT::Other && 7896 "Invalid chain type"); 7897 if (VT == SVT) 7898 return getStore(Chain, dl, Val, Ptr, MMO); 7899 7900 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7901 "Should only be a truncating store, not extending!"); 7902 assert(VT.isInteger() == SVT.isInteger() && 7903 "Can't do FP-INT conversion!"); 7904 assert(VT.isVector() == SVT.isVector() && 7905 "Cannot use trunc store to convert to or from a vector!"); 7906 assert((!VT.isVector() || 7907 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7908 "Cannot use trunc store to change the number of vector elements!"); 7909 7910 SDVTList VTs = getVTList(MVT::Other); 7911 SDValue Undef = getUNDEF(Ptr.getValueType()); 7912 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7913 FoldingSetNodeID ID; 7914 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7915 ID.AddInteger(SVT.getRawBits()); 7916 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7917 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7918 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7919 ID.AddInteger(MMO->getFlags()); 7920 void *IP = nullptr; 7921 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7922 cast<StoreSDNode>(E)->refineAlignment(MMO); 7923 return SDValue(E, 0); 7924 } 7925 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7926 ISD::UNINDEXED, true, SVT, MMO); 7927 createOperands(N, Ops); 7928 7929 CSEMap.InsertNode(N, IP); 7930 InsertNode(N); 7931 SDValue V(N, 0); 7932 NewSDValueDbgMsg(V, "Creating new node: ", this); 7933 return V; 7934 } 7935 7936 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7937 SDValue Base, SDValue Offset, 7938 ISD::MemIndexedMode AM) { 7939 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7940 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7941 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7942 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7943 FoldingSetNodeID ID; 7944 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7945 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7946 ID.AddInteger(ST->getRawSubclassData()); 7947 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7948 ID.AddInteger(ST->getMemOperand()->getFlags()); 7949 void *IP = nullptr; 7950 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7951 return SDValue(E, 0); 7952 7953 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7954 ST->isTruncatingStore(), ST->getMemoryVT(), 7955 ST->getMemOperand()); 7956 createOperands(N, Ops); 7957 7958 CSEMap.InsertNode(N, IP); 7959 InsertNode(N); 7960 SDValue V(N, 0); 7961 NewSDValueDbgMsg(V, "Creating new node: ", this); 7962 return V; 7963 } 7964 7965 SDValue SelectionDAG::getLoadVP( 7966 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7967 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7968 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7969 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7970 const MDNode *Ranges, bool IsExpanding) { 7971 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7972 7973 MMOFlags |= MachineMemOperand::MOLoad; 7974 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7975 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7976 // clients. 7977 if (PtrInfo.V.isNull()) 7978 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7979 7980 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7981 MachineFunction &MF = getMachineFunction(); 7982 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7983 Alignment, AAInfo, Ranges); 7984 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7985 MMO, IsExpanding); 7986 } 7987 7988 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7989 ISD::LoadExtType ExtType, EVT VT, 7990 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7991 SDValue Offset, SDValue Mask, SDValue EVL, 7992 EVT MemVT, MachineMemOperand *MMO, 7993 bool IsExpanding) { 7994 bool Indexed = AM != ISD::UNINDEXED; 7995 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7996 7997 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7998 : getVTList(VT, MVT::Other); 7999 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 8000 FoldingSetNodeID ID; 8001 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 8002 ID.AddInteger(VT.getRawBits()); 8003 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 8004 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8005 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8006 ID.AddInteger(MMO->getFlags()); 8007 void *IP = nullptr; 8008 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8009 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 8010 return SDValue(E, 0); 8011 } 8012 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8013 ExtType, IsExpanding, MemVT, MMO); 8014 createOperands(N, Ops); 8015 8016 CSEMap.InsertNode(N, IP); 8017 InsertNode(N); 8018 SDValue V(N, 0); 8019 NewSDValueDbgMsg(V, "Creating new node: ", this); 8020 return V; 8021 } 8022 8023 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8024 SDValue Ptr, SDValue Mask, SDValue EVL, 8025 MachinePointerInfo PtrInfo, 8026 MaybeAlign Alignment, 8027 MachineMemOperand::Flags MMOFlags, 8028 const AAMDNodes &AAInfo, const MDNode *Ranges, 8029 bool IsExpanding) { 8030 SDValue Undef = getUNDEF(Ptr.getValueType()); 8031 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8032 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 8033 IsExpanding); 8034 } 8035 8036 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8037 SDValue Ptr, SDValue Mask, SDValue EVL, 8038 MachineMemOperand *MMO, bool IsExpanding) { 8039 SDValue Undef = getUNDEF(Ptr.getValueType()); 8040 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8041 Mask, EVL, VT, MMO, IsExpanding); 8042 } 8043 8044 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8045 EVT VT, SDValue Chain, SDValue Ptr, 8046 SDValue Mask, SDValue EVL, 8047 MachinePointerInfo PtrInfo, EVT MemVT, 8048 MaybeAlign Alignment, 8049 MachineMemOperand::Flags MMOFlags, 8050 const AAMDNodes &AAInfo, bool IsExpanding) { 8051 SDValue Undef = getUNDEF(Ptr.getValueType()); 8052 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8053 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 8054 IsExpanding); 8055 } 8056 8057 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8058 EVT VT, SDValue Chain, SDValue Ptr, 8059 SDValue Mask, SDValue EVL, EVT MemVT, 8060 MachineMemOperand *MMO, bool IsExpanding) { 8061 SDValue Undef = getUNDEF(Ptr.getValueType()); 8062 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8063 EVL, MemVT, MMO, IsExpanding); 8064 } 8065 8066 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 8067 SDValue Base, SDValue Offset, 8068 ISD::MemIndexedMode AM) { 8069 auto *LD = cast<VPLoadSDNode>(OrigLoad); 8070 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8071 // Don't propagate the invariant or dereferenceable flags. 8072 auto MMOFlags = 8073 LD->getMemOperand()->getFlags() & 8074 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8075 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8076 LD->getChain(), Base, Offset, LD->getMask(), 8077 LD->getVectorLength(), LD->getPointerInfo(), 8078 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 8079 nullptr, LD->isExpandingLoad()); 8080 } 8081 8082 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 8083 SDValue Ptr, SDValue Offset, SDValue Mask, 8084 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 8085 ISD::MemIndexedMode AM, bool IsTruncating, 8086 bool IsCompressing) { 8087 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8088 bool Indexed = AM != ISD::UNINDEXED; 8089 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8090 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8091 : getVTList(MVT::Other); 8092 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 8093 FoldingSetNodeID ID; 8094 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8095 ID.AddInteger(MemVT.getRawBits()); 8096 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8097 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8098 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8099 ID.AddInteger(MMO->getFlags()); 8100 void *IP = nullptr; 8101 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8102 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8103 return SDValue(E, 0); 8104 } 8105 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8106 IsTruncating, IsCompressing, MemVT, MMO); 8107 createOperands(N, Ops); 8108 8109 CSEMap.InsertNode(N, IP); 8110 InsertNode(N); 8111 SDValue V(N, 0); 8112 NewSDValueDbgMsg(V, "Creating new node: ", this); 8113 return V; 8114 } 8115 8116 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8117 SDValue Val, SDValue Ptr, SDValue Mask, 8118 SDValue EVL, MachinePointerInfo PtrInfo, 8119 EVT SVT, Align Alignment, 8120 MachineMemOperand::Flags MMOFlags, 8121 const AAMDNodes &AAInfo, 8122 bool IsCompressing) { 8123 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8124 8125 MMOFlags |= MachineMemOperand::MOStore; 8126 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8127 8128 if (PtrInfo.V.isNull()) 8129 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8130 8131 MachineFunction &MF = getMachineFunction(); 8132 MachineMemOperand *MMO = MF.getMachineMemOperand( 8133 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8134 Alignment, AAInfo); 8135 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8136 IsCompressing); 8137 } 8138 8139 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8140 SDValue Val, SDValue Ptr, SDValue Mask, 8141 SDValue EVL, EVT SVT, 8142 MachineMemOperand *MMO, 8143 bool IsCompressing) { 8144 EVT VT = Val.getValueType(); 8145 8146 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8147 if (VT == SVT) 8148 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8149 EVL, VT, MMO, ISD::UNINDEXED, 8150 /*IsTruncating*/ false, IsCompressing); 8151 8152 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8153 "Should only be a truncating store, not extending!"); 8154 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8155 assert(VT.isVector() == SVT.isVector() && 8156 "Cannot use trunc store to convert to or from a vector!"); 8157 assert((!VT.isVector() || 8158 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8159 "Cannot use trunc store to change the number of vector elements!"); 8160 8161 SDVTList VTs = getVTList(MVT::Other); 8162 SDValue Undef = getUNDEF(Ptr.getValueType()); 8163 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8164 FoldingSetNodeID ID; 8165 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8166 ID.AddInteger(SVT.getRawBits()); 8167 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8168 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8169 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8170 ID.AddInteger(MMO->getFlags()); 8171 void *IP = nullptr; 8172 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8173 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8174 return SDValue(E, 0); 8175 } 8176 auto *N = 8177 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8178 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8179 createOperands(N, Ops); 8180 8181 CSEMap.InsertNode(N, IP); 8182 InsertNode(N); 8183 SDValue V(N, 0); 8184 NewSDValueDbgMsg(V, "Creating new node: ", this); 8185 return V; 8186 } 8187 8188 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8189 SDValue Base, SDValue Offset, 8190 ISD::MemIndexedMode AM) { 8191 auto *ST = cast<VPStoreSDNode>(OrigStore); 8192 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8193 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8194 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8195 Offset, ST->getMask(), ST->getVectorLength()}; 8196 FoldingSetNodeID ID; 8197 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8198 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8199 ID.AddInteger(ST->getRawSubclassData()); 8200 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8201 ID.AddInteger(ST->getMemOperand()->getFlags()); 8202 void *IP = nullptr; 8203 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8204 return SDValue(E, 0); 8205 8206 auto *N = newSDNode<VPStoreSDNode>( 8207 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8208 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8209 createOperands(N, Ops); 8210 8211 CSEMap.InsertNode(N, IP); 8212 InsertNode(N); 8213 SDValue V(N, 0); 8214 NewSDValueDbgMsg(V, "Creating new node: ", this); 8215 return V; 8216 } 8217 8218 SDValue SelectionDAG::getStridedLoadVP( 8219 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8220 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8221 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8222 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8223 const MDNode *Ranges, bool IsExpanding) { 8224 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8225 8226 MMOFlags |= MachineMemOperand::MOLoad; 8227 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8228 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8229 // clients. 8230 if (PtrInfo.V.isNull()) 8231 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8232 8233 uint64_t Size = MemoryLocation::UnknownSize; 8234 MachineFunction &MF = getMachineFunction(); 8235 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8236 Alignment, AAInfo, Ranges); 8237 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8238 EVL, MemVT, MMO, IsExpanding); 8239 } 8240 8241 SDValue SelectionDAG::getStridedLoadVP( 8242 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8243 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8244 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8245 bool Indexed = AM != ISD::UNINDEXED; 8246 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8247 8248 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8249 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8250 : getVTList(VT, MVT::Other); 8251 FoldingSetNodeID ID; 8252 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8253 ID.AddInteger(VT.getRawBits()); 8254 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8255 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8256 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8257 8258 void *IP = nullptr; 8259 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8260 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8261 return SDValue(E, 0); 8262 } 8263 8264 auto *N = 8265 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8266 ExtType, IsExpanding, MemVT, MMO); 8267 createOperands(N, Ops); 8268 CSEMap.InsertNode(N, IP); 8269 InsertNode(N); 8270 SDValue V(N, 0); 8271 NewSDValueDbgMsg(V, "Creating new node: ", this); 8272 return V; 8273 } 8274 8275 SDValue SelectionDAG::getStridedLoadVP( 8276 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8277 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8278 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8279 const MDNode *Ranges, bool IsExpanding) { 8280 SDValue Undef = getUNDEF(Ptr.getValueType()); 8281 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8282 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8283 MMOFlags, AAInfo, Ranges, IsExpanding); 8284 } 8285 8286 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8287 SDValue Ptr, SDValue Stride, 8288 SDValue Mask, SDValue EVL, 8289 MachineMemOperand *MMO, 8290 bool IsExpanding) { 8291 SDValue Undef = getUNDEF(Ptr.getValueType()); 8292 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8293 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8294 } 8295 8296 SDValue SelectionDAG::getExtStridedLoadVP( 8297 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8298 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8299 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8300 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8301 bool IsExpanding) { 8302 SDValue Undef = getUNDEF(Ptr.getValueType()); 8303 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8304 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8305 MMOFlags, AAInfo, nullptr, IsExpanding); 8306 } 8307 8308 SDValue SelectionDAG::getExtStridedLoadVP( 8309 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8310 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8311 MachineMemOperand *MMO, bool IsExpanding) { 8312 SDValue Undef = getUNDEF(Ptr.getValueType()); 8313 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8314 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8315 } 8316 8317 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8318 SDValue Base, SDValue Offset, 8319 ISD::MemIndexedMode AM) { 8320 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8321 assert(SLD->getOffset().isUndef() && 8322 "Strided load is already a indexed load!"); 8323 // Don't propagate the invariant or dereferenceable flags. 8324 auto MMOFlags = 8325 SLD->getMemOperand()->getFlags() & 8326 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8327 return getStridedLoadVP( 8328 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8329 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8330 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8331 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8332 } 8333 8334 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8335 SDValue Val, SDValue Ptr, 8336 SDValue Offset, SDValue Stride, 8337 SDValue Mask, SDValue EVL, EVT MemVT, 8338 MachineMemOperand *MMO, 8339 ISD::MemIndexedMode AM, 8340 bool IsTruncating, bool IsCompressing) { 8341 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8342 bool Indexed = AM != ISD::UNINDEXED; 8343 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8344 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8345 : getVTList(MVT::Other); 8346 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8347 FoldingSetNodeID ID; 8348 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8349 ID.AddInteger(MemVT.getRawBits()); 8350 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8351 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8352 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8353 void *IP = nullptr; 8354 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8355 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8356 return SDValue(E, 0); 8357 } 8358 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8359 VTs, AM, IsTruncating, 8360 IsCompressing, MemVT, MMO); 8361 createOperands(N, Ops); 8362 8363 CSEMap.InsertNode(N, IP); 8364 InsertNode(N); 8365 SDValue V(N, 0); 8366 NewSDValueDbgMsg(V, "Creating new node: ", this); 8367 return V; 8368 } 8369 8370 SDValue SelectionDAG::getTruncStridedStoreVP( 8371 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8372 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8373 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8374 bool IsCompressing) { 8375 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8376 8377 MMOFlags |= MachineMemOperand::MOStore; 8378 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8379 8380 if (PtrInfo.V.isNull()) 8381 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8382 8383 MachineFunction &MF = getMachineFunction(); 8384 MachineMemOperand *MMO = MF.getMachineMemOperand( 8385 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8386 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8387 MMO, IsCompressing); 8388 } 8389 8390 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8391 SDValue Val, SDValue Ptr, 8392 SDValue Stride, SDValue Mask, 8393 SDValue EVL, EVT SVT, 8394 MachineMemOperand *MMO, 8395 bool IsCompressing) { 8396 EVT VT = Val.getValueType(); 8397 8398 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8399 if (VT == SVT) 8400 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8401 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8402 /*IsTruncating*/ false, IsCompressing); 8403 8404 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8405 "Should only be a truncating store, not extending!"); 8406 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8407 assert(VT.isVector() == SVT.isVector() && 8408 "Cannot use trunc store to convert to or from a vector!"); 8409 assert((!VT.isVector() || 8410 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8411 "Cannot use trunc store to change the number of vector elements!"); 8412 8413 SDVTList VTs = getVTList(MVT::Other); 8414 SDValue Undef = getUNDEF(Ptr.getValueType()); 8415 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8416 FoldingSetNodeID ID; 8417 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8418 ID.AddInteger(SVT.getRawBits()); 8419 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8420 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8421 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8422 void *IP = nullptr; 8423 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8424 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8425 return SDValue(E, 0); 8426 } 8427 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8428 VTs, ISD::UNINDEXED, true, 8429 IsCompressing, SVT, MMO); 8430 createOperands(N, Ops); 8431 8432 CSEMap.InsertNode(N, IP); 8433 InsertNode(N); 8434 SDValue V(N, 0); 8435 NewSDValueDbgMsg(V, "Creating new node: ", this); 8436 return V; 8437 } 8438 8439 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 8440 const SDLoc &DL, SDValue Base, 8441 SDValue Offset, 8442 ISD::MemIndexedMode AM) { 8443 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 8444 assert(SST->getOffset().isUndef() && 8445 "Strided store is already an indexed store!"); 8446 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8447 SDValue Ops[] = { 8448 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 8449 SST->getMask(), SST->getVectorLength()}; 8450 FoldingSetNodeID ID; 8451 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8452 ID.AddInteger(SST->getMemoryVT().getRawBits()); 8453 ID.AddInteger(SST->getRawSubclassData()); 8454 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 8455 void *IP = nullptr; 8456 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8457 return SDValue(E, 0); 8458 8459 auto *N = newSDNode<VPStridedStoreSDNode>( 8460 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 8461 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 8462 createOperands(N, Ops); 8463 8464 CSEMap.InsertNode(N, IP); 8465 InsertNode(N); 8466 SDValue V(N, 0); 8467 NewSDValueDbgMsg(V, "Creating new node: ", this); 8468 return V; 8469 } 8470 8471 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8472 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8473 ISD::MemIndexType IndexType) { 8474 assert(Ops.size() == 6 && "Incompatible number of operands"); 8475 8476 FoldingSetNodeID ID; 8477 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8478 ID.AddInteger(VT.getRawBits()); 8479 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8480 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8481 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8482 ID.AddInteger(MMO->getFlags()); 8483 void *IP = nullptr; 8484 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8485 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8486 return SDValue(E, 0); 8487 } 8488 8489 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8490 VT, MMO, IndexType); 8491 createOperands(N, Ops); 8492 8493 assert(N->getMask().getValueType().getVectorElementCount() == 8494 N->getValueType(0).getVectorElementCount() && 8495 "Vector width mismatch between mask and data"); 8496 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8497 N->getValueType(0).getVectorElementCount().isScalable() && 8498 "Scalable flags of index and data do not match"); 8499 assert(ElementCount::isKnownGE( 8500 N->getIndex().getValueType().getVectorElementCount(), 8501 N->getValueType(0).getVectorElementCount()) && 8502 "Vector width mismatch between index and data"); 8503 assert(isa<ConstantSDNode>(N->getScale()) && 8504 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8505 "Scale should be a constant power of 2"); 8506 8507 CSEMap.InsertNode(N, IP); 8508 InsertNode(N); 8509 SDValue V(N, 0); 8510 NewSDValueDbgMsg(V, "Creating new node: ", this); 8511 return V; 8512 } 8513 8514 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8515 ArrayRef<SDValue> Ops, 8516 MachineMemOperand *MMO, 8517 ISD::MemIndexType IndexType) { 8518 assert(Ops.size() == 7 && "Incompatible number of operands"); 8519 8520 FoldingSetNodeID ID; 8521 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8522 ID.AddInteger(VT.getRawBits()); 8523 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8524 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8525 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8526 ID.AddInteger(MMO->getFlags()); 8527 void *IP = nullptr; 8528 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8529 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8530 return SDValue(E, 0); 8531 } 8532 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8533 VT, MMO, IndexType); 8534 createOperands(N, Ops); 8535 8536 assert(N->getMask().getValueType().getVectorElementCount() == 8537 N->getValue().getValueType().getVectorElementCount() && 8538 "Vector width mismatch between mask and data"); 8539 assert( 8540 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8541 N->getValue().getValueType().getVectorElementCount().isScalable() && 8542 "Scalable flags of index and data do not match"); 8543 assert(ElementCount::isKnownGE( 8544 N->getIndex().getValueType().getVectorElementCount(), 8545 N->getValue().getValueType().getVectorElementCount()) && 8546 "Vector width mismatch between index and data"); 8547 assert(isa<ConstantSDNode>(N->getScale()) && 8548 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8549 "Scale should be a constant power of 2"); 8550 8551 CSEMap.InsertNode(N, IP); 8552 InsertNode(N); 8553 SDValue V(N, 0); 8554 NewSDValueDbgMsg(V, "Creating new node: ", this); 8555 return V; 8556 } 8557 8558 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8559 SDValue Base, SDValue Offset, SDValue Mask, 8560 SDValue PassThru, EVT MemVT, 8561 MachineMemOperand *MMO, 8562 ISD::MemIndexedMode AM, 8563 ISD::LoadExtType ExtTy, bool isExpanding) { 8564 bool Indexed = AM != ISD::UNINDEXED; 8565 assert((Indexed || Offset.isUndef()) && 8566 "Unindexed masked load with an offset!"); 8567 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8568 : getVTList(VT, MVT::Other); 8569 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8570 FoldingSetNodeID ID; 8571 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8572 ID.AddInteger(MemVT.getRawBits()); 8573 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8574 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8575 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8576 ID.AddInteger(MMO->getFlags()); 8577 void *IP = nullptr; 8578 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8579 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8580 return SDValue(E, 0); 8581 } 8582 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8583 AM, ExtTy, isExpanding, MemVT, MMO); 8584 createOperands(N, Ops); 8585 8586 CSEMap.InsertNode(N, IP); 8587 InsertNode(N); 8588 SDValue V(N, 0); 8589 NewSDValueDbgMsg(V, "Creating new node: ", this); 8590 return V; 8591 } 8592 8593 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8594 SDValue Base, SDValue Offset, 8595 ISD::MemIndexedMode AM) { 8596 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8597 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8598 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8599 Offset, LD->getMask(), LD->getPassThru(), 8600 LD->getMemoryVT(), LD->getMemOperand(), AM, 8601 LD->getExtensionType(), LD->isExpandingLoad()); 8602 } 8603 8604 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8605 SDValue Val, SDValue Base, SDValue Offset, 8606 SDValue Mask, EVT MemVT, 8607 MachineMemOperand *MMO, 8608 ISD::MemIndexedMode AM, bool IsTruncating, 8609 bool IsCompressing) { 8610 assert(Chain.getValueType() == MVT::Other && 8611 "Invalid chain type"); 8612 bool Indexed = AM != ISD::UNINDEXED; 8613 assert((Indexed || Offset.isUndef()) && 8614 "Unindexed masked store with an offset!"); 8615 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8616 : getVTList(MVT::Other); 8617 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8618 FoldingSetNodeID ID; 8619 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8620 ID.AddInteger(MemVT.getRawBits()); 8621 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8622 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8623 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8624 ID.AddInteger(MMO->getFlags()); 8625 void *IP = nullptr; 8626 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8627 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8628 return SDValue(E, 0); 8629 } 8630 auto *N = 8631 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8632 IsTruncating, IsCompressing, MemVT, MMO); 8633 createOperands(N, Ops); 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::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8643 SDValue Base, SDValue Offset, 8644 ISD::MemIndexedMode AM) { 8645 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8646 assert(ST->getOffset().isUndef() && 8647 "Masked store is already a indexed store!"); 8648 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8649 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8650 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8651 } 8652 8653 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8654 ArrayRef<SDValue> Ops, 8655 MachineMemOperand *MMO, 8656 ISD::MemIndexType IndexType, 8657 ISD::LoadExtType ExtTy) { 8658 assert(Ops.size() == 6 && "Incompatible number of operands"); 8659 8660 FoldingSetNodeID ID; 8661 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8662 ID.AddInteger(MemVT.getRawBits()); 8663 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8664 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8665 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8666 ID.AddInteger(MMO->getFlags()); 8667 void *IP = nullptr; 8668 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8669 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8670 return SDValue(E, 0); 8671 } 8672 8673 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8674 VTs, MemVT, MMO, IndexType, ExtTy); 8675 createOperands(N, Ops); 8676 8677 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8678 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8679 assert(N->getMask().getValueType().getVectorElementCount() == 8680 N->getValueType(0).getVectorElementCount() && 8681 "Vector width mismatch between mask and data"); 8682 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8683 N->getValueType(0).getVectorElementCount().isScalable() && 8684 "Scalable flags of index and data do not match"); 8685 assert(ElementCount::isKnownGE( 8686 N->getIndex().getValueType().getVectorElementCount(), 8687 N->getValueType(0).getVectorElementCount()) && 8688 "Vector width mismatch between index and data"); 8689 assert(isa<ConstantSDNode>(N->getScale()) && 8690 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8691 "Scale should be a constant power of 2"); 8692 8693 CSEMap.InsertNode(N, IP); 8694 InsertNode(N); 8695 SDValue V(N, 0); 8696 NewSDValueDbgMsg(V, "Creating new node: ", this); 8697 return V; 8698 } 8699 8700 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8701 ArrayRef<SDValue> Ops, 8702 MachineMemOperand *MMO, 8703 ISD::MemIndexType IndexType, 8704 bool IsTrunc) { 8705 assert(Ops.size() == 6 && "Incompatible number of operands"); 8706 8707 FoldingSetNodeID ID; 8708 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8709 ID.AddInteger(MemVT.getRawBits()); 8710 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8711 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8712 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8713 ID.AddInteger(MMO->getFlags()); 8714 void *IP = nullptr; 8715 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8716 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8717 return SDValue(E, 0); 8718 } 8719 8720 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8721 VTs, MemVT, MMO, IndexType, IsTrunc); 8722 createOperands(N, Ops); 8723 8724 assert(N->getMask().getValueType().getVectorElementCount() == 8725 N->getValue().getValueType().getVectorElementCount() && 8726 "Vector width mismatch between mask and data"); 8727 assert( 8728 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8729 N->getValue().getValueType().getVectorElementCount().isScalable() && 8730 "Scalable flags of index and data do not match"); 8731 assert(ElementCount::isKnownGE( 8732 N->getIndex().getValueType().getVectorElementCount(), 8733 N->getValue().getValueType().getVectorElementCount()) && 8734 "Vector width mismatch between index and data"); 8735 assert(isa<ConstantSDNode>(N->getScale()) && 8736 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8737 "Scale should be a constant power of 2"); 8738 8739 CSEMap.InsertNode(N, IP); 8740 InsertNode(N); 8741 SDValue V(N, 0); 8742 NewSDValueDbgMsg(V, "Creating new node: ", this); 8743 return V; 8744 } 8745 8746 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8747 // select undef, T, F --> T (if T is a constant), otherwise F 8748 // select, ?, undef, F --> F 8749 // select, ?, T, undef --> T 8750 if (Cond.isUndef()) 8751 return isConstantValueOfAnyType(T) ? T : F; 8752 if (T.isUndef()) 8753 return F; 8754 if (F.isUndef()) 8755 return T; 8756 8757 // select true, T, F --> T 8758 // select false, T, F --> F 8759 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8760 return CondC->isZero() ? F : T; 8761 8762 // TODO: This should simplify VSELECT with constant condition using something 8763 // like this (but check boolean contents to be complete?): 8764 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8765 // return T; 8766 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8767 // return F; 8768 8769 // select ?, T, T --> T 8770 if (T == F) 8771 return T; 8772 8773 return SDValue(); 8774 } 8775 8776 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8777 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8778 if (X.isUndef()) 8779 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8780 // shift X, undef --> undef (because it may shift by the bitwidth) 8781 if (Y.isUndef()) 8782 return getUNDEF(X.getValueType()); 8783 8784 // shift 0, Y --> 0 8785 // shift X, 0 --> X 8786 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8787 return X; 8788 8789 // shift X, C >= bitwidth(X) --> undef 8790 // All vector elements must be too big (or undef) to avoid partial undefs. 8791 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8792 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8793 }; 8794 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8795 return getUNDEF(X.getValueType()); 8796 8797 return SDValue(); 8798 } 8799 8800 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8801 SDNodeFlags Flags) { 8802 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8803 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8804 // operation is poison. That result can be relaxed to undef. 8805 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8806 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8807 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8808 (YC && YC->getValueAPF().isNaN()); 8809 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8810 (YC && YC->getValueAPF().isInfinity()); 8811 8812 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8813 return getUNDEF(X.getValueType()); 8814 8815 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8816 return getUNDEF(X.getValueType()); 8817 8818 if (!YC) 8819 return SDValue(); 8820 8821 // X + -0.0 --> X 8822 if (Opcode == ISD::FADD) 8823 if (YC->getValueAPF().isNegZero()) 8824 return X; 8825 8826 // X - +0.0 --> X 8827 if (Opcode == ISD::FSUB) 8828 if (YC->getValueAPF().isPosZero()) 8829 return X; 8830 8831 // X * 1.0 --> X 8832 // X / 1.0 --> X 8833 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8834 if (YC->getValueAPF().isExactlyValue(1.0)) 8835 return X; 8836 8837 // X * 0.0 --> 0.0 8838 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8839 if (YC->getValueAPF().isZero()) 8840 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8841 8842 return SDValue(); 8843 } 8844 8845 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8846 SDValue Ptr, SDValue SV, unsigned Align) { 8847 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8848 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8849 } 8850 8851 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8852 ArrayRef<SDUse> Ops) { 8853 switch (Ops.size()) { 8854 case 0: return getNode(Opcode, DL, VT); 8855 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8856 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8857 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8858 default: break; 8859 } 8860 8861 // Copy from an SDUse array into an SDValue array for use with 8862 // the regular getNode logic. 8863 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8864 return getNode(Opcode, DL, VT, NewOps); 8865 } 8866 8867 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8868 ArrayRef<SDValue> Ops) { 8869 SDNodeFlags Flags; 8870 if (Inserter) 8871 Flags = Inserter->getFlags(); 8872 return getNode(Opcode, DL, VT, Ops, Flags); 8873 } 8874 8875 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8876 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8877 unsigned NumOps = Ops.size(); 8878 switch (NumOps) { 8879 case 0: return getNode(Opcode, DL, VT); 8880 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8881 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8882 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8883 default: break; 8884 } 8885 8886 #ifndef NDEBUG 8887 for (auto &Op : Ops) 8888 assert(Op.getOpcode() != ISD::DELETED_NODE && 8889 "Operand is DELETED_NODE!"); 8890 #endif 8891 8892 switch (Opcode) { 8893 default: break; 8894 case ISD::BUILD_VECTOR: 8895 // Attempt to simplify BUILD_VECTOR. 8896 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8897 return V; 8898 break; 8899 case ISD::CONCAT_VECTORS: 8900 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8901 return V; 8902 break; 8903 case ISD::SELECT_CC: 8904 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8905 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8906 "LHS and RHS of condition must have same type!"); 8907 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8908 "True and False arms of SelectCC must have same type!"); 8909 assert(Ops[2].getValueType() == VT && 8910 "select_cc node must be of same type as true and false value!"); 8911 break; 8912 case ISD::BR_CC: 8913 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8914 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8915 "LHS/RHS of comparison should match types!"); 8916 break; 8917 case ISD::VP_ADD: 8918 case ISD::VP_SUB: 8919 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR 8920 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8921 Opcode = ISD::VP_XOR; 8922 break; 8923 case ISD::VP_MUL: 8924 // If it is VP_MUL mask operation then turn it to VP_AND 8925 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8926 Opcode = ISD::VP_AND; 8927 break; 8928 case ISD::VP_REDUCE_MUL: 8929 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND 8930 if (VT == MVT::i1) 8931 Opcode = ISD::VP_REDUCE_AND; 8932 break; 8933 case ISD::VP_REDUCE_ADD: 8934 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR 8935 if (VT == MVT::i1) 8936 Opcode = ISD::VP_REDUCE_XOR; 8937 break; 8938 case ISD::VP_REDUCE_SMAX: 8939 case ISD::VP_REDUCE_UMIN: 8940 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to 8941 // VP_REDUCE_AND. 8942 if (VT == MVT::i1) 8943 Opcode = ISD::VP_REDUCE_AND; 8944 break; 8945 case ISD::VP_REDUCE_SMIN: 8946 case ISD::VP_REDUCE_UMAX: 8947 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to 8948 // VP_REDUCE_OR. 8949 if (VT == MVT::i1) 8950 Opcode = ISD::VP_REDUCE_OR; 8951 break; 8952 } 8953 8954 // Memoize nodes. 8955 SDNode *N; 8956 SDVTList VTs = getVTList(VT); 8957 8958 if (VT != MVT::Glue) { 8959 FoldingSetNodeID ID; 8960 AddNodeIDNode(ID, Opcode, VTs, Ops); 8961 void *IP = nullptr; 8962 8963 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8964 return SDValue(E, 0); 8965 8966 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8967 createOperands(N, Ops); 8968 8969 CSEMap.InsertNode(N, IP); 8970 } else { 8971 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8972 createOperands(N, Ops); 8973 } 8974 8975 N->setFlags(Flags); 8976 InsertNode(N); 8977 SDValue V(N, 0); 8978 NewSDValueDbgMsg(V, "Creating new node: ", this); 8979 return V; 8980 } 8981 8982 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8983 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8984 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8985 } 8986 8987 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8988 ArrayRef<SDValue> Ops) { 8989 SDNodeFlags Flags; 8990 if (Inserter) 8991 Flags = Inserter->getFlags(); 8992 return getNode(Opcode, DL, VTList, Ops, Flags); 8993 } 8994 8995 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8996 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8997 if (VTList.NumVTs == 1) 8998 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags); 8999 9000 #ifndef NDEBUG 9001 for (auto &Op : Ops) 9002 assert(Op.getOpcode() != ISD::DELETED_NODE && 9003 "Operand is DELETED_NODE!"); 9004 #endif 9005 9006 switch (Opcode) { 9007 case ISD::STRICT_FP_EXTEND: 9008 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 9009 "Invalid STRICT_FP_EXTEND!"); 9010 assert(VTList.VTs[0].isFloatingPoint() && 9011 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 9012 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9013 "STRICT_FP_EXTEND result type should be vector iff the operand " 9014 "type is vector!"); 9015 assert((!VTList.VTs[0].isVector() || 9016 VTList.VTs[0].getVectorNumElements() == 9017 Ops[1].getValueType().getVectorNumElements()) && 9018 "Vector element count mismatch!"); 9019 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 9020 "Invalid fpext node, dst <= src!"); 9021 break; 9022 case ISD::STRICT_FP_ROUND: 9023 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 9024 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9025 "STRICT_FP_ROUND result type should be vector iff the operand " 9026 "type is vector!"); 9027 assert((!VTList.VTs[0].isVector() || 9028 VTList.VTs[0].getVectorNumElements() == 9029 Ops[1].getValueType().getVectorNumElements()) && 9030 "Vector element count mismatch!"); 9031 assert(VTList.VTs[0].isFloatingPoint() && 9032 Ops[1].getValueType().isFloatingPoint() && 9033 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 9034 isa<ConstantSDNode>(Ops[2]) && 9035 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 9036 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 9037 "Invalid STRICT_FP_ROUND!"); 9038 break; 9039 #if 0 9040 // FIXME: figure out how to safely handle things like 9041 // int foo(int x) { return 1 << (x & 255); } 9042 // int bar() { return foo(256); } 9043 case ISD::SRA_PARTS: 9044 case ISD::SRL_PARTS: 9045 case ISD::SHL_PARTS: 9046 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 9047 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 9048 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9049 else if (N3.getOpcode() == ISD::AND) 9050 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 9051 // If the and is only masking out bits that cannot effect the shift, 9052 // eliminate the and. 9053 unsigned NumBits = VT.getScalarSizeInBits()*2; 9054 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 9055 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9056 } 9057 break; 9058 #endif 9059 } 9060 9061 // Memoize the node unless it returns a flag. 9062 SDNode *N; 9063 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 9064 FoldingSetNodeID ID; 9065 AddNodeIDNode(ID, Opcode, VTList, Ops); 9066 void *IP = nullptr; 9067 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9068 return SDValue(E, 0); 9069 9070 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9071 createOperands(N, Ops); 9072 CSEMap.InsertNode(N, IP); 9073 } else { 9074 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9075 createOperands(N, Ops); 9076 } 9077 9078 N->setFlags(Flags); 9079 InsertNode(N); 9080 SDValue V(N, 0); 9081 NewSDValueDbgMsg(V, "Creating new node: ", this); 9082 return V; 9083 } 9084 9085 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 9086 SDVTList VTList) { 9087 return getNode(Opcode, DL, VTList, None); 9088 } 9089 9090 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9091 SDValue N1) { 9092 SDValue Ops[] = { N1 }; 9093 return getNode(Opcode, DL, VTList, Ops); 9094 } 9095 9096 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9097 SDValue N1, SDValue N2) { 9098 SDValue Ops[] = { N1, N2 }; 9099 return getNode(Opcode, DL, VTList, Ops); 9100 } 9101 9102 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9103 SDValue N1, SDValue N2, SDValue N3) { 9104 SDValue Ops[] = { N1, N2, N3 }; 9105 return getNode(Opcode, DL, VTList, Ops); 9106 } 9107 9108 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9109 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 9110 SDValue Ops[] = { N1, N2, N3, N4 }; 9111 return getNode(Opcode, DL, VTList, Ops); 9112 } 9113 9114 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9115 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 9116 SDValue N5) { 9117 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 9118 return getNode(Opcode, DL, VTList, Ops); 9119 } 9120 9121 SDVTList SelectionDAG::getVTList(EVT VT) { 9122 return makeVTList(SDNode::getValueTypeList(VT), 1); 9123 } 9124 9125 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 9126 FoldingSetNodeID ID; 9127 ID.AddInteger(2U); 9128 ID.AddInteger(VT1.getRawBits()); 9129 ID.AddInteger(VT2.getRawBits()); 9130 9131 void *IP = nullptr; 9132 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9133 if (!Result) { 9134 EVT *Array = Allocator.Allocate<EVT>(2); 9135 Array[0] = VT1; 9136 Array[1] = VT2; 9137 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 9138 VTListMap.InsertNode(Result, IP); 9139 } 9140 return Result->getSDVTList(); 9141 } 9142 9143 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 9144 FoldingSetNodeID ID; 9145 ID.AddInteger(3U); 9146 ID.AddInteger(VT1.getRawBits()); 9147 ID.AddInteger(VT2.getRawBits()); 9148 ID.AddInteger(VT3.getRawBits()); 9149 9150 void *IP = nullptr; 9151 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9152 if (!Result) { 9153 EVT *Array = Allocator.Allocate<EVT>(3); 9154 Array[0] = VT1; 9155 Array[1] = VT2; 9156 Array[2] = VT3; 9157 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9158 VTListMap.InsertNode(Result, IP); 9159 } 9160 return Result->getSDVTList(); 9161 } 9162 9163 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9164 FoldingSetNodeID ID; 9165 ID.AddInteger(4U); 9166 ID.AddInteger(VT1.getRawBits()); 9167 ID.AddInteger(VT2.getRawBits()); 9168 ID.AddInteger(VT3.getRawBits()); 9169 ID.AddInteger(VT4.getRawBits()); 9170 9171 void *IP = nullptr; 9172 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9173 if (!Result) { 9174 EVT *Array = Allocator.Allocate<EVT>(4); 9175 Array[0] = VT1; 9176 Array[1] = VT2; 9177 Array[2] = VT3; 9178 Array[3] = VT4; 9179 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9180 VTListMap.InsertNode(Result, IP); 9181 } 9182 return Result->getSDVTList(); 9183 } 9184 9185 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9186 unsigned NumVTs = VTs.size(); 9187 FoldingSetNodeID ID; 9188 ID.AddInteger(NumVTs); 9189 for (unsigned index = 0; index < NumVTs; index++) { 9190 ID.AddInteger(VTs[index].getRawBits()); 9191 } 9192 9193 void *IP = nullptr; 9194 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9195 if (!Result) { 9196 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9197 llvm::copy(VTs, Array); 9198 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9199 VTListMap.InsertNode(Result, IP); 9200 } 9201 return Result->getSDVTList(); 9202 } 9203 9204 9205 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9206 /// specified operands. If the resultant node already exists in the DAG, 9207 /// this does not modify the specified node, instead it returns the node that 9208 /// already exists. If the resultant node does not exist in the DAG, the 9209 /// input node is returned. As a degenerate case, if you specify the same 9210 /// input operands as the node already has, the input node is returned. 9211 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9212 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9213 9214 // Check to see if there is no change. 9215 if (Op == N->getOperand(0)) return N; 9216 9217 // See if the modified node already exists. 9218 void *InsertPos = nullptr; 9219 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9220 return Existing; 9221 9222 // Nope it doesn't. Remove the node from its current place in the maps. 9223 if (InsertPos) 9224 if (!RemoveNodeFromCSEMaps(N)) 9225 InsertPos = nullptr; 9226 9227 // Now we update the operands. 9228 N->OperandList[0].set(Op); 9229 9230 updateDivergence(N); 9231 // If this gets put into a CSE map, add it. 9232 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9233 return N; 9234 } 9235 9236 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9237 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9238 9239 // Check to see if there is no change. 9240 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9241 return N; // No operands changed, just return the input node. 9242 9243 // See if the modified node already exists. 9244 void *InsertPos = nullptr; 9245 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9246 return Existing; 9247 9248 // Nope it doesn't. Remove the node from its current place in the maps. 9249 if (InsertPos) 9250 if (!RemoveNodeFromCSEMaps(N)) 9251 InsertPos = nullptr; 9252 9253 // Now we update the operands. 9254 if (N->OperandList[0] != Op1) 9255 N->OperandList[0].set(Op1); 9256 if (N->OperandList[1] != Op2) 9257 N->OperandList[1].set(Op2); 9258 9259 updateDivergence(N); 9260 // If this gets put into a CSE map, add it. 9261 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9262 return N; 9263 } 9264 9265 SDNode *SelectionDAG:: 9266 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9267 SDValue Ops[] = { Op1, Op2, Op3 }; 9268 return UpdateNodeOperands(N, Ops); 9269 } 9270 9271 SDNode *SelectionDAG:: 9272 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9273 SDValue Op3, SDValue Op4) { 9274 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9275 return UpdateNodeOperands(N, Ops); 9276 } 9277 9278 SDNode *SelectionDAG:: 9279 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9280 SDValue Op3, SDValue Op4, SDValue Op5) { 9281 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9282 return UpdateNodeOperands(N, Ops); 9283 } 9284 9285 SDNode *SelectionDAG:: 9286 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9287 unsigned NumOps = Ops.size(); 9288 assert(N->getNumOperands() == NumOps && 9289 "Update with wrong number of operands"); 9290 9291 // If no operands changed just return the input node. 9292 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9293 return N; 9294 9295 // See if the modified node already exists. 9296 void *InsertPos = nullptr; 9297 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9298 return Existing; 9299 9300 // Nope it doesn't. Remove the node from its current place in the maps. 9301 if (InsertPos) 9302 if (!RemoveNodeFromCSEMaps(N)) 9303 InsertPos = nullptr; 9304 9305 // Now we update the operands. 9306 for (unsigned i = 0; i != NumOps; ++i) 9307 if (N->OperandList[i] != Ops[i]) 9308 N->OperandList[i].set(Ops[i]); 9309 9310 updateDivergence(N); 9311 // If this gets put into a CSE map, add it. 9312 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9313 return N; 9314 } 9315 9316 /// DropOperands - Release the operands and set this node to have 9317 /// zero operands. 9318 void SDNode::DropOperands() { 9319 // Unlike the code in MorphNodeTo that does this, we don't need to 9320 // watch for dead nodes here. 9321 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9322 SDUse &Use = *I++; 9323 Use.set(SDValue()); 9324 } 9325 } 9326 9327 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9328 ArrayRef<MachineMemOperand *> NewMemRefs) { 9329 if (NewMemRefs.empty()) { 9330 N->clearMemRefs(); 9331 return; 9332 } 9333 9334 // Check if we can avoid allocating by storing a single reference directly. 9335 if (NewMemRefs.size() == 1) { 9336 N->MemRefs = NewMemRefs[0]; 9337 N->NumMemRefs = 1; 9338 return; 9339 } 9340 9341 MachineMemOperand **MemRefsBuffer = 9342 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 9343 llvm::copy(NewMemRefs, MemRefsBuffer); 9344 N->MemRefs = MemRefsBuffer; 9345 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 9346 } 9347 9348 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 9349 /// machine opcode. 9350 /// 9351 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9352 EVT VT) { 9353 SDVTList VTs = getVTList(VT); 9354 return SelectNodeTo(N, MachineOpc, VTs, None); 9355 } 9356 9357 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9358 EVT VT, SDValue Op1) { 9359 SDVTList VTs = getVTList(VT); 9360 SDValue Ops[] = { Op1 }; 9361 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9362 } 9363 9364 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9365 EVT VT, SDValue Op1, 9366 SDValue Op2) { 9367 SDVTList VTs = getVTList(VT); 9368 SDValue Ops[] = { Op1, Op2 }; 9369 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9370 } 9371 9372 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9373 EVT VT, SDValue Op1, 9374 SDValue Op2, SDValue Op3) { 9375 SDVTList VTs = getVTList(VT); 9376 SDValue Ops[] = { Op1, Op2, Op3 }; 9377 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9378 } 9379 9380 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9381 EVT VT, ArrayRef<SDValue> Ops) { 9382 SDVTList VTs = getVTList(VT); 9383 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9384 } 9385 9386 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9387 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 9388 SDVTList VTs = getVTList(VT1, VT2); 9389 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9390 } 9391 9392 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9393 EVT VT1, EVT VT2) { 9394 SDVTList VTs = getVTList(VT1, VT2); 9395 return SelectNodeTo(N, MachineOpc, VTs, None); 9396 } 9397 9398 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9399 EVT VT1, EVT VT2, EVT VT3, 9400 ArrayRef<SDValue> Ops) { 9401 SDVTList VTs = getVTList(VT1, VT2, VT3); 9402 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9403 } 9404 9405 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9406 EVT VT1, EVT VT2, 9407 SDValue Op1, SDValue Op2) { 9408 SDVTList VTs = getVTList(VT1, VT2); 9409 SDValue Ops[] = { Op1, Op2 }; 9410 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9411 } 9412 9413 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9414 SDVTList VTs,ArrayRef<SDValue> Ops) { 9415 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 9416 // Reset the NodeID to -1. 9417 New->setNodeId(-1); 9418 if (New != N) { 9419 ReplaceAllUsesWith(N, New); 9420 RemoveDeadNode(N); 9421 } 9422 return New; 9423 } 9424 9425 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 9426 /// the line number information on the merged node since it is not possible to 9427 /// preserve the information that operation is associated with multiple lines. 9428 /// This will make the debugger working better at -O0, were there is a higher 9429 /// probability having other instructions associated with that line. 9430 /// 9431 /// For IROrder, we keep the smaller of the two 9432 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 9433 DebugLoc NLoc = N->getDebugLoc(); 9434 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 9435 N->setDebugLoc(DebugLoc()); 9436 } 9437 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 9438 N->setIROrder(Order); 9439 return N; 9440 } 9441 9442 /// MorphNodeTo - This *mutates* the specified node to have the specified 9443 /// return type, opcode, and operands. 9444 /// 9445 /// Note that MorphNodeTo returns the resultant node. If there is already a 9446 /// node of the specified opcode and operands, it returns that node instead of 9447 /// the current one. Note that the SDLoc need not be the same. 9448 /// 9449 /// Using MorphNodeTo is faster than creating a new node and swapping it in 9450 /// with ReplaceAllUsesWith both because it often avoids allocating a new 9451 /// node, and because it doesn't require CSE recalculation for any of 9452 /// the node's users. 9453 /// 9454 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 9455 /// As a consequence it isn't appropriate to use from within the DAG combiner or 9456 /// the legalizer which maintain worklists that would need to be updated when 9457 /// deleting things. 9458 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 9459 SDVTList VTs, ArrayRef<SDValue> Ops) { 9460 // If an identical node already exists, use it. 9461 void *IP = nullptr; 9462 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 9463 FoldingSetNodeID ID; 9464 AddNodeIDNode(ID, Opc, VTs, Ops); 9465 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 9466 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 9467 } 9468 9469 if (!RemoveNodeFromCSEMaps(N)) 9470 IP = nullptr; 9471 9472 // Start the morphing. 9473 N->NodeType = Opc; 9474 N->ValueList = VTs.VTs; 9475 N->NumValues = VTs.NumVTs; 9476 9477 // Clear the operands list, updating used nodes to remove this from their 9478 // use list. Keep track of any operands that become dead as a result. 9479 SmallPtrSet<SDNode*, 16> DeadNodeSet; 9480 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 9481 SDUse &Use = *I++; 9482 SDNode *Used = Use.getNode(); 9483 Use.set(SDValue()); 9484 if (Used->use_empty()) 9485 DeadNodeSet.insert(Used); 9486 } 9487 9488 // For MachineNode, initialize the memory references information. 9489 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 9490 MN->clearMemRefs(); 9491 9492 // Swap for an appropriately sized array from the recycler. 9493 removeOperands(N); 9494 createOperands(N, Ops); 9495 9496 // Delete any nodes that are still dead after adding the uses for the 9497 // new operands. 9498 if (!DeadNodeSet.empty()) { 9499 SmallVector<SDNode *, 16> DeadNodes; 9500 for (SDNode *N : DeadNodeSet) 9501 if (N->use_empty()) 9502 DeadNodes.push_back(N); 9503 RemoveDeadNodes(DeadNodes); 9504 } 9505 9506 if (IP) 9507 CSEMap.InsertNode(N, IP); // Memoize the new node. 9508 return N; 9509 } 9510 9511 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9512 unsigned OrigOpc = Node->getOpcode(); 9513 unsigned NewOpc; 9514 switch (OrigOpc) { 9515 default: 9516 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9517 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9518 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9519 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9520 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9521 #include "llvm/IR/ConstrainedOps.def" 9522 } 9523 9524 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9525 9526 // We're taking this node out of the chain, so we need to re-link things. 9527 SDValue InputChain = Node->getOperand(0); 9528 SDValue OutputChain = SDValue(Node, 1); 9529 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9530 9531 SmallVector<SDValue, 3> Ops; 9532 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9533 Ops.push_back(Node->getOperand(i)); 9534 9535 SDVTList VTs = getVTList(Node->getValueType(0)); 9536 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9537 9538 // MorphNodeTo can operate in two ways: if an existing node with the 9539 // specified operands exists, it can just return it. Otherwise, it 9540 // updates the node in place to have the requested operands. 9541 if (Res == Node) { 9542 // If we updated the node in place, reset the node ID. To the isel, 9543 // this should be just like a newly allocated machine node. 9544 Res->setNodeId(-1); 9545 } else { 9546 ReplaceAllUsesWith(Node, Res); 9547 RemoveDeadNode(Node); 9548 } 9549 9550 return Res; 9551 } 9552 9553 /// getMachineNode - These are used for target selectors to create a new node 9554 /// with specified return type(s), MachineInstr opcode, and operands. 9555 /// 9556 /// Note that getMachineNode returns the resultant node. If there is already a 9557 /// node of the specified opcode and operands, it returns that node instead of 9558 /// the current one. 9559 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9560 EVT VT) { 9561 SDVTList VTs = getVTList(VT); 9562 return getMachineNode(Opcode, dl, VTs, None); 9563 } 9564 9565 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9566 EVT VT, SDValue Op1) { 9567 SDVTList VTs = getVTList(VT); 9568 SDValue Ops[] = { Op1 }; 9569 return getMachineNode(Opcode, dl, VTs, Ops); 9570 } 9571 9572 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9573 EVT VT, SDValue Op1, SDValue Op2) { 9574 SDVTList VTs = getVTList(VT); 9575 SDValue Ops[] = { Op1, Op2 }; 9576 return getMachineNode(Opcode, dl, VTs, Ops); 9577 } 9578 9579 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9580 EVT VT, SDValue Op1, SDValue Op2, 9581 SDValue Op3) { 9582 SDVTList VTs = getVTList(VT); 9583 SDValue Ops[] = { Op1, Op2, Op3 }; 9584 return getMachineNode(Opcode, dl, VTs, Ops); 9585 } 9586 9587 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9588 EVT VT, ArrayRef<SDValue> Ops) { 9589 SDVTList VTs = getVTList(VT); 9590 return getMachineNode(Opcode, dl, VTs, Ops); 9591 } 9592 9593 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9594 EVT VT1, EVT VT2, SDValue Op1, 9595 SDValue Op2) { 9596 SDVTList VTs = getVTList(VT1, VT2); 9597 SDValue Ops[] = { Op1, Op2 }; 9598 return getMachineNode(Opcode, dl, VTs, Ops); 9599 } 9600 9601 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9602 EVT VT1, EVT VT2, SDValue Op1, 9603 SDValue Op2, SDValue Op3) { 9604 SDVTList VTs = getVTList(VT1, VT2); 9605 SDValue Ops[] = { Op1, Op2, Op3 }; 9606 return getMachineNode(Opcode, dl, VTs, Ops); 9607 } 9608 9609 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9610 EVT VT1, EVT VT2, 9611 ArrayRef<SDValue> Ops) { 9612 SDVTList VTs = getVTList(VT1, VT2); 9613 return getMachineNode(Opcode, dl, VTs, Ops); 9614 } 9615 9616 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9617 EVT VT1, EVT VT2, EVT VT3, 9618 SDValue Op1, SDValue Op2) { 9619 SDVTList VTs = getVTList(VT1, VT2, VT3); 9620 SDValue Ops[] = { Op1, Op2 }; 9621 return getMachineNode(Opcode, dl, VTs, Ops); 9622 } 9623 9624 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9625 EVT VT1, EVT VT2, EVT VT3, 9626 SDValue Op1, SDValue Op2, 9627 SDValue Op3) { 9628 SDVTList VTs = getVTList(VT1, VT2, VT3); 9629 SDValue Ops[] = { Op1, Op2, Op3 }; 9630 return getMachineNode(Opcode, dl, VTs, Ops); 9631 } 9632 9633 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9634 EVT VT1, EVT VT2, EVT VT3, 9635 ArrayRef<SDValue> Ops) { 9636 SDVTList VTs = getVTList(VT1, VT2, VT3); 9637 return getMachineNode(Opcode, dl, VTs, Ops); 9638 } 9639 9640 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9641 ArrayRef<EVT> ResultTys, 9642 ArrayRef<SDValue> Ops) { 9643 SDVTList VTs = getVTList(ResultTys); 9644 return getMachineNode(Opcode, dl, VTs, Ops); 9645 } 9646 9647 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9648 SDVTList VTs, 9649 ArrayRef<SDValue> Ops) { 9650 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9651 MachineSDNode *N; 9652 void *IP = nullptr; 9653 9654 if (DoCSE) { 9655 FoldingSetNodeID ID; 9656 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9657 IP = nullptr; 9658 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9659 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9660 } 9661 } 9662 9663 // Allocate a new MachineSDNode. 9664 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9665 createOperands(N, Ops); 9666 9667 if (DoCSE) 9668 CSEMap.InsertNode(N, IP); 9669 9670 InsertNode(N); 9671 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9672 return N; 9673 } 9674 9675 /// getTargetExtractSubreg - A convenience function for creating 9676 /// TargetOpcode::EXTRACT_SUBREG nodes. 9677 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9678 SDValue Operand) { 9679 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9680 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9681 VT, Operand, SRIdxVal); 9682 return SDValue(Subreg, 0); 9683 } 9684 9685 /// getTargetInsertSubreg - A convenience function for creating 9686 /// TargetOpcode::INSERT_SUBREG nodes. 9687 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9688 SDValue Operand, SDValue Subreg) { 9689 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9690 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9691 VT, Operand, Subreg, SRIdxVal); 9692 return SDValue(Result, 0); 9693 } 9694 9695 /// getNodeIfExists - Get the specified node if it's already available, or 9696 /// else return NULL. 9697 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9698 ArrayRef<SDValue> Ops) { 9699 SDNodeFlags Flags; 9700 if (Inserter) 9701 Flags = Inserter->getFlags(); 9702 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9703 } 9704 9705 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9706 ArrayRef<SDValue> Ops, 9707 const SDNodeFlags Flags) { 9708 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9709 FoldingSetNodeID ID; 9710 AddNodeIDNode(ID, Opcode, VTList, Ops); 9711 void *IP = nullptr; 9712 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9713 E->intersectFlagsWith(Flags); 9714 return E; 9715 } 9716 } 9717 return nullptr; 9718 } 9719 9720 /// doesNodeExist - Check if a node exists without modifying its flags. 9721 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9722 ArrayRef<SDValue> Ops) { 9723 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9724 FoldingSetNodeID ID; 9725 AddNodeIDNode(ID, Opcode, VTList, Ops); 9726 void *IP = nullptr; 9727 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9728 return true; 9729 } 9730 return false; 9731 } 9732 9733 /// getDbgValue - Creates a SDDbgValue node. 9734 /// 9735 /// SDNode 9736 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9737 SDNode *N, unsigned R, bool IsIndirect, 9738 const DebugLoc &DL, unsigned O) { 9739 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9740 "Expected inlined-at fields to agree"); 9741 return new (DbgInfo->getAlloc()) 9742 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9743 {}, IsIndirect, DL, O, 9744 /*IsVariadic=*/false); 9745 } 9746 9747 /// Constant 9748 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9749 DIExpression *Expr, 9750 const Value *C, 9751 const DebugLoc &DL, unsigned O) { 9752 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9753 "Expected inlined-at fields to agree"); 9754 return new (DbgInfo->getAlloc()) 9755 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9756 /*IsIndirect=*/false, DL, O, 9757 /*IsVariadic=*/false); 9758 } 9759 9760 /// FrameIndex 9761 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9762 DIExpression *Expr, unsigned FI, 9763 bool IsIndirect, 9764 const DebugLoc &DL, 9765 unsigned O) { 9766 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9767 "Expected inlined-at fields to agree"); 9768 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9769 } 9770 9771 /// FrameIndex with dependencies 9772 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9773 DIExpression *Expr, unsigned FI, 9774 ArrayRef<SDNode *> Dependencies, 9775 bool IsIndirect, 9776 const DebugLoc &DL, 9777 unsigned O) { 9778 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9779 "Expected inlined-at fields to agree"); 9780 return new (DbgInfo->getAlloc()) 9781 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9782 Dependencies, IsIndirect, DL, O, 9783 /*IsVariadic=*/false); 9784 } 9785 9786 /// VReg 9787 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9788 unsigned VReg, bool IsIndirect, 9789 const DebugLoc &DL, unsigned O) { 9790 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9791 "Expected inlined-at fields to agree"); 9792 return new (DbgInfo->getAlloc()) 9793 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9794 {}, IsIndirect, DL, O, 9795 /*IsVariadic=*/false); 9796 } 9797 9798 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9799 ArrayRef<SDDbgOperand> Locs, 9800 ArrayRef<SDNode *> Dependencies, 9801 bool IsIndirect, const DebugLoc &DL, 9802 unsigned O, bool IsVariadic) { 9803 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9804 "Expected inlined-at fields to agree"); 9805 return new (DbgInfo->getAlloc()) 9806 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9807 DL, O, IsVariadic); 9808 } 9809 9810 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9811 unsigned OffsetInBits, unsigned SizeInBits, 9812 bool InvalidateDbg) { 9813 SDNode *FromNode = From.getNode(); 9814 SDNode *ToNode = To.getNode(); 9815 assert(FromNode && ToNode && "Can't modify dbg values"); 9816 9817 // PR35338 9818 // TODO: assert(From != To && "Redundant dbg value transfer"); 9819 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9820 if (From == To || FromNode == ToNode) 9821 return; 9822 9823 if (!FromNode->getHasDebugValue()) 9824 return; 9825 9826 SDDbgOperand FromLocOp = 9827 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9828 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9829 9830 SmallVector<SDDbgValue *, 2> ClonedDVs; 9831 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9832 if (Dbg->isInvalidated()) 9833 continue; 9834 9835 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9836 9837 // Create a new location ops vector that is equal to the old vector, but 9838 // with each instance of FromLocOp replaced with ToLocOp. 9839 bool Changed = false; 9840 auto NewLocOps = Dbg->copyLocationOps(); 9841 std::replace_if( 9842 NewLocOps.begin(), NewLocOps.end(), 9843 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9844 bool Match = Op == FromLocOp; 9845 Changed |= Match; 9846 return Match; 9847 }, 9848 ToLocOp); 9849 // Ignore this SDDbgValue if we didn't find a matching location. 9850 if (!Changed) 9851 continue; 9852 9853 DIVariable *Var = Dbg->getVariable(); 9854 auto *Expr = Dbg->getExpression(); 9855 // If a fragment is requested, update the expression. 9856 if (SizeInBits) { 9857 // When splitting a larger (e.g., sign-extended) value whose 9858 // lower bits are described with an SDDbgValue, do not attempt 9859 // to transfer the SDDbgValue to the upper bits. 9860 if (auto FI = Expr->getFragmentInfo()) 9861 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9862 continue; 9863 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9864 SizeInBits); 9865 if (!Fragment) 9866 continue; 9867 Expr = *Fragment; 9868 } 9869 9870 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9871 // Clone the SDDbgValue and move it to To. 9872 SDDbgValue *Clone = getDbgValueList( 9873 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9874 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9875 Dbg->isVariadic()); 9876 ClonedDVs.push_back(Clone); 9877 9878 if (InvalidateDbg) { 9879 // Invalidate value and indicate the SDDbgValue should not be emitted. 9880 Dbg->setIsInvalidated(); 9881 Dbg->setIsEmitted(); 9882 } 9883 } 9884 9885 for (SDDbgValue *Dbg : ClonedDVs) { 9886 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9887 "Transferred DbgValues should depend on the new SDNode"); 9888 AddDbgValue(Dbg, false); 9889 } 9890 } 9891 9892 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9893 if (!N.getHasDebugValue()) 9894 return; 9895 9896 SmallVector<SDDbgValue *, 2> ClonedDVs; 9897 for (auto DV : GetDbgValues(&N)) { 9898 if (DV->isInvalidated()) 9899 continue; 9900 switch (N.getOpcode()) { 9901 default: 9902 break; 9903 case ISD::ADD: 9904 SDValue N0 = N.getOperand(0); 9905 SDValue N1 = N.getOperand(1); 9906 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9907 isConstantIntBuildVectorOrConstantInt(N1)) { 9908 uint64_t Offset = N.getConstantOperandVal(1); 9909 9910 // Rewrite an ADD constant node into a DIExpression. Since we are 9911 // performing arithmetic to compute the variable's *value* in the 9912 // DIExpression, we need to mark the expression with a 9913 // DW_OP_stack_value. 9914 auto *DIExpr = DV->getExpression(); 9915 auto NewLocOps = DV->copyLocationOps(); 9916 bool Changed = false; 9917 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9918 // We're not given a ResNo to compare against because the whole 9919 // node is going away. We know that any ISD::ADD only has one 9920 // result, so we can assume any node match is using the result. 9921 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9922 NewLocOps[i].getSDNode() != &N) 9923 continue; 9924 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9925 SmallVector<uint64_t, 3> ExprOps; 9926 DIExpression::appendOffset(ExprOps, Offset); 9927 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9928 Changed = true; 9929 } 9930 (void)Changed; 9931 assert(Changed && "Salvage target doesn't use N"); 9932 9933 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9934 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9935 NewLocOps, AdditionalDependencies, 9936 DV->isIndirect(), DV->getDebugLoc(), 9937 DV->getOrder(), DV->isVariadic()); 9938 ClonedDVs.push_back(Clone); 9939 DV->setIsInvalidated(); 9940 DV->setIsEmitted(); 9941 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9942 N0.getNode()->dumprFull(this); 9943 dbgs() << " into " << *DIExpr << '\n'); 9944 } 9945 } 9946 } 9947 9948 for (SDDbgValue *Dbg : ClonedDVs) { 9949 assert(!Dbg->getSDNodes().empty() && 9950 "Salvaged DbgValue should depend on a new SDNode"); 9951 AddDbgValue(Dbg, false); 9952 } 9953 } 9954 9955 /// Creates a SDDbgLabel node. 9956 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9957 const DebugLoc &DL, unsigned O) { 9958 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9959 "Expected inlined-at fields to agree"); 9960 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9961 } 9962 9963 namespace { 9964 9965 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9966 /// pointed to by a use iterator is deleted, increment the use iterator 9967 /// so that it doesn't dangle. 9968 /// 9969 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9970 SDNode::use_iterator &UI; 9971 SDNode::use_iterator &UE; 9972 9973 void NodeDeleted(SDNode *N, SDNode *E) override { 9974 // Increment the iterator as needed. 9975 while (UI != UE && N == *UI) 9976 ++UI; 9977 } 9978 9979 public: 9980 RAUWUpdateListener(SelectionDAG &d, 9981 SDNode::use_iterator &ui, 9982 SDNode::use_iterator &ue) 9983 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9984 }; 9985 9986 } // end anonymous namespace 9987 9988 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9989 /// This can cause recursive merging of nodes in the DAG. 9990 /// 9991 /// This version assumes From has a single result value. 9992 /// 9993 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9994 SDNode *From = FromN.getNode(); 9995 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9996 "Cannot replace with this method!"); 9997 assert(From != To.getNode() && "Cannot replace uses of with self"); 9998 9999 // Preserve Debug Values 10000 transferDbgValues(FromN, To); 10001 10002 // Iterate over all the existing uses of From. New uses will be added 10003 // to the beginning of the use list, which we avoid visiting. 10004 // This specifically avoids visiting uses of From that arise while the 10005 // replacement is happening, because any such uses would be the result 10006 // of CSE: If an existing node looks like From after one of its operands 10007 // is replaced by To, we don't want to replace of all its users with To 10008 // too. See PR3018 for more info. 10009 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10010 RAUWUpdateListener Listener(*this, UI, UE); 10011 while (UI != UE) { 10012 SDNode *User = *UI; 10013 10014 // This node is about to morph, remove its old self from the CSE maps. 10015 RemoveNodeFromCSEMaps(User); 10016 10017 // A user can appear in a use list multiple times, and when this 10018 // happens the uses are usually next to each other in the list. 10019 // To help reduce the number of CSE recomputations, process all 10020 // the uses of this user that we can find this way. 10021 do { 10022 SDUse &Use = UI.getUse(); 10023 ++UI; 10024 Use.set(To); 10025 if (To->isDivergent() != From->isDivergent()) 10026 updateDivergence(User); 10027 } while (UI != UE && *UI == User); 10028 // Now that we have modified User, add it back to the CSE maps. If it 10029 // already exists there, recursively merge the results together. 10030 AddModifiedNodeToCSEMaps(User); 10031 } 10032 10033 // If we just RAUW'd the root, take note. 10034 if (FromN == getRoot()) 10035 setRoot(To); 10036 } 10037 10038 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10039 /// This can cause recursive merging of nodes in the DAG. 10040 /// 10041 /// This version assumes that for each value of From, there is a 10042 /// corresponding value in To in the same position with the same type. 10043 /// 10044 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 10045 #ifndef NDEBUG 10046 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10047 assert((!From->hasAnyUseOfValue(i) || 10048 From->getValueType(i) == To->getValueType(i)) && 10049 "Cannot use this version of ReplaceAllUsesWith!"); 10050 #endif 10051 10052 // Handle the trivial case. 10053 if (From == To) 10054 return; 10055 10056 // Preserve Debug Info. Only do this if there's a use. 10057 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10058 if (From->hasAnyUseOfValue(i)) { 10059 assert((i < To->getNumValues()) && "Invalid To location"); 10060 transferDbgValues(SDValue(From, i), SDValue(To, i)); 10061 } 10062 10063 // Iterate over just the existing users of From. See the comments in 10064 // the ReplaceAllUsesWith above. 10065 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10066 RAUWUpdateListener Listener(*this, UI, UE); 10067 while (UI != UE) { 10068 SDNode *User = *UI; 10069 10070 // This node is about to morph, remove its old self from the CSE maps. 10071 RemoveNodeFromCSEMaps(User); 10072 10073 // A user can appear in a use list multiple times, and when this 10074 // happens the uses are usually next to each other in the list. 10075 // To help reduce the number of CSE recomputations, process all 10076 // the uses of this user that we can find this way. 10077 do { 10078 SDUse &Use = UI.getUse(); 10079 ++UI; 10080 Use.setNode(To); 10081 if (To->isDivergent() != From->isDivergent()) 10082 updateDivergence(User); 10083 } while (UI != UE && *UI == User); 10084 10085 // Now that we have modified User, add it back to the CSE maps. If it 10086 // already exists there, recursively merge the results together. 10087 AddModifiedNodeToCSEMaps(User); 10088 } 10089 10090 // If we just RAUW'd the root, take note. 10091 if (From == getRoot().getNode()) 10092 setRoot(SDValue(To, getRoot().getResNo())); 10093 } 10094 10095 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10096 /// This can cause recursive merging of nodes in the DAG. 10097 /// 10098 /// This version can replace From with any result values. To must match the 10099 /// number and types of values returned by From. 10100 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 10101 if (From->getNumValues() == 1) // Handle the simple case efficiently. 10102 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 10103 10104 // Preserve Debug Info. 10105 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10106 transferDbgValues(SDValue(From, i), To[i]); 10107 10108 // Iterate over just the existing users of From. See the comments in 10109 // the ReplaceAllUsesWith above. 10110 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10111 RAUWUpdateListener Listener(*this, UI, UE); 10112 while (UI != UE) { 10113 SDNode *User = *UI; 10114 10115 // This node is about to morph, remove its old self from the CSE maps. 10116 RemoveNodeFromCSEMaps(User); 10117 10118 // A user can appear in a use list multiple times, and when this happens the 10119 // uses are usually next to each other in the list. To help reduce the 10120 // number of CSE and divergence recomputations, process all the uses of this 10121 // user that we can find this way. 10122 bool To_IsDivergent = false; 10123 do { 10124 SDUse &Use = UI.getUse(); 10125 const SDValue &ToOp = To[Use.getResNo()]; 10126 ++UI; 10127 Use.set(ToOp); 10128 To_IsDivergent |= ToOp->isDivergent(); 10129 } while (UI != UE && *UI == User); 10130 10131 if (To_IsDivergent != From->isDivergent()) 10132 updateDivergence(User); 10133 10134 // Now that we have modified User, add it back to the CSE maps. If it 10135 // already exists there, recursively merge the results together. 10136 AddModifiedNodeToCSEMaps(User); 10137 } 10138 10139 // If we just RAUW'd the root, take note. 10140 if (From == getRoot().getNode()) 10141 setRoot(SDValue(To[getRoot().getResNo()])); 10142 } 10143 10144 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 10145 /// uses of other values produced by From.getNode() alone. The Deleted 10146 /// vector is handled the same way as for ReplaceAllUsesWith. 10147 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 10148 // Handle the really simple, really trivial case efficiently. 10149 if (From == To) return; 10150 10151 // Handle the simple, trivial, case efficiently. 10152 if (From.getNode()->getNumValues() == 1) { 10153 ReplaceAllUsesWith(From, To); 10154 return; 10155 } 10156 10157 // Preserve Debug Info. 10158 transferDbgValues(From, To); 10159 10160 // Iterate over just the existing users of From. See the comments in 10161 // the ReplaceAllUsesWith above. 10162 SDNode::use_iterator UI = From.getNode()->use_begin(), 10163 UE = From.getNode()->use_end(); 10164 RAUWUpdateListener Listener(*this, UI, UE); 10165 while (UI != UE) { 10166 SDNode *User = *UI; 10167 bool UserRemovedFromCSEMaps = false; 10168 10169 // A user can appear in a use list multiple times, and when this 10170 // happens the uses are usually next to each other in the list. 10171 // To help reduce the number of CSE recomputations, process all 10172 // the uses of this user that we can find this way. 10173 do { 10174 SDUse &Use = UI.getUse(); 10175 10176 // Skip uses of different values from the same node. 10177 if (Use.getResNo() != From.getResNo()) { 10178 ++UI; 10179 continue; 10180 } 10181 10182 // If this node hasn't been modified yet, it's still in the CSE maps, 10183 // so remove its old self from the CSE maps. 10184 if (!UserRemovedFromCSEMaps) { 10185 RemoveNodeFromCSEMaps(User); 10186 UserRemovedFromCSEMaps = true; 10187 } 10188 10189 ++UI; 10190 Use.set(To); 10191 if (To->isDivergent() != From->isDivergent()) 10192 updateDivergence(User); 10193 } while (UI != UE && *UI == User); 10194 // We are iterating over all uses of the From node, so if a use 10195 // doesn't use the specific value, no changes are made. 10196 if (!UserRemovedFromCSEMaps) 10197 continue; 10198 10199 // Now that we have modified User, add it back to the CSE maps. If it 10200 // already exists there, recursively merge the results together. 10201 AddModifiedNodeToCSEMaps(User); 10202 } 10203 10204 // If we just RAUW'd the root, take note. 10205 if (From == getRoot()) 10206 setRoot(To); 10207 } 10208 10209 namespace { 10210 10211 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10212 /// to record information about a use. 10213 struct UseMemo { 10214 SDNode *User; 10215 unsigned Index; 10216 SDUse *Use; 10217 }; 10218 10219 /// operator< - Sort Memos by User. 10220 bool operator<(const UseMemo &L, const UseMemo &R) { 10221 return (intptr_t)L.User < (intptr_t)R.User; 10222 } 10223 10224 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10225 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10226 /// the node already has been taken care of recursively. 10227 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10228 SmallVector<UseMemo, 4> &Uses; 10229 10230 void NodeDeleted(SDNode *N, SDNode *E) override { 10231 for (UseMemo &Memo : Uses) 10232 if (Memo.User == N) 10233 Memo.User = nullptr; 10234 } 10235 10236 public: 10237 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10238 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10239 }; 10240 10241 } // end anonymous namespace 10242 10243 bool SelectionDAG::calculateDivergence(SDNode *N) { 10244 if (TLI->isSDNodeAlwaysUniform(N)) { 10245 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 10246 "Conflicting divergence information!"); 10247 return false; 10248 } 10249 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 10250 return true; 10251 for (auto &Op : N->ops()) { 10252 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10253 return true; 10254 } 10255 return false; 10256 } 10257 10258 void SelectionDAG::updateDivergence(SDNode *N) { 10259 SmallVector<SDNode *, 16> Worklist(1, N); 10260 do { 10261 N = Worklist.pop_back_val(); 10262 bool IsDivergent = calculateDivergence(N); 10263 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10264 N->SDNodeBits.IsDivergent = IsDivergent; 10265 llvm::append_range(Worklist, N->uses()); 10266 } 10267 } while (!Worklist.empty()); 10268 } 10269 10270 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10271 DenseMap<SDNode *, unsigned> Degree; 10272 Order.reserve(AllNodes.size()); 10273 for (auto &N : allnodes()) { 10274 unsigned NOps = N.getNumOperands(); 10275 Degree[&N] = NOps; 10276 if (0 == NOps) 10277 Order.push_back(&N); 10278 } 10279 for (size_t I = 0; I != Order.size(); ++I) { 10280 SDNode *N = Order[I]; 10281 for (auto U : N->uses()) { 10282 unsigned &UnsortedOps = Degree[U]; 10283 if (0 == --UnsortedOps) 10284 Order.push_back(U); 10285 } 10286 } 10287 } 10288 10289 #ifndef NDEBUG 10290 void SelectionDAG::VerifyDAGDivergence() { 10291 std::vector<SDNode *> TopoOrder; 10292 CreateTopologicalOrder(TopoOrder); 10293 for (auto *N : TopoOrder) { 10294 assert(calculateDivergence(N) == N->isDivergent() && 10295 "Divergence bit inconsistency detected"); 10296 } 10297 } 10298 #endif 10299 10300 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10301 /// uses of other values produced by From.getNode() alone. The same value 10302 /// may appear in both the From and To list. The Deleted vector is 10303 /// handled the same way as for ReplaceAllUsesWith. 10304 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10305 const SDValue *To, 10306 unsigned Num){ 10307 // Handle the simple, trivial case efficiently. 10308 if (Num == 1) 10309 return ReplaceAllUsesOfValueWith(*From, *To); 10310 10311 transferDbgValues(*From, *To); 10312 10313 // Read up all the uses and make records of them. This helps 10314 // processing new uses that are introduced during the 10315 // replacement process. 10316 SmallVector<UseMemo, 4> Uses; 10317 for (unsigned i = 0; i != Num; ++i) { 10318 unsigned FromResNo = From[i].getResNo(); 10319 SDNode *FromNode = From[i].getNode(); 10320 for (SDNode::use_iterator UI = FromNode->use_begin(), 10321 E = FromNode->use_end(); UI != E; ++UI) { 10322 SDUse &Use = UI.getUse(); 10323 if (Use.getResNo() == FromResNo) { 10324 UseMemo Memo = { *UI, i, &Use }; 10325 Uses.push_back(Memo); 10326 } 10327 } 10328 } 10329 10330 // Sort the uses, so that all the uses from a given User are together. 10331 llvm::sort(Uses); 10332 RAUOVWUpdateListener Listener(*this, Uses); 10333 10334 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 10335 UseIndex != UseIndexEnd; ) { 10336 // We know that this user uses some value of From. If it is the right 10337 // value, update it. 10338 SDNode *User = Uses[UseIndex].User; 10339 // If the node has been deleted by recursive CSE updates when updating 10340 // another node, then just skip this entry. 10341 if (User == nullptr) { 10342 ++UseIndex; 10343 continue; 10344 } 10345 10346 // This node is about to morph, remove its old self from the CSE maps. 10347 RemoveNodeFromCSEMaps(User); 10348 10349 // The Uses array is sorted, so all the uses for a given User 10350 // are next to each other in the list. 10351 // To help reduce the number of CSE recomputations, process all 10352 // the uses of this user that we can find this way. 10353 do { 10354 unsigned i = Uses[UseIndex].Index; 10355 SDUse &Use = *Uses[UseIndex].Use; 10356 ++UseIndex; 10357 10358 Use.set(To[i]); 10359 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 10360 10361 // Now that we have modified User, add it back to the CSE maps. If it 10362 // already exists there, recursively merge the results together. 10363 AddModifiedNodeToCSEMaps(User); 10364 } 10365 } 10366 10367 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 10368 /// based on their topological order. It returns the maximum id and a vector 10369 /// of the SDNodes* in assigned order by reference. 10370 unsigned SelectionDAG::AssignTopologicalOrder() { 10371 unsigned DAGSize = 0; 10372 10373 // SortedPos tracks the progress of the algorithm. Nodes before it are 10374 // sorted, nodes after it are unsorted. When the algorithm completes 10375 // it is at the end of the list. 10376 allnodes_iterator SortedPos = allnodes_begin(); 10377 10378 // Visit all the nodes. Move nodes with no operands to the front of 10379 // the list immediately. Annotate nodes that do have operands with their 10380 // operand count. Before we do this, the Node Id fields of the nodes 10381 // may contain arbitrary values. After, the Node Id fields for nodes 10382 // before SortedPos will contain the topological sort index, and the 10383 // Node Id fields for nodes At SortedPos and after will contain the 10384 // count of outstanding operands. 10385 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 10386 checkForCycles(&N, this); 10387 unsigned Degree = N.getNumOperands(); 10388 if (Degree == 0) { 10389 // A node with no uses, add it to the result array immediately. 10390 N.setNodeId(DAGSize++); 10391 allnodes_iterator Q(&N); 10392 if (Q != SortedPos) 10393 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 10394 assert(SortedPos != AllNodes.end() && "Overran node list"); 10395 ++SortedPos; 10396 } else { 10397 // Temporarily use the Node Id as scratch space for the degree count. 10398 N.setNodeId(Degree); 10399 } 10400 } 10401 10402 // Visit all the nodes. As we iterate, move nodes into sorted order, 10403 // such that by the time the end is reached all nodes will be sorted. 10404 for (SDNode &Node : allnodes()) { 10405 SDNode *N = &Node; 10406 checkForCycles(N, this); 10407 // N is in sorted position, so all its uses have one less operand 10408 // that needs to be sorted. 10409 for (SDNode *P : N->uses()) { 10410 unsigned Degree = P->getNodeId(); 10411 assert(Degree != 0 && "Invalid node degree"); 10412 --Degree; 10413 if (Degree == 0) { 10414 // All of P's operands are sorted, so P may sorted now. 10415 P->setNodeId(DAGSize++); 10416 if (P->getIterator() != SortedPos) 10417 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 10418 assert(SortedPos != AllNodes.end() && "Overran node list"); 10419 ++SortedPos; 10420 } else { 10421 // Update P's outstanding operand count. 10422 P->setNodeId(Degree); 10423 } 10424 } 10425 if (Node.getIterator() == SortedPos) { 10426 #ifndef NDEBUG 10427 allnodes_iterator I(N); 10428 SDNode *S = &*++I; 10429 dbgs() << "Overran sorted position:\n"; 10430 S->dumprFull(this); dbgs() << "\n"; 10431 dbgs() << "Checking if this is due to cycles\n"; 10432 checkForCycles(this, true); 10433 #endif 10434 llvm_unreachable(nullptr); 10435 } 10436 } 10437 10438 assert(SortedPos == AllNodes.end() && 10439 "Topological sort incomplete!"); 10440 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 10441 "First node in topological sort is not the entry token!"); 10442 assert(AllNodes.front().getNodeId() == 0 && 10443 "First node in topological sort has non-zero id!"); 10444 assert(AllNodes.front().getNumOperands() == 0 && 10445 "First node in topological sort has operands!"); 10446 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 10447 "Last node in topologic sort has unexpected id!"); 10448 assert(AllNodes.back().use_empty() && 10449 "Last node in topologic sort has users!"); 10450 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 10451 return DAGSize; 10452 } 10453 10454 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 10455 /// value is produced by SD. 10456 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 10457 for (SDNode *SD : DB->getSDNodes()) { 10458 if (!SD) 10459 continue; 10460 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 10461 SD->setHasDebugValue(true); 10462 } 10463 DbgInfo->add(DB, isParameter); 10464 } 10465 10466 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 10467 10468 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 10469 SDValue NewMemOpChain) { 10470 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 10471 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 10472 // The new memory operation must have the same position as the old load in 10473 // terms of memory dependency. Create a TokenFactor for the old load and new 10474 // memory operation and update uses of the old load's output chain to use that 10475 // TokenFactor. 10476 if (OldChain == NewMemOpChain || OldChain.use_empty()) 10477 return NewMemOpChain; 10478 10479 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 10480 OldChain, NewMemOpChain); 10481 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 10482 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 10483 return TokenFactor; 10484 } 10485 10486 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 10487 SDValue NewMemOp) { 10488 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 10489 SDValue OldChain = SDValue(OldLoad, 1); 10490 SDValue NewMemOpChain = NewMemOp.getValue(1); 10491 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 10492 } 10493 10494 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 10495 Function **OutFunction) { 10496 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 10497 10498 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 10499 auto *Module = MF->getFunction().getParent(); 10500 auto *Function = Module->getFunction(Symbol); 10501 10502 if (OutFunction != nullptr) 10503 *OutFunction = Function; 10504 10505 if (Function != nullptr) { 10506 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 10507 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 10508 } 10509 10510 std::string ErrorStr; 10511 raw_string_ostream ErrorFormatter(ErrorStr); 10512 ErrorFormatter << "Undefined external symbol "; 10513 ErrorFormatter << '"' << Symbol << '"'; 10514 report_fatal_error(Twine(ErrorFormatter.str())); 10515 } 10516 10517 //===----------------------------------------------------------------------===// 10518 // SDNode Class 10519 //===----------------------------------------------------------------------===// 10520 10521 bool llvm::isNullConstant(SDValue V) { 10522 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10523 return Const != nullptr && Const->isZero(); 10524 } 10525 10526 bool llvm::isNullFPConstant(SDValue V) { 10527 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10528 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10529 } 10530 10531 bool llvm::isAllOnesConstant(SDValue V) { 10532 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10533 return Const != nullptr && Const->isAllOnes(); 10534 } 10535 10536 bool llvm::isOneConstant(SDValue V) { 10537 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10538 return Const != nullptr && Const->isOne(); 10539 } 10540 10541 bool llvm::isMinSignedConstant(SDValue V) { 10542 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10543 return Const != nullptr && Const->isMinSignedValue(); 10544 } 10545 10546 SDValue llvm::peekThroughBitcasts(SDValue V) { 10547 while (V.getOpcode() == ISD::BITCAST) 10548 V = V.getOperand(0); 10549 return V; 10550 } 10551 10552 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10553 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10554 V = V.getOperand(0); 10555 return V; 10556 } 10557 10558 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10559 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10560 V = V.getOperand(0); 10561 return V; 10562 } 10563 10564 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10565 if (V.getOpcode() != ISD::XOR) 10566 return false; 10567 V = peekThroughBitcasts(V.getOperand(1)); 10568 unsigned NumBits = V.getScalarValueSizeInBits(); 10569 ConstantSDNode *C = 10570 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10571 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10572 } 10573 10574 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10575 bool AllowTruncation) { 10576 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10577 return CN; 10578 10579 // SplatVectors can truncate their operands. Ignore that case here unless 10580 // AllowTruncation is set. 10581 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10582 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10583 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10584 EVT CVT = CN->getValueType(0); 10585 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10586 if (AllowTruncation || CVT == VecEltVT) 10587 return CN; 10588 } 10589 } 10590 10591 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10592 BitVector UndefElements; 10593 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10594 10595 // BuildVectors can truncate their operands. Ignore that case here unless 10596 // AllowTruncation is set. 10597 if (CN && (UndefElements.none() || AllowUndefs)) { 10598 EVT CVT = CN->getValueType(0); 10599 EVT NSVT = N.getValueType().getScalarType(); 10600 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10601 if (AllowTruncation || (CVT == NSVT)) 10602 return CN; 10603 } 10604 } 10605 10606 return nullptr; 10607 } 10608 10609 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10610 bool AllowUndefs, 10611 bool AllowTruncation) { 10612 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10613 return CN; 10614 10615 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10616 BitVector UndefElements; 10617 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10618 10619 // BuildVectors can truncate their operands. Ignore that case here unless 10620 // AllowTruncation is set. 10621 if (CN && (UndefElements.none() || AllowUndefs)) { 10622 EVT CVT = CN->getValueType(0); 10623 EVT NSVT = N.getValueType().getScalarType(); 10624 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10625 if (AllowTruncation || (CVT == NSVT)) 10626 return CN; 10627 } 10628 } 10629 10630 return nullptr; 10631 } 10632 10633 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10634 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10635 return CN; 10636 10637 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10638 BitVector UndefElements; 10639 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10640 if (CN && (UndefElements.none() || AllowUndefs)) 10641 return CN; 10642 } 10643 10644 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10645 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10646 return CN; 10647 10648 return nullptr; 10649 } 10650 10651 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10652 const APInt &DemandedElts, 10653 bool AllowUndefs) { 10654 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10655 return CN; 10656 10657 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10658 BitVector UndefElements; 10659 ConstantFPSDNode *CN = 10660 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10661 if (CN && (UndefElements.none() || AllowUndefs)) 10662 return CN; 10663 } 10664 10665 return nullptr; 10666 } 10667 10668 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10669 // TODO: may want to use peekThroughBitcast() here. 10670 ConstantSDNode *C = 10671 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10672 return C && C->isZero(); 10673 } 10674 10675 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10676 ConstantSDNode *C = 10677 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true); 10678 return C && C->isOne(); 10679 } 10680 10681 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10682 N = peekThroughBitcasts(N); 10683 unsigned BitWidth = N.getScalarValueSizeInBits(); 10684 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10685 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10686 } 10687 10688 HandleSDNode::~HandleSDNode() { 10689 DropOperands(); 10690 } 10691 10692 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10693 const DebugLoc &DL, 10694 const GlobalValue *GA, EVT VT, 10695 int64_t o, unsigned TF) 10696 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10697 TheGlobal = GA; 10698 } 10699 10700 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10701 EVT VT, unsigned SrcAS, 10702 unsigned DestAS) 10703 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10704 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10705 10706 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10707 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10708 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10709 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10710 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10711 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10712 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10713 10714 // We check here that the size of the memory operand fits within the size of 10715 // the MMO. This is because the MMO might indicate only a possible address 10716 // range instead of specifying the affected memory addresses precisely. 10717 // TODO: Make MachineMemOperands aware of scalable vectors. 10718 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10719 "Size mismatch!"); 10720 } 10721 10722 /// Profile - Gather unique data for the node. 10723 /// 10724 void SDNode::Profile(FoldingSetNodeID &ID) const { 10725 AddNodeIDNode(ID, this); 10726 } 10727 10728 namespace { 10729 10730 struct EVTArray { 10731 std::vector<EVT> VTs; 10732 10733 EVTArray() { 10734 VTs.reserve(MVT::VALUETYPE_SIZE); 10735 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10736 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10737 } 10738 }; 10739 10740 } // end anonymous namespace 10741 10742 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10743 static ManagedStatic<EVTArray> SimpleVTArray; 10744 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10745 10746 /// getValueTypeList - Return a pointer to the specified value type. 10747 /// 10748 const EVT *SDNode::getValueTypeList(EVT VT) { 10749 if (VT.isExtended()) { 10750 sys::SmartScopedLock<true> Lock(*VTMutex); 10751 return &(*EVTs->insert(VT).first); 10752 } 10753 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10754 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10755 } 10756 10757 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10758 /// indicated value. This method ignores uses of other values defined by this 10759 /// operation. 10760 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10761 assert(Value < getNumValues() && "Bad value!"); 10762 10763 // TODO: Only iterate over uses of a given value of the node 10764 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10765 if (UI.getUse().getResNo() == Value) { 10766 if (NUses == 0) 10767 return false; 10768 --NUses; 10769 } 10770 } 10771 10772 // Found exactly the right number of uses? 10773 return NUses == 0; 10774 } 10775 10776 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10777 /// value. This method ignores uses of other values defined by this operation. 10778 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10779 assert(Value < getNumValues() && "Bad value!"); 10780 10781 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10782 if (UI.getUse().getResNo() == Value) 10783 return true; 10784 10785 return false; 10786 } 10787 10788 /// isOnlyUserOf - Return true if this node is the only use of N. 10789 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10790 bool Seen = false; 10791 for (const SDNode *User : N->uses()) { 10792 if (User == this) 10793 Seen = true; 10794 else 10795 return false; 10796 } 10797 10798 return Seen; 10799 } 10800 10801 /// Return true if the only users of N are contained in Nodes. 10802 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10803 bool Seen = false; 10804 for (const SDNode *User : N->uses()) { 10805 if (llvm::is_contained(Nodes, User)) 10806 Seen = true; 10807 else 10808 return false; 10809 } 10810 10811 return Seen; 10812 } 10813 10814 /// isOperand - Return true if this node is an operand of N. 10815 bool SDValue::isOperandOf(const SDNode *N) const { 10816 return is_contained(N->op_values(), *this); 10817 } 10818 10819 bool SDNode::isOperandOf(const SDNode *N) const { 10820 return any_of(N->op_values(), 10821 [this](SDValue Op) { return this == Op.getNode(); }); 10822 } 10823 10824 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10825 /// be a chain) reaches the specified operand without crossing any 10826 /// side-effecting instructions on any chain path. In practice, this looks 10827 /// through token factors and non-volatile loads. In order to remain efficient, 10828 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10829 /// 10830 /// Note that we only need to examine chains when we're searching for 10831 /// side-effects; SelectionDAG requires that all side-effects are represented 10832 /// by chains, even if another operand would force a specific ordering. This 10833 /// constraint is necessary to allow transformations like splitting loads. 10834 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10835 unsigned Depth) const { 10836 if (*this == Dest) return true; 10837 10838 // Don't search too deeply, we just want to be able to see through 10839 // TokenFactor's etc. 10840 if (Depth == 0) return false; 10841 10842 // If this is a token factor, all inputs to the TF happen in parallel. 10843 if (getOpcode() == ISD::TokenFactor) { 10844 // First, try a shallow search. 10845 if (is_contained((*this)->ops(), Dest)) { 10846 // We found the chain we want as an operand of this TokenFactor. 10847 // Essentially, we reach the chain without side-effects if we could 10848 // serialize the TokenFactor into a simple chain of operations with 10849 // Dest as the last operation. This is automatically true if the 10850 // chain has one use: there are no other ordering constraints. 10851 // If the chain has more than one use, we give up: some other 10852 // use of Dest might force a side-effect between Dest and the current 10853 // node. 10854 if (Dest.hasOneUse()) 10855 return true; 10856 } 10857 // Next, try a deep search: check whether every operand of the TokenFactor 10858 // reaches Dest. 10859 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10860 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10861 }); 10862 } 10863 10864 // Loads don't have side effects, look through them. 10865 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10866 if (Ld->isUnordered()) 10867 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10868 } 10869 return false; 10870 } 10871 10872 bool SDNode::hasPredecessor(const SDNode *N) const { 10873 SmallPtrSet<const SDNode *, 32> Visited; 10874 SmallVector<const SDNode *, 16> Worklist; 10875 Worklist.push_back(this); 10876 return hasPredecessorHelper(N, Visited, Worklist); 10877 } 10878 10879 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10880 this->Flags.intersectWith(Flags); 10881 } 10882 10883 SDValue 10884 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10885 ArrayRef<ISD::NodeType> CandidateBinOps, 10886 bool AllowPartials) { 10887 // The pattern must end in an extract from index 0. 10888 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10889 !isNullConstant(Extract->getOperand(1))) 10890 return SDValue(); 10891 10892 // Match against one of the candidate binary ops. 10893 SDValue Op = Extract->getOperand(0); 10894 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10895 return Op.getOpcode() == unsigned(BinOp); 10896 })) 10897 return SDValue(); 10898 10899 // Floating-point reductions may require relaxed constraints on the final step 10900 // of the reduction because they may reorder intermediate operations. 10901 unsigned CandidateBinOp = Op.getOpcode(); 10902 if (Op.getValueType().isFloatingPoint()) { 10903 SDNodeFlags Flags = Op->getFlags(); 10904 switch (CandidateBinOp) { 10905 case ISD::FADD: 10906 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10907 return SDValue(); 10908 break; 10909 default: 10910 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10911 } 10912 } 10913 10914 // Matching failed - attempt to see if we did enough stages that a partial 10915 // reduction from a subvector is possible. 10916 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10917 if (!AllowPartials || !Op) 10918 return SDValue(); 10919 EVT OpVT = Op.getValueType(); 10920 EVT OpSVT = OpVT.getScalarType(); 10921 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10922 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10923 return SDValue(); 10924 BinOp = (ISD::NodeType)CandidateBinOp; 10925 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10926 getVectorIdxConstant(0, SDLoc(Op))); 10927 }; 10928 10929 // At each stage, we're looking for something that looks like: 10930 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10931 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10932 // i32 undef, i32 undef, i32 undef, i32 undef> 10933 // %a = binop <8 x i32> %op, %s 10934 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10935 // we expect something like: 10936 // <4,5,6,7,u,u,u,u> 10937 // <2,3,u,u,u,u,u,u> 10938 // <1,u,u,u,u,u,u,u> 10939 // While a partial reduction match would be: 10940 // <2,3,u,u,u,u,u,u> 10941 // <1,u,u,u,u,u,u,u> 10942 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10943 SDValue PrevOp; 10944 for (unsigned i = 0; i < Stages; ++i) { 10945 unsigned MaskEnd = (1 << i); 10946 10947 if (Op.getOpcode() != CandidateBinOp) 10948 return PartialReduction(PrevOp, MaskEnd); 10949 10950 SDValue Op0 = Op.getOperand(0); 10951 SDValue Op1 = Op.getOperand(1); 10952 10953 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10954 if (Shuffle) { 10955 Op = Op1; 10956 } else { 10957 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10958 Op = Op0; 10959 } 10960 10961 // The first operand of the shuffle should be the same as the other operand 10962 // of the binop. 10963 if (!Shuffle || Shuffle->getOperand(0) != Op) 10964 return PartialReduction(PrevOp, MaskEnd); 10965 10966 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10967 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10968 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10969 return PartialReduction(PrevOp, MaskEnd); 10970 10971 PrevOp = Op; 10972 } 10973 10974 // Handle subvector reductions, which tend to appear after the shuffle 10975 // reduction stages. 10976 while (Op.getOpcode() == CandidateBinOp) { 10977 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10978 SDValue Op0 = Op.getOperand(0); 10979 SDValue Op1 = Op.getOperand(1); 10980 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10981 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10982 Op0.getOperand(0) != Op1.getOperand(0)) 10983 break; 10984 SDValue Src = Op0.getOperand(0); 10985 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10986 if (NumSrcElts != (2 * NumElts)) 10987 break; 10988 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10989 Op1.getConstantOperandAPInt(1) == NumElts) && 10990 !(Op1.getConstantOperandAPInt(1) == 0 && 10991 Op0.getConstantOperandAPInt(1) == NumElts)) 10992 break; 10993 Op = Src; 10994 } 10995 10996 BinOp = (ISD::NodeType)CandidateBinOp; 10997 return Op; 10998 } 10999 11000 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 11001 assert(N->getNumValues() == 1 && 11002 "Can't unroll a vector with multiple results!"); 11003 11004 EVT VT = N->getValueType(0); 11005 unsigned NE = VT.getVectorNumElements(); 11006 EVT EltVT = VT.getVectorElementType(); 11007 SDLoc dl(N); 11008 11009 SmallVector<SDValue, 8> Scalars; 11010 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 11011 11012 // If ResNE is 0, fully unroll the vector op. 11013 if (ResNE == 0) 11014 ResNE = NE; 11015 else if (NE > ResNE) 11016 NE = ResNE; 11017 11018 unsigned i; 11019 for (i= 0; i != NE; ++i) { 11020 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 11021 SDValue Operand = N->getOperand(j); 11022 EVT OperandVT = Operand.getValueType(); 11023 if (OperandVT.isVector()) { 11024 // A vector operand; extract a single element. 11025 EVT OperandEltVT = OperandVT.getVectorElementType(); 11026 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 11027 Operand, getVectorIdxConstant(i, dl)); 11028 } else { 11029 // A scalar operand; just use it as is. 11030 Operands[j] = Operand; 11031 } 11032 } 11033 11034 switch (N->getOpcode()) { 11035 default: { 11036 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 11037 N->getFlags())); 11038 break; 11039 } 11040 case ISD::VSELECT: 11041 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 11042 break; 11043 case ISD::SHL: 11044 case ISD::SRA: 11045 case ISD::SRL: 11046 case ISD::ROTL: 11047 case ISD::ROTR: 11048 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 11049 getShiftAmountOperand(Operands[0].getValueType(), 11050 Operands[1]))); 11051 break; 11052 case ISD::SIGN_EXTEND_INREG: { 11053 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 11054 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 11055 Operands[0], 11056 getValueType(ExtVT))); 11057 } 11058 } 11059 } 11060 11061 for (; i < ResNE; ++i) 11062 Scalars.push_back(getUNDEF(EltVT)); 11063 11064 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 11065 return getBuildVector(VecVT, dl, Scalars); 11066 } 11067 11068 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 11069 SDNode *N, unsigned ResNE) { 11070 unsigned Opcode = N->getOpcode(); 11071 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 11072 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 11073 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 11074 "Expected an overflow opcode"); 11075 11076 EVT ResVT = N->getValueType(0); 11077 EVT OvVT = N->getValueType(1); 11078 EVT ResEltVT = ResVT.getVectorElementType(); 11079 EVT OvEltVT = OvVT.getVectorElementType(); 11080 SDLoc dl(N); 11081 11082 // If ResNE is 0, fully unroll the vector op. 11083 unsigned NE = ResVT.getVectorNumElements(); 11084 if (ResNE == 0) 11085 ResNE = NE; 11086 else if (NE > ResNE) 11087 NE = ResNE; 11088 11089 SmallVector<SDValue, 8> LHSScalars; 11090 SmallVector<SDValue, 8> RHSScalars; 11091 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 11092 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 11093 11094 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 11095 SDVTList VTs = getVTList(ResEltVT, SVT); 11096 SmallVector<SDValue, 8> ResScalars; 11097 SmallVector<SDValue, 8> OvScalars; 11098 for (unsigned i = 0; i < NE; ++i) { 11099 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 11100 SDValue Ov = 11101 getSelect(dl, OvEltVT, Res.getValue(1), 11102 getBoolConstant(true, dl, OvEltVT, ResVT), 11103 getConstant(0, dl, OvEltVT)); 11104 11105 ResScalars.push_back(Res); 11106 OvScalars.push_back(Ov); 11107 } 11108 11109 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 11110 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 11111 11112 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 11113 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 11114 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 11115 getBuildVector(NewOvVT, dl, OvScalars)); 11116 } 11117 11118 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 11119 LoadSDNode *Base, 11120 unsigned Bytes, 11121 int Dist) const { 11122 if (LD->isVolatile() || Base->isVolatile()) 11123 return false; 11124 // TODO: probably too restrictive for atomics, revisit 11125 if (!LD->isSimple()) 11126 return false; 11127 if (LD->isIndexed() || Base->isIndexed()) 11128 return false; 11129 if (LD->getChain() != Base->getChain()) 11130 return false; 11131 EVT VT = LD->getValueType(0); 11132 if (VT.getSizeInBits() / 8 != Bytes) 11133 return false; 11134 11135 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 11136 auto LocDecomp = BaseIndexOffset::match(LD, *this); 11137 11138 int64_t Offset = 0; 11139 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 11140 return (Dist * Bytes == Offset); 11141 return false; 11142 } 11143 11144 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 11145 /// if it cannot be inferred. 11146 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 11147 // If this is a GlobalAddress + cst, return the alignment. 11148 const GlobalValue *GV = nullptr; 11149 int64_t GVOffset = 0; 11150 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 11151 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 11152 KnownBits Known(PtrWidth); 11153 llvm::computeKnownBits(GV, Known, getDataLayout()); 11154 unsigned AlignBits = Known.countMinTrailingZeros(); 11155 if (AlignBits) 11156 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11157 } 11158 11159 // If this is a direct reference to a stack slot, use information about the 11160 // stack slot's alignment. 11161 int FrameIdx = INT_MIN; 11162 int64_t FrameOffset = 0; 11163 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11164 FrameIdx = FI->getIndex(); 11165 } else if (isBaseWithConstantOffset(Ptr) && 11166 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11167 // Handle FI+Cst 11168 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11169 FrameOffset = Ptr.getConstantOperandVal(1); 11170 } 11171 11172 if (FrameIdx != INT_MIN) { 11173 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11174 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11175 } 11176 11177 return None; 11178 } 11179 11180 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11181 /// which is split (or expanded) into two not necessarily identical pieces. 11182 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11183 // Currently all types are split in half. 11184 EVT LoVT, HiVT; 11185 if (!VT.isVector()) 11186 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11187 else 11188 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11189 11190 return std::make_pair(LoVT, HiVT); 11191 } 11192 11193 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11194 /// type, dependent on an enveloping VT that has been split into two identical 11195 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11196 std::pair<EVT, EVT> 11197 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11198 bool *HiIsEmpty) const { 11199 EVT EltTp = VT.getVectorElementType(); 11200 // Examples: 11201 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11202 // custom VL=9 with enveloping VL=8/8 yields 8/1 11203 // custom VL=10 with enveloping VL=8/8 yields 8/2 11204 // etc. 11205 ElementCount VTNumElts = VT.getVectorElementCount(); 11206 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11207 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11208 "Mixing fixed width and scalable vectors when enveloping a type"); 11209 EVT LoVT, HiVT; 11210 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11211 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11212 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11213 *HiIsEmpty = false; 11214 } else { 11215 // Flag that hi type has zero storage size, but return split envelop type 11216 // (this would be easier if vector types with zero elements were allowed). 11217 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11218 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11219 *HiIsEmpty = true; 11220 } 11221 return std::make_pair(LoVT, HiVT); 11222 } 11223 11224 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11225 /// low/high part. 11226 std::pair<SDValue, SDValue> 11227 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11228 const EVT &HiVT) { 11229 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 11230 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 11231 "Splitting vector with an invalid mixture of fixed and scalable " 11232 "vector types"); 11233 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 11234 N.getValueType().getVectorMinNumElements() && 11235 "More vector elements requested than available!"); 11236 SDValue Lo, Hi; 11237 Lo = 11238 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 11239 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 11240 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 11241 // IDX with the runtime scaling factor of the result vector type. For 11242 // fixed-width result vectors, that runtime scaling factor is 1. 11243 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 11244 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 11245 return std::make_pair(Lo, Hi); 11246 } 11247 11248 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 11249 const SDLoc &DL) { 11250 // Split the vector length parameter. 11251 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 11252 EVT VT = N.getValueType(); 11253 assert(VecVT.getVectorElementCount().isKnownEven() && 11254 "Expecting the mask to be an evenly-sized vector"); 11255 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 11256 SDValue HalfNumElts = 11257 VecVT.isFixedLengthVector() 11258 ? getConstant(HalfMinNumElts, DL, VT) 11259 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 11260 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 11261 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 11262 return std::make_pair(Lo, Hi); 11263 } 11264 11265 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 11266 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 11267 EVT VT = N.getValueType(); 11268 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 11269 NextPowerOf2(VT.getVectorNumElements())); 11270 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 11271 getVectorIdxConstant(0, DL)); 11272 } 11273 11274 void SelectionDAG::ExtractVectorElements(SDValue Op, 11275 SmallVectorImpl<SDValue> &Args, 11276 unsigned Start, unsigned Count, 11277 EVT EltVT) { 11278 EVT VT = Op.getValueType(); 11279 if (Count == 0) 11280 Count = VT.getVectorNumElements(); 11281 if (EltVT == EVT()) 11282 EltVT = VT.getVectorElementType(); 11283 SDLoc SL(Op); 11284 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 11285 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 11286 getVectorIdxConstant(i, SL))); 11287 } 11288 } 11289 11290 // getAddressSpace - Return the address space this GlobalAddress belongs to. 11291 unsigned GlobalAddressSDNode::getAddressSpace() const { 11292 return getGlobal()->getType()->getAddressSpace(); 11293 } 11294 11295 Type *ConstantPoolSDNode::getType() const { 11296 if (isMachineConstantPoolEntry()) 11297 return Val.MachineCPVal->getType(); 11298 return Val.ConstVal->getType(); 11299 } 11300 11301 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 11302 unsigned &SplatBitSize, 11303 bool &HasAnyUndefs, 11304 unsigned MinSplatBits, 11305 bool IsBigEndian) const { 11306 EVT VT = getValueType(0); 11307 assert(VT.isVector() && "Expected a vector type"); 11308 unsigned VecWidth = VT.getSizeInBits(); 11309 if (MinSplatBits > VecWidth) 11310 return false; 11311 11312 // FIXME: The widths are based on this node's type, but build vectors can 11313 // truncate their operands. 11314 SplatValue = APInt(VecWidth, 0); 11315 SplatUndef = APInt(VecWidth, 0); 11316 11317 // Get the bits. Bits with undefined values (when the corresponding element 11318 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 11319 // in SplatValue. If any of the values are not constant, give up and return 11320 // false. 11321 unsigned int NumOps = getNumOperands(); 11322 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 11323 unsigned EltWidth = VT.getScalarSizeInBits(); 11324 11325 for (unsigned j = 0; j < NumOps; ++j) { 11326 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 11327 SDValue OpVal = getOperand(i); 11328 unsigned BitPos = j * EltWidth; 11329 11330 if (OpVal.isUndef()) 11331 SplatUndef.setBits(BitPos, BitPos + EltWidth); 11332 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 11333 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 11334 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 11335 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 11336 else 11337 return false; 11338 } 11339 11340 // The build_vector is all constants or undefs. Find the smallest element 11341 // size that splats the vector. 11342 HasAnyUndefs = (SplatUndef != 0); 11343 11344 // FIXME: This does not work for vectors with elements less than 8 bits. 11345 while (VecWidth > 8) { 11346 unsigned HalfSize = VecWidth / 2; 11347 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 11348 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 11349 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 11350 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 11351 11352 // If the two halves do not match (ignoring undef bits), stop here. 11353 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 11354 MinSplatBits > HalfSize) 11355 break; 11356 11357 SplatValue = HighValue | LowValue; 11358 SplatUndef = HighUndef & LowUndef; 11359 11360 VecWidth = HalfSize; 11361 } 11362 11363 SplatBitSize = VecWidth; 11364 return true; 11365 } 11366 11367 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 11368 BitVector *UndefElements) const { 11369 unsigned NumOps = getNumOperands(); 11370 if (UndefElements) { 11371 UndefElements->clear(); 11372 UndefElements->resize(NumOps); 11373 } 11374 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11375 if (!DemandedElts) 11376 return SDValue(); 11377 SDValue Splatted; 11378 for (unsigned i = 0; i != NumOps; ++i) { 11379 if (!DemandedElts[i]) 11380 continue; 11381 SDValue Op = getOperand(i); 11382 if (Op.isUndef()) { 11383 if (UndefElements) 11384 (*UndefElements)[i] = true; 11385 } else if (!Splatted) { 11386 Splatted = Op; 11387 } else if (Splatted != Op) { 11388 return SDValue(); 11389 } 11390 } 11391 11392 if (!Splatted) { 11393 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 11394 assert(getOperand(FirstDemandedIdx).isUndef() && 11395 "Can only have a splat without a constant for all undefs."); 11396 return getOperand(FirstDemandedIdx); 11397 } 11398 11399 return Splatted; 11400 } 11401 11402 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 11403 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11404 return getSplatValue(DemandedElts, UndefElements); 11405 } 11406 11407 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 11408 SmallVectorImpl<SDValue> &Sequence, 11409 BitVector *UndefElements) const { 11410 unsigned NumOps = getNumOperands(); 11411 Sequence.clear(); 11412 if (UndefElements) { 11413 UndefElements->clear(); 11414 UndefElements->resize(NumOps); 11415 } 11416 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11417 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 11418 return false; 11419 11420 // Set the undefs even if we don't find a sequence (like getSplatValue). 11421 if (UndefElements) 11422 for (unsigned I = 0; I != NumOps; ++I) 11423 if (DemandedElts[I] && getOperand(I).isUndef()) 11424 (*UndefElements)[I] = true; 11425 11426 // Iteratively widen the sequence length looking for repetitions. 11427 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 11428 Sequence.append(SeqLen, SDValue()); 11429 for (unsigned I = 0; I != NumOps; ++I) { 11430 if (!DemandedElts[I]) 11431 continue; 11432 SDValue &SeqOp = Sequence[I % SeqLen]; 11433 SDValue Op = getOperand(I); 11434 if (Op.isUndef()) { 11435 if (!SeqOp) 11436 SeqOp = Op; 11437 continue; 11438 } 11439 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 11440 Sequence.clear(); 11441 break; 11442 } 11443 SeqOp = Op; 11444 } 11445 if (!Sequence.empty()) 11446 return true; 11447 } 11448 11449 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 11450 return false; 11451 } 11452 11453 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 11454 BitVector *UndefElements) const { 11455 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11456 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 11457 } 11458 11459 ConstantSDNode * 11460 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 11461 BitVector *UndefElements) const { 11462 return dyn_cast_or_null<ConstantSDNode>( 11463 getSplatValue(DemandedElts, UndefElements)); 11464 } 11465 11466 ConstantSDNode * 11467 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 11468 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 11469 } 11470 11471 ConstantFPSDNode * 11472 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 11473 BitVector *UndefElements) const { 11474 return dyn_cast_or_null<ConstantFPSDNode>( 11475 getSplatValue(DemandedElts, UndefElements)); 11476 } 11477 11478 ConstantFPSDNode * 11479 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 11480 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 11481 } 11482 11483 int32_t 11484 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 11485 uint32_t BitWidth) const { 11486 if (ConstantFPSDNode *CN = 11487 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 11488 bool IsExact; 11489 APSInt IntVal(BitWidth); 11490 const APFloat &APF = CN->getValueAPF(); 11491 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 11492 APFloat::opOK || 11493 !IsExact) 11494 return -1; 11495 11496 return IntVal.exactLogBase2(); 11497 } 11498 return -1; 11499 } 11500 11501 bool BuildVectorSDNode::getConstantRawBits( 11502 bool IsLittleEndian, unsigned DstEltSizeInBits, 11503 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 11504 // Early-out if this contains anything but Undef/Constant/ConstantFP. 11505 if (!isConstant()) 11506 return false; 11507 11508 unsigned NumSrcOps = getNumOperands(); 11509 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 11510 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11511 "Invalid bitcast scale"); 11512 11513 // Extract raw src bits. 11514 SmallVector<APInt> SrcBitElements(NumSrcOps, 11515 APInt::getNullValue(SrcEltSizeInBits)); 11516 BitVector SrcUndeElements(NumSrcOps, false); 11517 11518 for (unsigned I = 0; I != NumSrcOps; ++I) { 11519 SDValue Op = getOperand(I); 11520 if (Op.isUndef()) { 11521 SrcUndeElements.set(I); 11522 continue; 11523 } 11524 auto *CInt = dyn_cast<ConstantSDNode>(Op); 11525 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 11526 assert((CInt || CFP) && "Unknown constant"); 11527 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits) 11528 : CFP->getValueAPF().bitcastToAPInt(); 11529 } 11530 11531 // Recast to dst width. 11532 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11533 SrcBitElements, UndefElements, SrcUndeElements); 11534 return true; 11535 } 11536 11537 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11538 unsigned DstEltSizeInBits, 11539 SmallVectorImpl<APInt> &DstBitElements, 11540 ArrayRef<APInt> SrcBitElements, 11541 BitVector &DstUndefElements, 11542 const BitVector &SrcUndefElements) { 11543 unsigned NumSrcOps = SrcBitElements.size(); 11544 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11545 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11546 "Invalid bitcast scale"); 11547 assert(NumSrcOps == SrcUndefElements.size() && 11548 "Vector size mismatch"); 11549 11550 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11551 DstUndefElements.clear(); 11552 DstUndefElements.resize(NumDstOps, false); 11553 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11554 11555 // Concatenate src elements constant bits together into dst element. 11556 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11557 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11558 for (unsigned I = 0; I != NumDstOps; ++I) { 11559 DstUndefElements.set(I); 11560 APInt &DstBits = DstBitElements[I]; 11561 for (unsigned J = 0; J != Scale; ++J) { 11562 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11563 if (SrcUndefElements[Idx]) 11564 continue; 11565 DstUndefElements.reset(I); 11566 const APInt &SrcBits = SrcBitElements[Idx]; 11567 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11568 "Illegal constant bitwidths"); 11569 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11570 } 11571 } 11572 return; 11573 } 11574 11575 // Split src element constant bits into dst elements. 11576 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11577 for (unsigned I = 0; I != NumSrcOps; ++I) { 11578 if (SrcUndefElements[I]) { 11579 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11580 continue; 11581 } 11582 const APInt &SrcBits = SrcBitElements[I]; 11583 for (unsigned J = 0; J != Scale; ++J) { 11584 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11585 APInt &DstBits = DstBitElements[Idx]; 11586 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11587 } 11588 } 11589 } 11590 11591 bool BuildVectorSDNode::isConstant() const { 11592 for (const SDValue &Op : op_values()) { 11593 unsigned Opc = Op.getOpcode(); 11594 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11595 return false; 11596 } 11597 return true; 11598 } 11599 11600 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11601 // Find the first non-undef value in the shuffle mask. 11602 unsigned i, e; 11603 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11604 /* search */; 11605 11606 // If all elements are undefined, this shuffle can be considered a splat 11607 // (although it should eventually get simplified away completely). 11608 if (i == e) 11609 return true; 11610 11611 // Make sure all remaining elements are either undef or the same as the first 11612 // non-undef value. 11613 for (int Idx = Mask[i]; i != e; ++i) 11614 if (Mask[i] >= 0 && Mask[i] != Idx) 11615 return false; 11616 return true; 11617 } 11618 11619 // Returns the SDNode if it is a constant integer BuildVector 11620 // or constant integer. 11621 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11622 if (isa<ConstantSDNode>(N)) 11623 return N.getNode(); 11624 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11625 return N.getNode(); 11626 // Treat a GlobalAddress supporting constant offset folding as a 11627 // constant integer. 11628 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11629 if (GA->getOpcode() == ISD::GlobalAddress && 11630 TLI->isOffsetFoldingLegal(GA)) 11631 return GA; 11632 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11633 isa<ConstantSDNode>(N.getOperand(0))) 11634 return N.getNode(); 11635 return nullptr; 11636 } 11637 11638 // Returns the SDNode if it is a constant float BuildVector 11639 // or constant float. 11640 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11641 if (isa<ConstantFPSDNode>(N)) 11642 return N.getNode(); 11643 11644 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11645 return N.getNode(); 11646 11647 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11648 isa<ConstantFPSDNode>(N.getOperand(0))) 11649 return N.getNode(); 11650 11651 return nullptr; 11652 } 11653 11654 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11655 assert(!Node->OperandList && "Node already has operands"); 11656 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11657 "too many operands to fit into SDNode"); 11658 SDUse *Ops = OperandRecycler.allocate( 11659 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11660 11661 bool IsDivergent = false; 11662 for (unsigned I = 0; I != Vals.size(); ++I) { 11663 Ops[I].setUser(Node); 11664 Ops[I].setInitial(Vals[I]); 11665 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11666 IsDivergent |= Ops[I].getNode()->isDivergent(); 11667 } 11668 Node->NumOperands = Vals.size(); 11669 Node->OperandList = Ops; 11670 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11671 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11672 Node->SDNodeBits.IsDivergent = IsDivergent; 11673 } 11674 checkForCycles(Node); 11675 } 11676 11677 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11678 SmallVectorImpl<SDValue> &Vals) { 11679 size_t Limit = SDNode::getMaxNumOperands(); 11680 while (Vals.size() > Limit) { 11681 unsigned SliceIdx = Vals.size() - Limit; 11682 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11683 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11684 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11685 Vals.emplace_back(NewTF); 11686 } 11687 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11688 } 11689 11690 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11691 EVT VT, SDNodeFlags Flags) { 11692 switch (Opcode) { 11693 default: 11694 return SDValue(); 11695 case ISD::ADD: 11696 case ISD::OR: 11697 case ISD::XOR: 11698 case ISD::UMAX: 11699 return getConstant(0, DL, VT); 11700 case ISD::MUL: 11701 return getConstant(1, DL, VT); 11702 case ISD::AND: 11703 case ISD::UMIN: 11704 return getAllOnesConstant(DL, VT); 11705 case ISD::SMAX: 11706 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11707 case ISD::SMIN: 11708 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11709 case ISD::FADD: 11710 return getConstantFP(-0.0, DL, VT); 11711 case ISD::FMUL: 11712 return getConstantFP(1.0, DL, VT); 11713 case ISD::FMINNUM: 11714 case ISD::FMAXNUM: { 11715 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11716 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11717 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11718 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11719 APFloat::getLargest(Semantics); 11720 if (Opcode == ISD::FMAXNUM) 11721 NeutralAF.changeSign(); 11722 11723 return getConstantFP(NeutralAF, DL, VT); 11724 } 11725 } 11726 } 11727 11728 #ifndef NDEBUG 11729 static void checkForCyclesHelper(const SDNode *N, 11730 SmallPtrSetImpl<const SDNode*> &Visited, 11731 SmallPtrSetImpl<const SDNode*> &Checked, 11732 const llvm::SelectionDAG *DAG) { 11733 // If this node has already been checked, don't check it again. 11734 if (Checked.count(N)) 11735 return; 11736 11737 // If a node has already been visited on this depth-first walk, reject it as 11738 // a cycle. 11739 if (!Visited.insert(N).second) { 11740 errs() << "Detected cycle in SelectionDAG\n"; 11741 dbgs() << "Offending node:\n"; 11742 N->dumprFull(DAG); dbgs() << "\n"; 11743 abort(); 11744 } 11745 11746 for (const SDValue &Op : N->op_values()) 11747 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11748 11749 Checked.insert(N); 11750 Visited.erase(N); 11751 } 11752 #endif 11753 11754 void llvm::checkForCycles(const llvm::SDNode *N, 11755 const llvm::SelectionDAG *DAG, 11756 bool force) { 11757 #ifndef NDEBUG 11758 bool check = force; 11759 #ifdef EXPENSIVE_CHECKS 11760 check = true; 11761 #endif // EXPENSIVE_CHECKS 11762 if (check) { 11763 assert(N && "Checking nonexistent SDNode"); 11764 SmallPtrSet<const SDNode*, 32> visited; 11765 SmallPtrSet<const SDNode*, 32> checked; 11766 checkForCyclesHelper(N, visited, checked, DAG); 11767 } 11768 #endif // !NDEBUG 11769 } 11770 11771 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11772 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11773 } 11774