1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements the SelectionDAG class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/SelectionDAG.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/APSInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/FoldingSet.h" 21 #include "llvm/ADT/None.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Triple.h" 26 #include "llvm/ADT/Twine.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/CodeGen/Analysis.h" 30 #include "llvm/CodeGen/FunctionLoweringInfo.h" 31 #include "llvm/CodeGen/ISDOpcodes.h" 32 #include "llvm/CodeGen/MachineBasicBlock.h" 33 #include "llvm/CodeGen/MachineConstantPool.h" 34 #include "llvm/CodeGen/MachineFrameInfo.h" 35 #include "llvm/CodeGen/MachineFunction.h" 36 #include "llvm/CodeGen/MachineMemOperand.h" 37 #include "llvm/CodeGen/RuntimeLibcalls.h" 38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 39 #include "llvm/CodeGen/SelectionDAGNodes.h" 40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 41 #include "llvm/CodeGen/TargetFrameLowering.h" 42 #include "llvm/CodeGen/TargetLowering.h" 43 #include "llvm/CodeGen/TargetRegisterInfo.h" 44 #include "llvm/CodeGen/TargetSubtargetInfo.h" 45 #include "llvm/CodeGen/ValueTypes.h" 46 #include "llvm/IR/Constant.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DebugInfoMetadata.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/IR/GlobalValue.h" 54 #include "llvm/IR/Metadata.h" 55 #include "llvm/IR/Type.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CodeGen.h" 58 #include "llvm/Support/Compiler.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/KnownBits.h" 62 #include "llvm/Support/MachineValueType.h" 63 #include "llvm/Support/ManagedStatic.h" 64 #include "llvm/Support/MathExtras.h" 65 #include "llvm/Support/Mutex.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include "llvm/Target/TargetOptions.h" 69 #include "llvm/Transforms/Utils/SizeOpts.h" 70 #include <algorithm> 71 #include <cassert> 72 #include <cstdint> 73 #include <cstdlib> 74 #include <limits> 75 #include <set> 76 #include <string> 77 #include <utility> 78 #include <vector> 79 80 using namespace llvm; 81 82 /// makeVTList - Return an instance of the SDVTList struct initialized with the 83 /// specified members. 84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 85 SDVTList Res = {VTs, NumVTs}; 86 return Res; 87 } 88 89 // Default null implementations of the callbacks. 90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 93 94 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 95 96 #define DEBUG_TYPE "selectiondag" 97 98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 99 cl::Hidden, cl::init(true), 100 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 101 102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 103 cl::desc("Number limit for gluing ld/st of memcpy."), 104 cl::Hidden, cl::init(0)); 105 106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 107 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 108 } 109 110 //===----------------------------------------------------------------------===// 111 // ConstantFPSDNode Class 112 //===----------------------------------------------------------------------===// 113 114 /// isExactlyValue - We don't rely on operator== working on double values, as 115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 116 /// As such, this method can be used to do an exact bit-for-bit comparison of 117 /// two floating point values. 118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 119 return getValueAPF().bitwiseIsEqual(V); 120 } 121 122 bool ConstantFPSDNode::isValueValidForType(EVT VT, 123 const APFloat& Val) { 124 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 125 126 // convert modifies in place, so make a copy. 127 APFloat Val2 = APFloat(Val); 128 bool losesInfo; 129 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 130 APFloat::rmNearestTiesToEven, 131 &losesInfo); 132 return !losesInfo; 133 } 134 135 //===----------------------------------------------------------------------===// 136 // ISD Namespace 137 //===----------------------------------------------------------------------===// 138 139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 140 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 141 unsigned EltSize = 142 N->getValueType(0).getVectorElementType().getSizeInBits(); 143 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 144 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize); 145 return true; 146 } 147 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 148 SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize); 149 return true; 150 } 151 } 152 153 auto *BV = dyn_cast<BuildVectorSDNode>(N); 154 if (!BV) 155 return false; 156 157 APInt SplatUndef; 158 unsigned SplatBitSize; 159 bool HasUndefs; 160 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 161 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 162 EltSize) && 163 EltSize == SplatBitSize; 164 } 165 166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 167 // specializations of the more general isConstantSplatVector()? 168 169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 170 // Look through a bit convert. 171 while (N->getOpcode() == ISD::BITCAST) 172 N = N->getOperand(0).getNode(); 173 174 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 175 APInt SplatVal; 176 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 177 } 178 179 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 180 181 unsigned i = 0, e = N->getNumOperands(); 182 183 // Skip over all of the undef values. 184 while (i != e && N->getOperand(i).isUndef()) 185 ++i; 186 187 // Do not accept an all-undef vector. 188 if (i == e) return false; 189 190 // Do not accept build_vectors that aren't all constants or which have non-~0 191 // elements. We have to be a bit careful here, as the type of the constant 192 // may not be the same as the type of the vector elements due to type 193 // legalization (the elements are promoted to a legal type for the target and 194 // a vector of a type may be legal when the base element type is not). 195 // We only want to check enough bits to cover the vector elements, because 196 // we care if the resultant vector is all ones, not whether the individual 197 // constants are. 198 SDValue NotZero = N->getOperand(i); 199 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 200 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 201 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 202 return false; 203 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 204 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 205 return false; 206 } else 207 return false; 208 209 // Okay, we have at least one ~0 value, check to see if the rest match or are 210 // undefs. Even with the above element type twiddling, this should be OK, as 211 // the same type legalization should have applied to all the elements. 212 for (++i; i != e; ++i) 213 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 214 return false; 215 return true; 216 } 217 218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 219 // Look through a bit convert. 220 while (N->getOpcode() == ISD::BITCAST) 221 N = N->getOperand(0).getNode(); 222 223 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 224 APInt SplatVal; 225 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 226 } 227 228 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 229 230 bool IsAllUndef = true; 231 for (const SDValue &Op : N->op_values()) { 232 if (Op.isUndef()) 233 continue; 234 IsAllUndef = false; 235 // Do not accept build_vectors that aren't all constants or which have non-0 236 // elements. We have to be a bit careful here, as the type of the constant 237 // may not be the same as the type of the vector elements due to type 238 // legalization (the elements are promoted to a legal type for the target 239 // and a vector of a type may be legal when the base element type is not). 240 // We only want to check enough bits to cover the vector elements, because 241 // we care if the resultant vector is all zeros, not whether the individual 242 // constants are. 243 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 244 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 245 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 246 return false; 247 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 248 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 249 return false; 250 } else 251 return false; 252 } 253 254 // Do not accept an all-undef vector. 255 if (IsAllUndef) 256 return false; 257 return true; 258 } 259 260 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 261 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 262 } 263 264 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 265 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 266 } 267 268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 269 if (N->getOpcode() != ISD::BUILD_VECTOR) 270 return false; 271 272 for (const SDValue &Op : N->op_values()) { 273 if (Op.isUndef()) 274 continue; 275 if (!isa<ConstantSDNode>(Op)) 276 return false; 277 } 278 return true; 279 } 280 281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 282 if (N->getOpcode() != ISD::BUILD_VECTOR) 283 return false; 284 285 for (const SDValue &Op : N->op_values()) { 286 if (Op.isUndef()) 287 continue; 288 if (!isa<ConstantFPSDNode>(Op)) 289 return false; 290 } 291 return true; 292 } 293 294 bool ISD::allOperandsUndef(const SDNode *N) { 295 // Return false if the node has no operands. 296 // This is "logically inconsistent" with the definition of "all" but 297 // is probably the desired behavior. 298 if (N->getNumOperands() == 0) 299 return false; 300 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 301 } 302 303 bool ISD::matchUnaryPredicate(SDValue Op, 304 std::function<bool(ConstantSDNode *)> Match, 305 bool AllowUndefs) { 306 // FIXME: Add support for scalar UNDEF cases? 307 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 308 return Match(Cst); 309 310 // FIXME: Add support for vector UNDEF cases? 311 if (ISD::BUILD_VECTOR != Op.getOpcode() && 312 ISD::SPLAT_VECTOR != Op.getOpcode()) 313 return false; 314 315 EVT SVT = Op.getValueType().getScalarType(); 316 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 317 if (AllowUndefs && Op.getOperand(i).isUndef()) { 318 if (!Match(nullptr)) 319 return false; 320 continue; 321 } 322 323 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 324 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 325 return false; 326 } 327 return true; 328 } 329 330 bool ISD::matchBinaryPredicate( 331 SDValue LHS, SDValue RHS, 332 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 333 bool AllowUndefs, bool AllowTypeMismatch) { 334 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 335 return false; 336 337 // TODO: Add support for scalar UNDEF cases? 338 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 339 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 340 return Match(LHSCst, RHSCst); 341 342 // TODO: Add support for vector UNDEF cases? 343 if (LHS.getOpcode() != RHS.getOpcode() || 344 (LHS.getOpcode() != ISD::BUILD_VECTOR && 345 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 346 return false; 347 348 EVT SVT = LHS.getValueType().getScalarType(); 349 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 350 SDValue LHSOp = LHS.getOperand(i); 351 SDValue RHSOp = RHS.getOperand(i); 352 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 353 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 354 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 355 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 356 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 357 return false; 358 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 359 LHSOp.getValueType() != RHSOp.getValueType())) 360 return false; 361 if (!Match(LHSCst, RHSCst)) 362 return false; 363 } 364 return true; 365 } 366 367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 368 switch (VecReduceOpcode) { 369 default: 370 llvm_unreachable("Expected VECREDUCE opcode"); 371 case ISD::VECREDUCE_FADD: 372 case ISD::VECREDUCE_SEQ_FADD: 373 case ISD::VP_REDUCE_FADD: 374 case ISD::VP_REDUCE_SEQ_FADD: 375 return ISD::FADD; 376 case ISD::VECREDUCE_FMUL: 377 case ISD::VECREDUCE_SEQ_FMUL: 378 case ISD::VP_REDUCE_FMUL: 379 case ISD::VP_REDUCE_SEQ_FMUL: 380 return ISD::FMUL; 381 case ISD::VECREDUCE_ADD: 382 case ISD::VP_REDUCE_ADD: 383 return ISD::ADD; 384 case ISD::VECREDUCE_MUL: 385 case ISD::VP_REDUCE_MUL: 386 return ISD::MUL; 387 case ISD::VECREDUCE_AND: 388 case ISD::VP_REDUCE_AND: 389 return ISD::AND; 390 case ISD::VECREDUCE_OR: 391 case ISD::VP_REDUCE_OR: 392 return ISD::OR; 393 case ISD::VECREDUCE_XOR: 394 case ISD::VP_REDUCE_XOR: 395 return ISD::XOR; 396 case ISD::VECREDUCE_SMAX: 397 case ISD::VP_REDUCE_SMAX: 398 return ISD::SMAX; 399 case ISD::VECREDUCE_SMIN: 400 case ISD::VP_REDUCE_SMIN: 401 return ISD::SMIN; 402 case ISD::VECREDUCE_UMAX: 403 case ISD::VP_REDUCE_UMAX: 404 return ISD::UMAX; 405 case ISD::VECREDUCE_UMIN: 406 case ISD::VP_REDUCE_UMIN: 407 return ISD::UMIN; 408 case ISD::VECREDUCE_FMAX: 409 case ISD::VP_REDUCE_FMAX: 410 return ISD::FMAXNUM; 411 case ISD::VECREDUCE_FMIN: 412 case ISD::VP_REDUCE_FMIN: 413 return ISD::FMINNUM; 414 } 415 } 416 417 bool ISD::isVPOpcode(unsigned Opcode) { 418 switch (Opcode) { 419 default: 420 return false; 421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 422 case ISD::VPSD: \ 423 return true; 424 #include "llvm/IR/VPIntrinsics.def" 425 } 426 } 427 428 bool ISD::isVPBinaryOp(unsigned Opcode) { 429 switch (Opcode) { 430 default: 431 break; 432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 433 #define VP_PROPERTY_BINARYOP return true; 434 #define END_REGISTER_VP_SDNODE(VPSD) break; 435 #include "llvm/IR/VPIntrinsics.def" 436 } 437 return false; 438 } 439 440 bool ISD::isVPReduction(unsigned Opcode) { 441 switch (Opcode) { 442 default: 443 break; 444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 446 #define END_REGISTER_VP_SDNODE(VPSD) break; 447 #include "llvm/IR/VPIntrinsics.def" 448 } 449 return false; 450 } 451 452 /// The operand position of the vector mask. 453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 454 switch (Opcode) { 455 default: 456 return None; 457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 458 case ISD::VPSD: \ 459 return MASKPOS; 460 #include "llvm/IR/VPIntrinsics.def" 461 } 462 } 463 464 /// The operand position of the explicit vector length parameter. 465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 466 switch (Opcode) { 467 default: 468 return None; 469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 470 case ISD::VPSD: \ 471 return EVLPOS; 472 #include "llvm/IR/VPIntrinsics.def" 473 } 474 } 475 476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 477 switch (ExtType) { 478 case ISD::EXTLOAD: 479 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 480 case ISD::SEXTLOAD: 481 return ISD::SIGN_EXTEND; 482 case ISD::ZEXTLOAD: 483 return ISD::ZERO_EXTEND; 484 default: 485 break; 486 } 487 488 llvm_unreachable("Invalid LoadExtType"); 489 } 490 491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 492 // To perform this operation, we just need to swap the L and G bits of the 493 // operation. 494 unsigned OldL = (Operation >> 2) & 1; 495 unsigned OldG = (Operation >> 1) & 1; 496 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 497 (OldL << 1) | // New G bit 498 (OldG << 2)); // New L bit. 499 } 500 501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 502 unsigned Operation = Op; 503 if (isIntegerLike) 504 Operation ^= 7; // Flip L, G, E bits, but not U. 505 else 506 Operation ^= 15; // Flip all of the condition bits. 507 508 if (Operation > ISD::SETTRUE2) 509 Operation &= ~8; // Don't let N and U bits get set. 510 511 return ISD::CondCode(Operation); 512 } 513 514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 515 return getSetCCInverseImpl(Op, Type.isInteger()); 516 } 517 518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 519 bool isIntegerLike) { 520 return getSetCCInverseImpl(Op, isIntegerLike); 521 } 522 523 /// For an integer comparison, return 1 if the comparison is a signed operation 524 /// and 2 if the result is an unsigned comparison. Return zero if the operation 525 /// does not depend on the sign of the input (setne and seteq). 526 static int isSignedOp(ISD::CondCode Opcode) { 527 switch (Opcode) { 528 default: llvm_unreachable("Illegal integer setcc operation!"); 529 case ISD::SETEQ: 530 case ISD::SETNE: return 0; 531 case ISD::SETLT: 532 case ISD::SETLE: 533 case ISD::SETGT: 534 case ISD::SETGE: return 1; 535 case ISD::SETULT: 536 case ISD::SETULE: 537 case ISD::SETUGT: 538 case ISD::SETUGE: return 2; 539 } 540 } 541 542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 543 EVT Type) { 544 bool IsInteger = Type.isInteger(); 545 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 546 // Cannot fold a signed integer setcc with an unsigned integer setcc. 547 return ISD::SETCC_INVALID; 548 549 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 550 551 // If the N and U bits get set, then the resultant comparison DOES suddenly 552 // care about orderedness, and it is true when ordered. 553 if (Op > ISD::SETTRUE2) 554 Op &= ~16; // Clear the U bit if the N bit is set. 555 556 // Canonicalize illegal integer setcc's. 557 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 558 Op = ISD::SETNE; 559 560 return ISD::CondCode(Op); 561 } 562 563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 564 EVT Type) { 565 bool IsInteger = Type.isInteger(); 566 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 567 // Cannot fold a signed setcc with an unsigned setcc. 568 return ISD::SETCC_INVALID; 569 570 // Combine all of the condition bits. 571 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 572 573 // Canonicalize illegal integer setcc's. 574 if (IsInteger) { 575 switch (Result) { 576 default: break; 577 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 578 case ISD::SETOEQ: // SETEQ & SETU[LG]E 579 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 580 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 581 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 582 } 583 } 584 585 return Result; 586 } 587 588 //===----------------------------------------------------------------------===// 589 // SDNode Profile Support 590 //===----------------------------------------------------------------------===// 591 592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 594 ID.AddInteger(OpC); 595 } 596 597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 598 /// solely with their pointer. 599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 600 ID.AddPointer(VTList.VTs); 601 } 602 603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 604 static void AddNodeIDOperands(FoldingSetNodeID &ID, 605 ArrayRef<SDValue> Ops) { 606 for (auto& Op : Ops) { 607 ID.AddPointer(Op.getNode()); 608 ID.AddInteger(Op.getResNo()); 609 } 610 } 611 612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 613 static void AddNodeIDOperands(FoldingSetNodeID &ID, 614 ArrayRef<SDUse> Ops) { 615 for (auto& Op : Ops) { 616 ID.AddPointer(Op.getNode()); 617 ID.AddInteger(Op.getResNo()); 618 } 619 } 620 621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 622 SDVTList VTList, ArrayRef<SDValue> OpList) { 623 AddNodeIDOpcode(ID, OpC); 624 AddNodeIDValueTypes(ID, VTList); 625 AddNodeIDOperands(ID, OpList); 626 } 627 628 /// If this is an SDNode with special info, add this info to the NodeID data. 629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 630 switch (N->getOpcode()) { 631 case ISD::TargetExternalSymbol: 632 case ISD::ExternalSymbol: 633 case ISD::MCSymbol: 634 llvm_unreachable("Should only be used on nodes with operands"); 635 default: break; // Normal nodes don't need extra info. 636 case ISD::TargetConstant: 637 case ISD::Constant: { 638 const ConstantSDNode *C = cast<ConstantSDNode>(N); 639 ID.AddPointer(C->getConstantIntValue()); 640 ID.AddBoolean(C->isOpaque()); 641 break; 642 } 643 case ISD::TargetConstantFP: 644 case ISD::ConstantFP: 645 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 646 break; 647 case ISD::TargetGlobalAddress: 648 case ISD::GlobalAddress: 649 case ISD::TargetGlobalTLSAddress: 650 case ISD::GlobalTLSAddress: { 651 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 652 ID.AddPointer(GA->getGlobal()); 653 ID.AddInteger(GA->getOffset()); 654 ID.AddInteger(GA->getTargetFlags()); 655 break; 656 } 657 case ISD::BasicBlock: 658 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 659 break; 660 case ISD::Register: 661 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 662 break; 663 case ISD::RegisterMask: 664 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 665 break; 666 case ISD::SRCVALUE: 667 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 668 break; 669 case ISD::FrameIndex: 670 case ISD::TargetFrameIndex: 671 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 672 break; 673 case ISD::LIFETIME_START: 674 case ISD::LIFETIME_END: 675 if (cast<LifetimeSDNode>(N)->hasOffset()) { 676 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 677 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 678 } 679 break; 680 case ISD::PSEUDO_PROBE: 681 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 682 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 683 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 684 break; 685 case ISD::JumpTable: 686 case ISD::TargetJumpTable: 687 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 688 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 689 break; 690 case ISD::ConstantPool: 691 case ISD::TargetConstantPool: { 692 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 693 ID.AddInteger(CP->getAlign().value()); 694 ID.AddInteger(CP->getOffset()); 695 if (CP->isMachineConstantPoolEntry()) 696 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 697 else 698 ID.AddPointer(CP->getConstVal()); 699 ID.AddInteger(CP->getTargetFlags()); 700 break; 701 } 702 case ISD::TargetIndex: { 703 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 704 ID.AddInteger(TI->getIndex()); 705 ID.AddInteger(TI->getOffset()); 706 ID.AddInteger(TI->getTargetFlags()); 707 break; 708 } 709 case ISD::LOAD: { 710 const LoadSDNode *LD = cast<LoadSDNode>(N); 711 ID.AddInteger(LD->getMemoryVT().getRawBits()); 712 ID.AddInteger(LD->getRawSubclassData()); 713 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 714 ID.AddInteger(LD->getMemOperand()->getFlags()); 715 break; 716 } 717 case ISD::STORE: { 718 const StoreSDNode *ST = cast<StoreSDNode>(N); 719 ID.AddInteger(ST->getMemoryVT().getRawBits()); 720 ID.AddInteger(ST->getRawSubclassData()); 721 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 722 ID.AddInteger(ST->getMemOperand()->getFlags()); 723 break; 724 } 725 case ISD::VP_LOAD: { 726 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 727 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 728 ID.AddInteger(ELD->getRawSubclassData()); 729 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 730 ID.AddInteger(ELD->getMemOperand()->getFlags()); 731 break; 732 } 733 case ISD::VP_STORE: { 734 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 735 ID.AddInteger(EST->getMemoryVT().getRawBits()); 736 ID.AddInteger(EST->getRawSubclassData()); 737 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 738 ID.AddInteger(EST->getMemOperand()->getFlags()); 739 break; 740 } 741 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: { 742 const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N); 743 ID.AddInteger(SLD->getMemoryVT().getRawBits()); 744 ID.AddInteger(SLD->getRawSubclassData()); 745 ID.AddInteger(SLD->getPointerInfo().getAddrSpace()); 746 break; 747 } 748 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: { 749 const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N); 750 ID.AddInteger(SST->getMemoryVT().getRawBits()); 751 ID.AddInteger(SST->getRawSubclassData()); 752 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 753 break; 754 } 755 case ISD::VP_GATHER: { 756 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 757 ID.AddInteger(EG->getMemoryVT().getRawBits()); 758 ID.AddInteger(EG->getRawSubclassData()); 759 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 760 ID.AddInteger(EG->getMemOperand()->getFlags()); 761 break; 762 } 763 case ISD::VP_SCATTER: { 764 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 765 ID.AddInteger(ES->getMemoryVT().getRawBits()); 766 ID.AddInteger(ES->getRawSubclassData()); 767 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 768 ID.AddInteger(ES->getMemOperand()->getFlags()); 769 break; 770 } 771 case ISD::MLOAD: { 772 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 773 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 774 ID.AddInteger(MLD->getRawSubclassData()); 775 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 776 ID.AddInteger(MLD->getMemOperand()->getFlags()); 777 break; 778 } 779 case ISD::MSTORE: { 780 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 781 ID.AddInteger(MST->getMemoryVT().getRawBits()); 782 ID.AddInteger(MST->getRawSubclassData()); 783 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 784 ID.AddInteger(MST->getMemOperand()->getFlags()); 785 break; 786 } 787 case ISD::MGATHER: { 788 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 789 ID.AddInteger(MG->getMemoryVT().getRawBits()); 790 ID.AddInteger(MG->getRawSubclassData()); 791 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 792 ID.AddInteger(MG->getMemOperand()->getFlags()); 793 break; 794 } 795 case ISD::MSCATTER: { 796 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 797 ID.AddInteger(MS->getMemoryVT().getRawBits()); 798 ID.AddInteger(MS->getRawSubclassData()); 799 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 800 ID.AddInteger(MS->getMemOperand()->getFlags()); 801 break; 802 } 803 case ISD::ATOMIC_CMP_SWAP: 804 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 805 case ISD::ATOMIC_SWAP: 806 case ISD::ATOMIC_LOAD_ADD: 807 case ISD::ATOMIC_LOAD_SUB: 808 case ISD::ATOMIC_LOAD_AND: 809 case ISD::ATOMIC_LOAD_CLR: 810 case ISD::ATOMIC_LOAD_OR: 811 case ISD::ATOMIC_LOAD_XOR: 812 case ISD::ATOMIC_LOAD_NAND: 813 case ISD::ATOMIC_LOAD_MIN: 814 case ISD::ATOMIC_LOAD_MAX: 815 case ISD::ATOMIC_LOAD_UMIN: 816 case ISD::ATOMIC_LOAD_UMAX: 817 case ISD::ATOMIC_LOAD: 818 case ISD::ATOMIC_STORE: { 819 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 820 ID.AddInteger(AT->getMemoryVT().getRawBits()); 821 ID.AddInteger(AT->getRawSubclassData()); 822 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 823 ID.AddInteger(AT->getMemOperand()->getFlags()); 824 break; 825 } 826 case ISD::PREFETCH: { 827 const MemSDNode *PF = cast<MemSDNode>(N); 828 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 829 ID.AddInteger(PF->getMemOperand()->getFlags()); 830 break; 831 } 832 case ISD::VECTOR_SHUFFLE: { 833 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 834 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 835 i != e; ++i) 836 ID.AddInteger(SVN->getMaskElt(i)); 837 break; 838 } 839 case ISD::TargetBlockAddress: 840 case ISD::BlockAddress: { 841 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 842 ID.AddPointer(BA->getBlockAddress()); 843 ID.AddInteger(BA->getOffset()); 844 ID.AddInteger(BA->getTargetFlags()); 845 break; 846 } 847 case ISD::AssertAlign: 848 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value()); 849 break; 850 } // end switch (N->getOpcode()) 851 852 // Target specific memory nodes could also have address spaces and flags 853 // to check. 854 if (N->isTargetMemoryOpcode()) { 855 const MemSDNode *MN = cast<MemSDNode>(N); 856 ID.AddInteger(MN->getPointerInfo().getAddrSpace()); 857 ID.AddInteger(MN->getMemOperand()->getFlags()); 858 } 859 } 860 861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 862 /// data. 863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 864 AddNodeIDOpcode(ID, N->getOpcode()); 865 // Add the return value info. 866 AddNodeIDValueTypes(ID, N->getVTList()); 867 // Add the operand info. 868 AddNodeIDOperands(ID, N->ops()); 869 870 // Handle SDNode leafs with special info. 871 AddNodeIDCustom(ID, N); 872 } 873 874 //===----------------------------------------------------------------------===// 875 // SelectionDAG Class 876 //===----------------------------------------------------------------------===// 877 878 /// doNotCSE - Return true if CSE should not be performed for this node. 879 static bool doNotCSE(SDNode *N) { 880 if (N->getValueType(0) == MVT::Glue) 881 return true; // Never CSE anything that produces a flag. 882 883 switch (N->getOpcode()) { 884 default: break; 885 case ISD::HANDLENODE: 886 case ISD::EH_LABEL: 887 return true; // Never CSE these nodes. 888 } 889 890 // Check that remaining values produced are not flags. 891 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 892 if (N->getValueType(i) == MVT::Glue) 893 return true; // Never CSE anything that produces a flag. 894 895 return false; 896 } 897 898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 899 /// SelectionDAG. 900 void SelectionDAG::RemoveDeadNodes() { 901 // Create a dummy node (which is not added to allnodes), that adds a reference 902 // to the root node, preventing it from being deleted. 903 HandleSDNode Dummy(getRoot()); 904 905 SmallVector<SDNode*, 128> DeadNodes; 906 907 // Add all obviously-dead nodes to the DeadNodes worklist. 908 for (SDNode &Node : allnodes()) 909 if (Node.use_empty()) 910 DeadNodes.push_back(&Node); 911 912 RemoveDeadNodes(DeadNodes); 913 914 // If the root changed (e.g. it was a dead load, update the root). 915 setRoot(Dummy.getValue()); 916 } 917 918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 919 /// given list, and any nodes that become unreachable as a result. 920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 921 922 // Process the worklist, deleting the nodes and adding their uses to the 923 // worklist. 924 while (!DeadNodes.empty()) { 925 SDNode *N = DeadNodes.pop_back_val(); 926 // Skip to next node if we've already managed to delete the node. This could 927 // happen if replacing a node causes a node previously added to the node to 928 // be deleted. 929 if (N->getOpcode() == ISD::DELETED_NODE) 930 continue; 931 932 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 933 DUL->NodeDeleted(N, nullptr); 934 935 // Take the node out of the appropriate CSE map. 936 RemoveNodeFromCSEMaps(N); 937 938 // Next, brutally remove the operand list. This is safe to do, as there are 939 // no cycles in the graph. 940 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 941 SDUse &Use = *I++; 942 SDNode *Operand = Use.getNode(); 943 Use.set(SDValue()); 944 945 // Now that we removed this operand, see if there are no uses of it left. 946 if (Operand->use_empty()) 947 DeadNodes.push_back(Operand); 948 } 949 950 DeallocateNode(N); 951 } 952 } 953 954 void SelectionDAG::RemoveDeadNode(SDNode *N){ 955 SmallVector<SDNode*, 16> DeadNodes(1, N); 956 957 // Create a dummy node that adds a reference to the root node, preventing 958 // it from being deleted. (This matters if the root is an operand of the 959 // dead node.) 960 HandleSDNode Dummy(getRoot()); 961 962 RemoveDeadNodes(DeadNodes); 963 } 964 965 void SelectionDAG::DeleteNode(SDNode *N) { 966 // First take this out of the appropriate CSE map. 967 RemoveNodeFromCSEMaps(N); 968 969 // Finally, remove uses due to operands of this node, remove from the 970 // AllNodes list, and delete the node. 971 DeleteNodeNotInCSEMaps(N); 972 } 973 974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 975 assert(N->getIterator() != AllNodes.begin() && 976 "Cannot delete the entry node!"); 977 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 978 979 // Drop all of the operands and decrement used node's use counts. 980 N->DropOperands(); 981 982 DeallocateNode(N); 983 } 984 985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 986 assert(!(V->isVariadic() && isParameter)); 987 if (isParameter) 988 ByvalParmDbgValues.push_back(V); 989 else 990 DbgValues.push_back(V); 991 for (const SDNode *Node : V->getSDNodes()) 992 if (Node) 993 DbgValMap[Node].push_back(V); 994 } 995 996 void SDDbgInfo::erase(const SDNode *Node) { 997 DbgValMapType::iterator I = DbgValMap.find(Node); 998 if (I == DbgValMap.end()) 999 return; 1000 for (auto &Val: I->second) 1001 Val->setIsInvalidated(); 1002 DbgValMap.erase(I); 1003 } 1004 1005 void SelectionDAG::DeallocateNode(SDNode *N) { 1006 // If we have operands, deallocate them. 1007 removeOperands(N); 1008 1009 NodeAllocator.Deallocate(AllNodes.remove(N)); 1010 1011 // Set the opcode to DELETED_NODE to help catch bugs when node 1012 // memory is reallocated. 1013 // FIXME: There are places in SDag that have grown a dependency on the opcode 1014 // value in the released node. 1015 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 1016 N->NodeType = ISD::DELETED_NODE; 1017 1018 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 1019 // them and forget about that node. 1020 DbgInfo->erase(N); 1021 } 1022 1023 #ifndef NDEBUG 1024 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 1025 static void VerifySDNode(SDNode *N) { 1026 switch (N->getOpcode()) { 1027 default: 1028 break; 1029 case ISD::BUILD_PAIR: { 1030 EVT VT = N->getValueType(0); 1031 assert(N->getNumValues() == 1 && "Too many results!"); 1032 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1033 "Wrong return type!"); 1034 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1035 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1036 "Mismatched operand types!"); 1037 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1038 "Wrong operand type!"); 1039 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1040 "Wrong return type size"); 1041 break; 1042 } 1043 case ISD::BUILD_VECTOR: { 1044 assert(N->getNumValues() == 1 && "Too many results!"); 1045 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1046 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1047 "Wrong number of operands!"); 1048 EVT EltVT = N->getValueType(0).getVectorElementType(); 1049 for (const SDUse &Op : N->ops()) { 1050 assert((Op.getValueType() == EltVT || 1051 (EltVT.isInteger() && Op.getValueType().isInteger() && 1052 EltVT.bitsLE(Op.getValueType()))) && 1053 "Wrong operand type!"); 1054 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1055 "Operands must all have the same type"); 1056 } 1057 break; 1058 } 1059 } 1060 } 1061 #endif // NDEBUG 1062 1063 /// Insert a newly allocated node into the DAG. 1064 /// 1065 /// Handles insertion into the all nodes list and CSE map, as well as 1066 /// verification and other common operations when a new node is allocated. 1067 void SelectionDAG::InsertNode(SDNode *N) { 1068 AllNodes.push_back(N); 1069 #ifndef NDEBUG 1070 N->PersistentId = NextPersistentId++; 1071 VerifySDNode(N); 1072 #endif 1073 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1074 DUL->NodeInserted(N); 1075 } 1076 1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1078 /// correspond to it. This is useful when we're about to delete or repurpose 1079 /// the node. We don't want future request for structurally identical nodes 1080 /// to return N anymore. 1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1082 bool Erased = false; 1083 switch (N->getOpcode()) { 1084 case ISD::HANDLENODE: return false; // noop. 1085 case ISD::CONDCODE: 1086 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1087 "Cond code doesn't exist!"); 1088 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1089 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1090 break; 1091 case ISD::ExternalSymbol: 1092 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1093 break; 1094 case ISD::TargetExternalSymbol: { 1095 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1096 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1097 ESN->getSymbol(), ESN->getTargetFlags())); 1098 break; 1099 } 1100 case ISD::MCSymbol: { 1101 auto *MCSN = cast<MCSymbolSDNode>(N); 1102 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1103 break; 1104 } 1105 case ISD::VALUETYPE: { 1106 EVT VT = cast<VTSDNode>(N)->getVT(); 1107 if (VT.isExtended()) { 1108 Erased = ExtendedValueTypeNodes.erase(VT); 1109 } else { 1110 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1111 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1112 } 1113 break; 1114 } 1115 default: 1116 // Remove it from the CSE Map. 1117 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1118 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1119 Erased = CSEMap.RemoveNode(N); 1120 break; 1121 } 1122 #ifndef NDEBUG 1123 // Verify that the node was actually in one of the CSE maps, unless it has a 1124 // flag result (which cannot be CSE'd) or is one of the special cases that are 1125 // not subject to CSE. 1126 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1127 !N->isMachineOpcode() && !doNotCSE(N)) { 1128 N->dump(this); 1129 dbgs() << "\n"; 1130 llvm_unreachable("Node is not in map!"); 1131 } 1132 #endif 1133 return Erased; 1134 } 1135 1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1138 /// node already exists, in which case transfer all its users to the existing 1139 /// node. This transfer can potentially trigger recursive merging. 1140 void 1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1142 // For node types that aren't CSE'd, just act as if no identical node 1143 // already exists. 1144 if (!doNotCSE(N)) { 1145 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1146 if (Existing != N) { 1147 // If there was already an existing matching node, use ReplaceAllUsesWith 1148 // to replace the dead one with the existing one. This can cause 1149 // recursive merging of other unrelated nodes down the line. 1150 ReplaceAllUsesWith(N, Existing); 1151 1152 // N is now dead. Inform the listeners and delete it. 1153 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1154 DUL->NodeDeleted(N, Existing); 1155 DeleteNodeNotInCSEMaps(N); 1156 return; 1157 } 1158 } 1159 1160 // If the node doesn't already exist, we updated it. Inform listeners. 1161 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1162 DUL->NodeUpdated(N); 1163 } 1164 1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1166 /// were replaced with those specified. If this node is never memoized, 1167 /// return null, otherwise return a pointer to the slot it would take. If a 1168 /// node already exists with these operands, the slot will be non-null. 1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1170 void *&InsertPos) { 1171 if (doNotCSE(N)) 1172 return nullptr; 1173 1174 SDValue Ops[] = { Op }; 1175 FoldingSetNodeID ID; 1176 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1177 AddNodeIDCustom(ID, N); 1178 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1179 if (Node) 1180 Node->intersectFlagsWith(N->getFlags()); 1181 return Node; 1182 } 1183 1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1185 /// were replaced with those specified. If this node is never memoized, 1186 /// return null, otherwise return a pointer to the slot it would take. If a 1187 /// node already exists with these operands, the slot will be non-null. 1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1189 SDValue Op1, SDValue Op2, 1190 void *&InsertPos) { 1191 if (doNotCSE(N)) 1192 return nullptr; 1193 1194 SDValue Ops[] = { Op1, Op2 }; 1195 FoldingSetNodeID ID; 1196 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1197 AddNodeIDCustom(ID, N); 1198 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1199 if (Node) 1200 Node->intersectFlagsWith(N->getFlags()); 1201 return Node; 1202 } 1203 1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1205 /// were replaced with those specified. If this node is never memoized, 1206 /// return null, otherwise return a pointer to the slot it would take. If a 1207 /// node already exists with these operands, the slot will be non-null. 1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1209 void *&InsertPos) { 1210 if (doNotCSE(N)) 1211 return nullptr; 1212 1213 FoldingSetNodeID ID; 1214 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1215 AddNodeIDCustom(ID, N); 1216 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1217 if (Node) 1218 Node->intersectFlagsWith(N->getFlags()); 1219 return Node; 1220 } 1221 1222 Align SelectionDAG::getEVTAlign(EVT VT) const { 1223 Type *Ty = VT == MVT::iPTR ? 1224 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1225 VT.getTypeForEVT(*getContext()); 1226 1227 return getDataLayout().getABITypeAlign(Ty); 1228 } 1229 1230 // EntryNode could meaningfully have debug info if we can find it... 1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1232 : TM(tm), OptLevel(OL), 1233 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1234 Root(getEntryNode()) { 1235 InsertNode(&EntryNode); 1236 DbgInfo = new SDDbgInfo(); 1237 } 1238 1239 void SelectionDAG::init(MachineFunction &NewMF, 1240 OptimizationRemarkEmitter &NewORE, 1241 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1242 LegacyDivergenceAnalysis * Divergence, 1243 ProfileSummaryInfo *PSIin, 1244 BlockFrequencyInfo *BFIin) { 1245 MF = &NewMF; 1246 SDAGISelPass = PassPtr; 1247 ORE = &NewORE; 1248 TLI = getSubtarget().getTargetLowering(); 1249 TSI = getSubtarget().getSelectionDAGInfo(); 1250 LibInfo = LibraryInfo; 1251 Context = &MF->getFunction().getContext(); 1252 DA = Divergence; 1253 PSI = PSIin; 1254 BFI = BFIin; 1255 } 1256 1257 SelectionDAG::~SelectionDAG() { 1258 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1259 allnodes_clear(); 1260 OperandRecycler.clear(OperandAllocator); 1261 delete DbgInfo; 1262 } 1263 1264 bool SelectionDAG::shouldOptForSize() const { 1265 return MF->getFunction().hasOptSize() || 1266 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1267 } 1268 1269 void SelectionDAG::allnodes_clear() { 1270 assert(&*AllNodes.begin() == &EntryNode); 1271 AllNodes.remove(AllNodes.begin()); 1272 while (!AllNodes.empty()) 1273 DeallocateNode(&AllNodes.front()); 1274 #ifndef NDEBUG 1275 NextPersistentId = 0; 1276 #endif 1277 } 1278 1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1280 void *&InsertPos) { 1281 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1282 if (N) { 1283 switch (N->getOpcode()) { 1284 default: break; 1285 case ISD::Constant: 1286 case ISD::ConstantFP: 1287 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1288 "debug location. Use another overload."); 1289 } 1290 } 1291 return N; 1292 } 1293 1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1295 const SDLoc &DL, void *&InsertPos) { 1296 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1297 if (N) { 1298 switch (N->getOpcode()) { 1299 case ISD::Constant: 1300 case ISD::ConstantFP: 1301 // Erase debug location from the node if the node is used at several 1302 // different places. Do not propagate one location to all uses as it 1303 // will cause a worse single stepping debugging experience. 1304 if (N->getDebugLoc() != DL.getDebugLoc()) 1305 N->setDebugLoc(DebugLoc()); 1306 break; 1307 default: 1308 // When the node's point of use is located earlier in the instruction 1309 // sequence than its prior point of use, update its debug info to the 1310 // earlier location. 1311 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1312 N->setDebugLoc(DL.getDebugLoc()); 1313 break; 1314 } 1315 } 1316 return N; 1317 } 1318 1319 void SelectionDAG::clear() { 1320 allnodes_clear(); 1321 OperandRecycler.clear(OperandAllocator); 1322 OperandAllocator.Reset(); 1323 CSEMap.clear(); 1324 1325 ExtendedValueTypeNodes.clear(); 1326 ExternalSymbols.clear(); 1327 TargetExternalSymbols.clear(); 1328 MCSymbols.clear(); 1329 SDCallSiteDbgInfo.clear(); 1330 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1331 static_cast<CondCodeSDNode*>(nullptr)); 1332 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1333 static_cast<SDNode*>(nullptr)); 1334 1335 EntryNode.UseList = nullptr; 1336 InsertNode(&EntryNode); 1337 Root = getEntryNode(); 1338 DbgInfo->clear(); 1339 } 1340 1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1342 return VT.bitsGT(Op.getValueType()) 1343 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1344 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1345 } 1346 1347 std::pair<SDValue, SDValue> 1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1349 const SDLoc &DL, EVT VT) { 1350 assert(!VT.bitsEq(Op.getValueType()) && 1351 "Strict no-op FP extend/round not allowed."); 1352 SDValue Res = 1353 VT.bitsGT(Op.getValueType()) 1354 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1355 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1356 {Chain, Op, getIntPtrConstant(0, DL)}); 1357 1358 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1359 } 1360 1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1362 return VT.bitsGT(Op.getValueType()) ? 1363 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1364 getNode(ISD::TRUNCATE, DL, VT, Op); 1365 } 1366 1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1368 return VT.bitsGT(Op.getValueType()) ? 1369 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1370 getNode(ISD::TRUNCATE, DL, VT, Op); 1371 } 1372 1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1374 return VT.bitsGT(Op.getValueType()) ? 1375 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1376 getNode(ISD::TRUNCATE, DL, VT, Op); 1377 } 1378 1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1380 EVT OpVT) { 1381 if (VT.bitsLE(Op.getValueType())) 1382 return getNode(ISD::TRUNCATE, SL, VT, Op); 1383 1384 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1385 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1386 } 1387 1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1389 EVT OpVT = Op.getValueType(); 1390 assert(VT.isInteger() && OpVT.isInteger() && 1391 "Cannot getZeroExtendInReg FP types"); 1392 assert(VT.isVector() == OpVT.isVector() && 1393 "getZeroExtendInReg type should be vector iff the operand " 1394 "type is vector!"); 1395 assert((!VT.isVector() || 1396 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1397 "Vector element counts must match in getZeroExtendInReg"); 1398 assert(VT.bitsLE(OpVT) && "Not extending!"); 1399 if (OpVT == VT) 1400 return Op; 1401 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1402 VT.getScalarSizeInBits()); 1403 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1404 } 1405 1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1407 // Only unsigned pointer semantics are supported right now. In the future this 1408 // might delegate to TLI to check pointer signedness. 1409 return getZExtOrTrunc(Op, DL, VT); 1410 } 1411 1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1413 // Only unsigned pointer semantics are supported right now. In the future this 1414 // might delegate to TLI to check pointer signedness. 1415 return getZeroExtendInReg(Op, DL, VT); 1416 } 1417 1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1420 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1421 } 1422 1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1424 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1425 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1426 } 1427 1428 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1429 EVT OpVT) { 1430 if (!V) 1431 return getConstant(0, DL, VT); 1432 1433 switch (TLI->getBooleanContents(OpVT)) { 1434 case TargetLowering::ZeroOrOneBooleanContent: 1435 case TargetLowering::UndefinedBooleanContent: 1436 return getConstant(1, DL, VT); 1437 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1438 return getAllOnesConstant(DL, VT); 1439 } 1440 llvm_unreachable("Unexpected boolean content enum!"); 1441 } 1442 1443 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1444 bool isT, bool isO) { 1445 EVT EltVT = VT.getScalarType(); 1446 assert((EltVT.getSizeInBits() >= 64 || 1447 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1448 "getConstant with a uint64_t value that doesn't fit in the type!"); 1449 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1450 } 1451 1452 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1453 bool isT, bool isO) { 1454 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1455 } 1456 1457 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1458 EVT VT, bool isT, bool isO) { 1459 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1460 1461 EVT EltVT = VT.getScalarType(); 1462 const ConstantInt *Elt = &Val; 1463 1464 // In some cases the vector type is legal but the element type is illegal and 1465 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1466 // inserted value (the type does not need to match the vector element type). 1467 // Any extra bits introduced will be truncated away. 1468 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1469 TargetLowering::TypePromoteInteger) { 1470 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1471 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1472 Elt = ConstantInt::get(*getContext(), NewVal); 1473 } 1474 // In other cases the element type is illegal and needs to be expanded, for 1475 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1476 // the value into n parts and use a vector type with n-times the elements. 1477 // Then bitcast to the type requested. 1478 // Legalizing constants too early makes the DAGCombiner's job harder so we 1479 // only legalize if the DAG tells us we must produce legal types. 1480 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1481 TLI->getTypeAction(*getContext(), EltVT) == 1482 TargetLowering::TypeExpandInteger) { 1483 const APInt &NewVal = Elt->getValue(); 1484 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1485 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1486 1487 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1488 if (VT.isScalableVector()) { 1489 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1490 "Can only handle an even split!"); 1491 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1492 1493 SmallVector<SDValue, 2> ScalarParts; 1494 for (unsigned i = 0; i != Parts; ++i) 1495 ScalarParts.push_back(getConstant( 1496 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1497 ViaEltVT, isT, isO)); 1498 1499 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1500 } 1501 1502 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1503 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1504 1505 // Check the temporary vector is the correct size. If this fails then 1506 // getTypeToTransformTo() probably returned a type whose size (in bits) 1507 // isn't a power-of-2 factor of the requested type size. 1508 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1509 1510 SmallVector<SDValue, 2> EltParts; 1511 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1512 EltParts.push_back(getConstant( 1513 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1514 ViaEltVT, isT, isO)); 1515 1516 // EltParts is currently in little endian order. If we actually want 1517 // big-endian order then reverse it now. 1518 if (getDataLayout().isBigEndian()) 1519 std::reverse(EltParts.begin(), EltParts.end()); 1520 1521 // The elements must be reversed when the element order is different 1522 // to the endianness of the elements (because the BITCAST is itself a 1523 // vector shuffle in this situation). However, we do not need any code to 1524 // perform this reversal because getConstant() is producing a vector 1525 // splat. 1526 // This situation occurs in MIPS MSA. 1527 1528 SmallVector<SDValue, 8> Ops; 1529 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1530 llvm::append_range(Ops, EltParts); 1531 1532 SDValue V = 1533 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1534 return V; 1535 } 1536 1537 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1538 "APInt size does not match type size!"); 1539 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1540 FoldingSetNodeID ID; 1541 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1542 ID.AddPointer(Elt); 1543 ID.AddBoolean(isO); 1544 void *IP = nullptr; 1545 SDNode *N = nullptr; 1546 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1547 if (!VT.isVector()) 1548 return SDValue(N, 0); 1549 1550 if (!N) { 1551 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1552 CSEMap.InsertNode(N, IP); 1553 InsertNode(N); 1554 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1555 } 1556 1557 SDValue Result(N, 0); 1558 if (VT.isScalableVector()) 1559 Result = getSplatVector(VT, DL, Result); 1560 else if (VT.isVector()) 1561 Result = getSplatBuildVector(VT, DL, Result); 1562 1563 return Result; 1564 } 1565 1566 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1567 bool isTarget) { 1568 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1569 } 1570 1571 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1572 const SDLoc &DL, bool LegalTypes) { 1573 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1574 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1575 return getConstant(Val, DL, ShiftVT); 1576 } 1577 1578 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1579 bool isTarget) { 1580 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1581 } 1582 1583 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1584 bool isTarget) { 1585 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1586 } 1587 1588 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1589 EVT VT, bool isTarget) { 1590 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1591 1592 EVT EltVT = VT.getScalarType(); 1593 1594 // Do the map lookup using the actual bit pattern for the floating point 1595 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1596 // we don't have issues with SNANs. 1597 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1598 FoldingSetNodeID ID; 1599 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1600 ID.AddPointer(&V); 1601 void *IP = nullptr; 1602 SDNode *N = nullptr; 1603 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1604 if (!VT.isVector()) 1605 return SDValue(N, 0); 1606 1607 if (!N) { 1608 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1609 CSEMap.InsertNode(N, IP); 1610 InsertNode(N); 1611 } 1612 1613 SDValue Result(N, 0); 1614 if (VT.isScalableVector()) 1615 Result = getSplatVector(VT, DL, Result); 1616 else if (VT.isVector()) 1617 Result = getSplatBuildVector(VT, DL, Result); 1618 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1619 return Result; 1620 } 1621 1622 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1623 bool isTarget) { 1624 EVT EltVT = VT.getScalarType(); 1625 if (EltVT == MVT::f32) 1626 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1627 if (EltVT == MVT::f64) 1628 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1629 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1630 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1631 bool Ignored; 1632 APFloat APF = APFloat(Val); 1633 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1634 &Ignored); 1635 return getConstantFP(APF, DL, VT, isTarget); 1636 } 1637 llvm_unreachable("Unsupported type in getConstantFP"); 1638 } 1639 1640 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1641 EVT VT, int64_t Offset, bool isTargetGA, 1642 unsigned TargetFlags) { 1643 assert((TargetFlags == 0 || isTargetGA) && 1644 "Cannot set target flags on target-independent globals"); 1645 1646 // Truncate (with sign-extension) the offset value to the pointer size. 1647 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1648 if (BitWidth < 64) 1649 Offset = SignExtend64(Offset, BitWidth); 1650 1651 unsigned Opc; 1652 if (GV->isThreadLocal()) 1653 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1654 else 1655 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1656 1657 FoldingSetNodeID ID; 1658 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1659 ID.AddPointer(GV); 1660 ID.AddInteger(Offset); 1661 ID.AddInteger(TargetFlags); 1662 void *IP = nullptr; 1663 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1664 return SDValue(E, 0); 1665 1666 auto *N = newSDNode<GlobalAddressSDNode>( 1667 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1668 CSEMap.InsertNode(N, IP); 1669 InsertNode(N); 1670 return SDValue(N, 0); 1671 } 1672 1673 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1674 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1675 FoldingSetNodeID ID; 1676 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1677 ID.AddInteger(FI); 1678 void *IP = nullptr; 1679 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1680 return SDValue(E, 0); 1681 1682 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1683 CSEMap.InsertNode(N, IP); 1684 InsertNode(N); 1685 return SDValue(N, 0); 1686 } 1687 1688 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1689 unsigned TargetFlags) { 1690 assert((TargetFlags == 0 || isTarget) && 1691 "Cannot set target flags on target-independent jump tables"); 1692 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1693 FoldingSetNodeID ID; 1694 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1695 ID.AddInteger(JTI); 1696 ID.AddInteger(TargetFlags); 1697 void *IP = nullptr; 1698 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1699 return SDValue(E, 0); 1700 1701 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1702 CSEMap.InsertNode(N, IP); 1703 InsertNode(N); 1704 return SDValue(N, 0); 1705 } 1706 1707 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1708 MaybeAlign Alignment, int Offset, 1709 bool isTarget, unsigned TargetFlags) { 1710 assert((TargetFlags == 0 || isTarget) && 1711 "Cannot set target flags on target-independent globals"); 1712 if (!Alignment) 1713 Alignment = shouldOptForSize() 1714 ? getDataLayout().getABITypeAlign(C->getType()) 1715 : getDataLayout().getPrefTypeAlign(C->getType()); 1716 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1717 FoldingSetNodeID ID; 1718 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1719 ID.AddInteger(Alignment->value()); 1720 ID.AddInteger(Offset); 1721 ID.AddPointer(C); 1722 ID.AddInteger(TargetFlags); 1723 void *IP = nullptr; 1724 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1725 return SDValue(E, 0); 1726 1727 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1728 TargetFlags); 1729 CSEMap.InsertNode(N, IP); 1730 InsertNode(N); 1731 SDValue V = SDValue(N, 0); 1732 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1733 return V; 1734 } 1735 1736 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1737 MaybeAlign Alignment, int Offset, 1738 bool isTarget, unsigned TargetFlags) { 1739 assert((TargetFlags == 0 || isTarget) && 1740 "Cannot set target flags on target-independent globals"); 1741 if (!Alignment) 1742 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1743 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1744 FoldingSetNodeID ID; 1745 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1746 ID.AddInteger(Alignment->value()); 1747 ID.AddInteger(Offset); 1748 C->addSelectionDAGCSEId(ID); 1749 ID.AddInteger(TargetFlags); 1750 void *IP = nullptr; 1751 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1752 return SDValue(E, 0); 1753 1754 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1755 TargetFlags); 1756 CSEMap.InsertNode(N, IP); 1757 InsertNode(N); 1758 return SDValue(N, 0); 1759 } 1760 1761 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1762 unsigned TargetFlags) { 1763 FoldingSetNodeID ID; 1764 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1765 ID.AddInteger(Index); 1766 ID.AddInteger(Offset); 1767 ID.AddInteger(TargetFlags); 1768 void *IP = nullptr; 1769 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1770 return SDValue(E, 0); 1771 1772 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1773 CSEMap.InsertNode(N, IP); 1774 InsertNode(N); 1775 return SDValue(N, 0); 1776 } 1777 1778 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1779 FoldingSetNodeID ID; 1780 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1781 ID.AddPointer(MBB); 1782 void *IP = nullptr; 1783 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1784 return SDValue(E, 0); 1785 1786 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1787 CSEMap.InsertNode(N, IP); 1788 InsertNode(N); 1789 return SDValue(N, 0); 1790 } 1791 1792 SDValue SelectionDAG::getValueType(EVT VT) { 1793 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1794 ValueTypeNodes.size()) 1795 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1796 1797 SDNode *&N = VT.isExtended() ? 1798 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1799 1800 if (N) return SDValue(N, 0); 1801 N = newSDNode<VTSDNode>(VT); 1802 InsertNode(N); 1803 return SDValue(N, 0); 1804 } 1805 1806 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1807 SDNode *&N = ExternalSymbols[Sym]; 1808 if (N) return SDValue(N, 0); 1809 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1810 InsertNode(N); 1811 return SDValue(N, 0); 1812 } 1813 1814 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1815 SDNode *&N = MCSymbols[Sym]; 1816 if (N) 1817 return SDValue(N, 0); 1818 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1819 InsertNode(N); 1820 return SDValue(N, 0); 1821 } 1822 1823 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1824 unsigned TargetFlags) { 1825 SDNode *&N = 1826 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1827 if (N) return SDValue(N, 0); 1828 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1829 InsertNode(N); 1830 return SDValue(N, 0); 1831 } 1832 1833 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1834 if ((unsigned)Cond >= CondCodeNodes.size()) 1835 CondCodeNodes.resize(Cond+1); 1836 1837 if (!CondCodeNodes[Cond]) { 1838 auto *N = newSDNode<CondCodeSDNode>(Cond); 1839 CondCodeNodes[Cond] = N; 1840 InsertNode(N); 1841 } 1842 1843 return SDValue(CondCodeNodes[Cond], 0); 1844 } 1845 1846 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1847 APInt One(ResVT.getScalarSizeInBits(), 1); 1848 return getStepVector(DL, ResVT, One); 1849 } 1850 1851 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1852 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1853 if (ResVT.isScalableVector()) 1854 return getNode( 1855 ISD::STEP_VECTOR, DL, ResVT, 1856 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1857 1858 SmallVector<SDValue, 16> OpsStepConstants; 1859 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1860 OpsStepConstants.push_back( 1861 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1862 return getBuildVector(ResVT, DL, OpsStepConstants); 1863 } 1864 1865 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1866 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1867 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1868 std::swap(N1, N2); 1869 ShuffleVectorSDNode::commuteMask(M); 1870 } 1871 1872 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1873 SDValue N2, ArrayRef<int> Mask) { 1874 assert(VT.getVectorNumElements() == Mask.size() && 1875 "Must have the same number of vector elements as mask elements!"); 1876 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1877 "Invalid VECTOR_SHUFFLE"); 1878 1879 // Canonicalize shuffle undef, undef -> undef 1880 if (N1.isUndef() && N2.isUndef()) 1881 return getUNDEF(VT); 1882 1883 // Validate that all indices in Mask are within the range of the elements 1884 // input to the shuffle. 1885 int NElts = Mask.size(); 1886 assert(llvm::all_of(Mask, 1887 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1888 "Index out of range"); 1889 1890 // Copy the mask so we can do any needed cleanup. 1891 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1892 1893 // Canonicalize shuffle v, v -> v, undef 1894 if (N1 == N2) { 1895 N2 = getUNDEF(VT); 1896 for (int i = 0; i != NElts; ++i) 1897 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1898 } 1899 1900 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1901 if (N1.isUndef()) 1902 commuteShuffle(N1, N2, MaskVec); 1903 1904 if (TLI->hasVectorBlend()) { 1905 // If shuffling a splat, try to blend the splat instead. We do this here so 1906 // that even when this arises during lowering we don't have to re-handle it. 1907 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1908 BitVector UndefElements; 1909 SDValue Splat = BV->getSplatValue(&UndefElements); 1910 if (!Splat) 1911 return; 1912 1913 for (int i = 0; i < NElts; ++i) { 1914 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1915 continue; 1916 1917 // If this input comes from undef, mark it as such. 1918 if (UndefElements[MaskVec[i] - Offset]) { 1919 MaskVec[i] = -1; 1920 continue; 1921 } 1922 1923 // If we can blend a non-undef lane, use that instead. 1924 if (!UndefElements[i]) 1925 MaskVec[i] = i + Offset; 1926 } 1927 }; 1928 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1929 BlendSplat(N1BV, 0); 1930 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1931 BlendSplat(N2BV, NElts); 1932 } 1933 1934 // Canonicalize all index into lhs, -> shuffle lhs, undef 1935 // Canonicalize all index into rhs, -> shuffle rhs, undef 1936 bool AllLHS = true, AllRHS = true; 1937 bool N2Undef = N2.isUndef(); 1938 for (int i = 0; i != NElts; ++i) { 1939 if (MaskVec[i] >= NElts) { 1940 if (N2Undef) 1941 MaskVec[i] = -1; 1942 else 1943 AllLHS = false; 1944 } else if (MaskVec[i] >= 0) { 1945 AllRHS = false; 1946 } 1947 } 1948 if (AllLHS && AllRHS) 1949 return getUNDEF(VT); 1950 if (AllLHS && !N2Undef) 1951 N2 = getUNDEF(VT); 1952 if (AllRHS) { 1953 N1 = getUNDEF(VT); 1954 commuteShuffle(N1, N2, MaskVec); 1955 } 1956 // Reset our undef status after accounting for the mask. 1957 N2Undef = N2.isUndef(); 1958 // Re-check whether both sides ended up undef. 1959 if (N1.isUndef() && N2Undef) 1960 return getUNDEF(VT); 1961 1962 // If Identity shuffle return that node. 1963 bool Identity = true, AllSame = true; 1964 for (int i = 0; i != NElts; ++i) { 1965 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1966 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1967 } 1968 if (Identity && NElts) 1969 return N1; 1970 1971 // Shuffling a constant splat doesn't change the result. 1972 if (N2Undef) { 1973 SDValue V = N1; 1974 1975 // Look through any bitcasts. We check that these don't change the number 1976 // (and size) of elements and just changes their types. 1977 while (V.getOpcode() == ISD::BITCAST) 1978 V = V->getOperand(0); 1979 1980 // A splat should always show up as a build vector node. 1981 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1982 BitVector UndefElements; 1983 SDValue Splat = BV->getSplatValue(&UndefElements); 1984 // If this is a splat of an undef, shuffling it is also undef. 1985 if (Splat && Splat.isUndef()) 1986 return getUNDEF(VT); 1987 1988 bool SameNumElts = 1989 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1990 1991 // We only have a splat which can skip shuffles if there is a splatted 1992 // value and no undef lanes rearranged by the shuffle. 1993 if (Splat && UndefElements.none()) { 1994 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1995 // number of elements match or the value splatted is a zero constant. 1996 if (SameNumElts) 1997 return N1; 1998 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1999 if (C->isZero()) 2000 return N1; 2001 } 2002 2003 // If the shuffle itself creates a splat, build the vector directly. 2004 if (AllSame && SameNumElts) { 2005 EVT BuildVT = BV->getValueType(0); 2006 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2007 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2008 2009 // We may have jumped through bitcasts, so the type of the 2010 // BUILD_VECTOR may not match the type of the shuffle. 2011 if (BuildVT != VT) 2012 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2013 return NewBV; 2014 } 2015 } 2016 } 2017 2018 FoldingSetNodeID ID; 2019 SDValue Ops[2] = { N1, N2 }; 2020 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2021 for (int i = 0; i != NElts; ++i) 2022 ID.AddInteger(MaskVec[i]); 2023 2024 void* IP = nullptr; 2025 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2026 return SDValue(E, 0); 2027 2028 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2029 // SDNode doesn't have access to it. This memory will be "leaked" when 2030 // the node is deallocated, but recovered when the NodeAllocator is released. 2031 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2032 llvm::copy(MaskVec, MaskAlloc); 2033 2034 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2035 dl.getDebugLoc(), MaskAlloc); 2036 createOperands(N, Ops); 2037 2038 CSEMap.InsertNode(N, IP); 2039 InsertNode(N); 2040 SDValue V = SDValue(N, 0); 2041 NewSDValueDbgMsg(V, "Creating new node: ", this); 2042 return V; 2043 } 2044 2045 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2046 EVT VT = SV.getValueType(0); 2047 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2048 ShuffleVectorSDNode::commuteMask(MaskVec); 2049 2050 SDValue Op0 = SV.getOperand(0); 2051 SDValue Op1 = SV.getOperand(1); 2052 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2053 } 2054 2055 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2056 FoldingSetNodeID ID; 2057 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2058 ID.AddInteger(RegNo); 2059 void *IP = nullptr; 2060 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2061 return SDValue(E, 0); 2062 2063 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2064 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2065 CSEMap.InsertNode(N, IP); 2066 InsertNode(N); 2067 return SDValue(N, 0); 2068 } 2069 2070 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2071 FoldingSetNodeID ID; 2072 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2073 ID.AddPointer(RegMask); 2074 void *IP = nullptr; 2075 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2076 return SDValue(E, 0); 2077 2078 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2079 CSEMap.InsertNode(N, IP); 2080 InsertNode(N); 2081 return SDValue(N, 0); 2082 } 2083 2084 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2085 MCSymbol *Label) { 2086 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2087 } 2088 2089 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2090 SDValue Root, MCSymbol *Label) { 2091 FoldingSetNodeID ID; 2092 SDValue Ops[] = { Root }; 2093 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2094 ID.AddPointer(Label); 2095 void *IP = nullptr; 2096 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2097 return SDValue(E, 0); 2098 2099 auto *N = 2100 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2101 createOperands(N, Ops); 2102 2103 CSEMap.InsertNode(N, IP); 2104 InsertNode(N); 2105 return SDValue(N, 0); 2106 } 2107 2108 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2109 int64_t Offset, bool isTarget, 2110 unsigned TargetFlags) { 2111 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2112 2113 FoldingSetNodeID ID; 2114 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2115 ID.AddPointer(BA); 2116 ID.AddInteger(Offset); 2117 ID.AddInteger(TargetFlags); 2118 void *IP = nullptr; 2119 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2120 return SDValue(E, 0); 2121 2122 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2123 CSEMap.InsertNode(N, IP); 2124 InsertNode(N); 2125 return SDValue(N, 0); 2126 } 2127 2128 SDValue SelectionDAG::getSrcValue(const Value *V) { 2129 FoldingSetNodeID ID; 2130 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2131 ID.AddPointer(V); 2132 2133 void *IP = nullptr; 2134 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2135 return SDValue(E, 0); 2136 2137 auto *N = newSDNode<SrcValueSDNode>(V); 2138 CSEMap.InsertNode(N, IP); 2139 InsertNode(N); 2140 return SDValue(N, 0); 2141 } 2142 2143 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2144 FoldingSetNodeID ID; 2145 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2146 ID.AddPointer(MD); 2147 2148 void *IP = nullptr; 2149 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2150 return SDValue(E, 0); 2151 2152 auto *N = newSDNode<MDNodeSDNode>(MD); 2153 CSEMap.InsertNode(N, IP); 2154 InsertNode(N); 2155 return SDValue(N, 0); 2156 } 2157 2158 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2159 if (VT == V.getValueType()) 2160 return V; 2161 2162 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2163 } 2164 2165 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2166 unsigned SrcAS, unsigned DestAS) { 2167 SDValue Ops[] = {Ptr}; 2168 FoldingSetNodeID ID; 2169 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2170 ID.AddInteger(SrcAS); 2171 ID.AddInteger(DestAS); 2172 2173 void *IP = nullptr; 2174 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2175 return SDValue(E, 0); 2176 2177 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2178 VT, SrcAS, DestAS); 2179 createOperands(N, Ops); 2180 2181 CSEMap.InsertNode(N, IP); 2182 InsertNode(N); 2183 return SDValue(N, 0); 2184 } 2185 2186 SDValue SelectionDAG::getFreeze(SDValue V) { 2187 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2188 } 2189 2190 /// getShiftAmountOperand - Return the specified value casted to 2191 /// the target's desired shift amount type. 2192 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2193 EVT OpTy = Op.getValueType(); 2194 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2195 if (OpTy == ShTy || OpTy.isVector()) return Op; 2196 2197 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2198 } 2199 2200 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2201 SDLoc dl(Node); 2202 const TargetLowering &TLI = getTargetLoweringInfo(); 2203 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2204 EVT VT = Node->getValueType(0); 2205 SDValue Tmp1 = Node->getOperand(0); 2206 SDValue Tmp2 = Node->getOperand(1); 2207 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2208 2209 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2210 Tmp2, MachinePointerInfo(V)); 2211 SDValue VAList = VAListLoad; 2212 2213 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2214 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2215 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2216 2217 VAList = 2218 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2219 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2220 } 2221 2222 // Increment the pointer, VAList, to the next vaarg 2223 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2224 getConstant(getDataLayout().getTypeAllocSize( 2225 VT.getTypeForEVT(*getContext())), 2226 dl, VAList.getValueType())); 2227 // Store the incremented VAList to the legalized pointer 2228 Tmp1 = 2229 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2230 // Load the actual argument out of the pointer VAList 2231 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2232 } 2233 2234 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2235 SDLoc dl(Node); 2236 const TargetLowering &TLI = getTargetLoweringInfo(); 2237 // This defaults to loading a pointer from the input and storing it to the 2238 // output, returning the chain. 2239 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2240 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2241 SDValue Tmp1 = 2242 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2243 Node->getOperand(2), MachinePointerInfo(VS)); 2244 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2245 MachinePointerInfo(VD)); 2246 } 2247 2248 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2249 const DataLayout &DL = getDataLayout(); 2250 Type *Ty = VT.getTypeForEVT(*getContext()); 2251 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2252 2253 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2254 return RedAlign; 2255 2256 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2257 const Align StackAlign = TFI->getStackAlign(); 2258 2259 // See if we can choose a smaller ABI alignment in cases where it's an 2260 // illegal vector type that will get broken down. 2261 if (RedAlign > StackAlign) { 2262 EVT IntermediateVT; 2263 MVT RegisterVT; 2264 unsigned NumIntermediates; 2265 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2266 NumIntermediates, RegisterVT); 2267 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2268 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2269 if (RedAlign2 < RedAlign) 2270 RedAlign = RedAlign2; 2271 } 2272 2273 return RedAlign; 2274 } 2275 2276 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2277 MachineFrameInfo &MFI = MF->getFrameInfo(); 2278 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2279 int StackID = 0; 2280 if (Bytes.isScalable()) 2281 StackID = TFI->getStackIDForScalableVectors(); 2282 // The stack id gives an indication of whether the object is scalable or 2283 // not, so it's safe to pass in the minimum size here. 2284 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2285 false, nullptr, StackID); 2286 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2287 } 2288 2289 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2290 Type *Ty = VT.getTypeForEVT(*getContext()); 2291 Align StackAlign = 2292 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2293 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2294 } 2295 2296 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2297 TypeSize VT1Size = VT1.getStoreSize(); 2298 TypeSize VT2Size = VT2.getStoreSize(); 2299 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2300 "Don't know how to choose the maximum size when creating a stack " 2301 "temporary"); 2302 TypeSize Bytes = 2303 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2304 2305 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2306 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2307 const DataLayout &DL = getDataLayout(); 2308 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2309 return CreateStackTemporary(Bytes, Align); 2310 } 2311 2312 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2313 ISD::CondCode Cond, const SDLoc &dl) { 2314 EVT OpVT = N1.getValueType(); 2315 2316 // These setcc operations always fold. 2317 switch (Cond) { 2318 default: break; 2319 case ISD::SETFALSE: 2320 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2321 case ISD::SETTRUE: 2322 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2323 2324 case ISD::SETOEQ: 2325 case ISD::SETOGT: 2326 case ISD::SETOGE: 2327 case ISD::SETOLT: 2328 case ISD::SETOLE: 2329 case ISD::SETONE: 2330 case ISD::SETO: 2331 case ISD::SETUO: 2332 case ISD::SETUEQ: 2333 case ISD::SETUNE: 2334 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2335 break; 2336 } 2337 2338 if (OpVT.isInteger()) { 2339 // For EQ and NE, we can always pick a value for the undef to make the 2340 // predicate pass or fail, so we can return undef. 2341 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2342 // icmp eq/ne X, undef -> undef. 2343 if ((N1.isUndef() || N2.isUndef()) && 2344 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2345 return getUNDEF(VT); 2346 2347 // If both operands are undef, we can return undef for int comparison. 2348 // icmp undef, undef -> undef. 2349 if (N1.isUndef() && N2.isUndef()) 2350 return getUNDEF(VT); 2351 2352 // icmp X, X -> true/false 2353 // icmp X, undef -> true/false because undef could be X. 2354 if (N1 == N2) 2355 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2356 } 2357 2358 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2359 const APInt &C2 = N2C->getAPIntValue(); 2360 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2361 const APInt &C1 = N1C->getAPIntValue(); 2362 2363 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2364 dl, VT, OpVT); 2365 } 2366 } 2367 2368 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2369 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2370 2371 if (N1CFP && N2CFP) { 2372 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2373 switch (Cond) { 2374 default: break; 2375 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2376 return getUNDEF(VT); 2377 LLVM_FALLTHROUGH; 2378 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2379 OpVT); 2380 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2381 return getUNDEF(VT); 2382 LLVM_FALLTHROUGH; 2383 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2384 R==APFloat::cmpLessThan, dl, VT, 2385 OpVT); 2386 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2387 return getUNDEF(VT); 2388 LLVM_FALLTHROUGH; 2389 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2390 OpVT); 2391 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2392 return getUNDEF(VT); 2393 LLVM_FALLTHROUGH; 2394 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2395 VT, OpVT); 2396 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2397 return getUNDEF(VT); 2398 LLVM_FALLTHROUGH; 2399 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2400 R==APFloat::cmpEqual, dl, VT, 2401 OpVT); 2402 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2403 return getUNDEF(VT); 2404 LLVM_FALLTHROUGH; 2405 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2406 R==APFloat::cmpEqual, dl, VT, OpVT); 2407 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2408 OpVT); 2409 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2410 OpVT); 2411 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2412 R==APFloat::cmpEqual, dl, VT, 2413 OpVT); 2414 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2415 OpVT); 2416 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2417 R==APFloat::cmpLessThan, dl, VT, 2418 OpVT); 2419 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2420 R==APFloat::cmpUnordered, dl, VT, 2421 OpVT); 2422 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2423 VT, OpVT); 2424 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2425 OpVT); 2426 } 2427 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2428 // Ensure that the constant occurs on the RHS. 2429 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2430 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2431 return SDValue(); 2432 return getSetCC(dl, VT, N2, N1, SwappedCond); 2433 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2434 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2435 // If an operand is known to be a nan (or undef that could be a nan), we can 2436 // fold it. 2437 // Choosing NaN for the undef will always make unordered comparison succeed 2438 // and ordered comparison fails. 2439 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2440 switch (ISD::getUnorderedFlavor(Cond)) { 2441 default: 2442 llvm_unreachable("Unknown flavor!"); 2443 case 0: // Known false. 2444 return getBoolConstant(false, dl, VT, OpVT); 2445 case 1: // Known true. 2446 return getBoolConstant(true, dl, VT, OpVT); 2447 case 2: // Undefined. 2448 return getUNDEF(VT); 2449 } 2450 } 2451 2452 // Could not fold it. 2453 return SDValue(); 2454 } 2455 2456 /// See if the specified operand can be simplified with the knowledge that only 2457 /// the bits specified by DemandedBits are used. 2458 /// TODO: really we should be making this into the DAG equivalent of 2459 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2460 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2461 EVT VT = V.getValueType(); 2462 2463 if (VT.isScalableVector()) 2464 return SDValue(); 2465 2466 APInt DemandedElts = VT.isVector() 2467 ? APInt::getAllOnes(VT.getVectorNumElements()) 2468 : APInt(1, 1); 2469 return GetDemandedBits(V, DemandedBits, DemandedElts); 2470 } 2471 2472 /// See if the specified operand can be simplified with the knowledge that only 2473 /// the bits specified by DemandedBits are used in the elements specified by 2474 /// DemandedElts. 2475 /// TODO: really we should be making this into the DAG equivalent of 2476 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2477 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2478 const APInt &DemandedElts) { 2479 switch (V.getOpcode()) { 2480 default: 2481 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2482 *this); 2483 case ISD::Constant: { 2484 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2485 APInt NewVal = CVal & DemandedBits; 2486 if (NewVal != CVal) 2487 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2488 break; 2489 } 2490 case ISD::SRL: 2491 // Only look at single-use SRLs. 2492 if (!V.getNode()->hasOneUse()) 2493 break; 2494 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2495 // See if we can recursively simplify the LHS. 2496 unsigned Amt = RHSC->getZExtValue(); 2497 2498 // Watch out for shift count overflow though. 2499 if (Amt >= DemandedBits.getBitWidth()) 2500 break; 2501 APInt SrcDemandedBits = DemandedBits << Amt; 2502 if (SDValue SimplifyLHS = 2503 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2504 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2505 V.getOperand(1)); 2506 } 2507 break; 2508 } 2509 return SDValue(); 2510 } 2511 2512 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2513 /// use this predicate to simplify operations downstream. 2514 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2515 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2516 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2517 } 2518 2519 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2520 /// this predicate to simplify operations downstream. Mask is known to be zero 2521 /// for bits that V cannot have. 2522 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2523 unsigned Depth) const { 2524 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2525 } 2526 2527 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2528 /// DemandedElts. We use this predicate to simplify operations downstream. 2529 /// Mask is known to be zero for bits that V cannot have. 2530 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2531 const APInt &DemandedElts, 2532 unsigned Depth) const { 2533 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2534 } 2535 2536 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2537 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2538 unsigned Depth) const { 2539 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2540 } 2541 2542 /// isSplatValue - Return true if the vector V has the same value 2543 /// across all DemandedElts. For scalable vectors it does not make 2544 /// sense to specify which elements are demanded or undefined, therefore 2545 /// they are simply ignored. 2546 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2547 APInt &UndefElts, unsigned Depth) const { 2548 unsigned Opcode = V.getOpcode(); 2549 EVT VT = V.getValueType(); 2550 assert(VT.isVector() && "Vector type expected"); 2551 2552 if (!VT.isScalableVector() && !DemandedElts) 2553 return false; // No demanded elts, better to assume we don't know anything. 2554 2555 if (Depth >= MaxRecursionDepth) 2556 return false; // Limit search depth. 2557 2558 // Deal with some common cases here that work for both fixed and scalable 2559 // vector types. 2560 switch (Opcode) { 2561 case ISD::SPLAT_VECTOR: 2562 UndefElts = V.getOperand(0).isUndef() 2563 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2564 : APInt(DemandedElts.getBitWidth(), 0); 2565 return true; 2566 case ISD::ADD: 2567 case ISD::SUB: 2568 case ISD::AND: 2569 case ISD::XOR: 2570 case ISD::OR: { 2571 APInt UndefLHS, UndefRHS; 2572 SDValue LHS = V.getOperand(0); 2573 SDValue RHS = V.getOperand(1); 2574 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2575 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2576 UndefElts = UndefLHS | UndefRHS; 2577 return true; 2578 } 2579 return false; 2580 } 2581 case ISD::ABS: 2582 case ISD::TRUNCATE: 2583 case ISD::SIGN_EXTEND: 2584 case ISD::ZERO_EXTEND: 2585 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2586 default: 2587 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2588 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2589 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth); 2590 break; 2591 } 2592 2593 // We don't support other cases than those above for scalable vectors at 2594 // the moment. 2595 if (VT.isScalableVector()) 2596 return false; 2597 2598 unsigned NumElts = VT.getVectorNumElements(); 2599 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2600 UndefElts = APInt::getZero(NumElts); 2601 2602 switch (Opcode) { 2603 case ISD::BUILD_VECTOR: { 2604 SDValue Scl; 2605 for (unsigned i = 0; i != NumElts; ++i) { 2606 SDValue Op = V.getOperand(i); 2607 if (Op.isUndef()) { 2608 UndefElts.setBit(i); 2609 continue; 2610 } 2611 if (!DemandedElts[i]) 2612 continue; 2613 if (Scl && Scl != Op) 2614 return false; 2615 Scl = Op; 2616 } 2617 return true; 2618 } 2619 case ISD::VECTOR_SHUFFLE: { 2620 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2621 APInt DemandedLHS = APInt::getNullValue(NumElts); 2622 APInt DemandedRHS = APInt::getNullValue(NumElts); 2623 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2624 for (int i = 0; i != (int)NumElts; ++i) { 2625 int M = Mask[i]; 2626 if (M < 0) { 2627 UndefElts.setBit(i); 2628 continue; 2629 } 2630 if (!DemandedElts[i]) 2631 continue; 2632 if (M < (int)NumElts) 2633 DemandedLHS.setBit(M); 2634 else 2635 DemandedRHS.setBit(M - NumElts); 2636 } 2637 2638 // If we aren't demanding either op, assume there's no splat. 2639 // If we are demanding both ops, assume there's no splat. 2640 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2641 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2642 return false; 2643 2644 // See if the demanded elts of the source op is a splat or we only demand 2645 // one element, which should always be a splat. 2646 // TODO: Handle source ops splats with undefs. 2647 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2648 APInt SrcUndefs; 2649 return (SrcElts.countPopulation() == 1) || 2650 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2651 (SrcElts & SrcUndefs).isZero()); 2652 }; 2653 if (!DemandedLHS.isZero()) 2654 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2655 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2656 } 2657 case ISD::EXTRACT_SUBVECTOR: { 2658 // Offset the demanded elts by the subvector index. 2659 SDValue Src = V.getOperand(0); 2660 // We don't support scalable vectors at the moment. 2661 if (Src.getValueType().isScalableVector()) 2662 return false; 2663 uint64_t Idx = V.getConstantOperandVal(1); 2664 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2665 APInt UndefSrcElts; 2666 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2667 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2668 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2669 return true; 2670 } 2671 break; 2672 } 2673 case ISD::ANY_EXTEND_VECTOR_INREG: 2674 case ISD::SIGN_EXTEND_VECTOR_INREG: 2675 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2676 // Widen the demanded elts by the src element count. 2677 SDValue Src = V.getOperand(0); 2678 // We don't support scalable vectors at the moment. 2679 if (Src.getValueType().isScalableVector()) 2680 return false; 2681 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2682 APInt UndefSrcElts; 2683 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 2684 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2685 UndefElts = UndefSrcElts.truncOrSelf(NumElts); 2686 return true; 2687 } 2688 break; 2689 } 2690 case ISD::BITCAST: { 2691 SDValue Src = V.getOperand(0); 2692 EVT SrcVT = Src.getValueType(); 2693 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2694 unsigned BitWidth = VT.getScalarSizeInBits(); 2695 2696 // Ignore bitcasts from unsupported types. 2697 // TODO: Add fp support? 2698 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2699 break; 2700 2701 // Bitcast 'small element' vector to 'large element' vector. 2702 if ((BitWidth % SrcBitWidth) == 0) { 2703 // See if each sub element is a splat. 2704 unsigned Scale = BitWidth / SrcBitWidth; 2705 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2706 APInt ScaledDemandedElts = 2707 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2708 for (unsigned I = 0; I != Scale; ++I) { 2709 APInt SubUndefElts; 2710 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2711 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2712 SubDemandedElts &= ScaledDemandedElts; 2713 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2714 return false; 2715 // TODO: Add support for merging sub undef elements. 2716 if (SubDemandedElts.isSubsetOf(SubUndefElts)) 2717 return false; 2718 } 2719 return true; 2720 } 2721 break; 2722 } 2723 } 2724 2725 return false; 2726 } 2727 2728 /// Helper wrapper to main isSplatValue function. 2729 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2730 EVT VT = V.getValueType(); 2731 assert(VT.isVector() && "Vector type expected"); 2732 2733 APInt UndefElts; 2734 APInt DemandedElts; 2735 2736 // For now we don't support this with scalable vectors. 2737 if (!VT.isScalableVector()) 2738 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2739 return isSplatValue(V, DemandedElts, UndefElts) && 2740 (AllowUndefs || !UndefElts); 2741 } 2742 2743 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2744 V = peekThroughExtractSubvectors(V); 2745 2746 EVT VT = V.getValueType(); 2747 unsigned Opcode = V.getOpcode(); 2748 switch (Opcode) { 2749 default: { 2750 APInt UndefElts; 2751 APInt DemandedElts; 2752 2753 if (!VT.isScalableVector()) 2754 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2755 2756 if (isSplatValue(V, DemandedElts, UndefElts)) { 2757 if (VT.isScalableVector()) { 2758 // DemandedElts and UndefElts are ignored for scalable vectors, since 2759 // the only supported cases are SPLAT_VECTOR nodes. 2760 SplatIdx = 0; 2761 } else { 2762 // Handle case where all demanded elements are UNDEF. 2763 if (DemandedElts.isSubsetOf(UndefElts)) { 2764 SplatIdx = 0; 2765 return getUNDEF(VT); 2766 } 2767 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2768 } 2769 return V; 2770 } 2771 break; 2772 } 2773 case ISD::SPLAT_VECTOR: 2774 SplatIdx = 0; 2775 return V; 2776 case ISD::VECTOR_SHUFFLE: { 2777 if (VT.isScalableVector()) 2778 return SDValue(); 2779 2780 // Check if this is a shuffle node doing a splat. 2781 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2782 // getTargetVShiftNode currently struggles without the splat source. 2783 auto *SVN = cast<ShuffleVectorSDNode>(V); 2784 if (!SVN->isSplat()) 2785 break; 2786 int Idx = SVN->getSplatIndex(); 2787 int NumElts = V.getValueType().getVectorNumElements(); 2788 SplatIdx = Idx % NumElts; 2789 return V.getOperand(Idx / NumElts); 2790 } 2791 } 2792 2793 return SDValue(); 2794 } 2795 2796 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2797 int SplatIdx; 2798 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2799 EVT SVT = SrcVector.getValueType().getScalarType(); 2800 EVT LegalSVT = SVT; 2801 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2802 if (!SVT.isInteger()) 2803 return SDValue(); 2804 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2805 if (LegalSVT.bitsLT(SVT)) 2806 return SDValue(); 2807 } 2808 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2809 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2810 } 2811 return SDValue(); 2812 } 2813 2814 const APInt * 2815 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2816 const APInt &DemandedElts) const { 2817 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2818 V.getOpcode() == ISD::SRA) && 2819 "Unknown shift node"); 2820 unsigned BitWidth = V.getScalarValueSizeInBits(); 2821 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2822 // Shifting more than the bitwidth is not valid. 2823 const APInt &ShAmt = SA->getAPIntValue(); 2824 if (ShAmt.ult(BitWidth)) 2825 return &ShAmt; 2826 } 2827 return nullptr; 2828 } 2829 2830 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2831 SDValue V, const APInt &DemandedElts) const { 2832 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2833 V.getOpcode() == ISD::SRA) && 2834 "Unknown shift node"); 2835 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2836 return ValidAmt; 2837 unsigned BitWidth = V.getScalarValueSizeInBits(); 2838 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2839 if (!BV) 2840 return nullptr; 2841 const APInt *MinShAmt = nullptr; 2842 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2843 if (!DemandedElts[i]) 2844 continue; 2845 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2846 if (!SA) 2847 return nullptr; 2848 // Shifting more than the bitwidth is not valid. 2849 const APInt &ShAmt = SA->getAPIntValue(); 2850 if (ShAmt.uge(BitWidth)) 2851 return nullptr; 2852 if (MinShAmt && MinShAmt->ule(ShAmt)) 2853 continue; 2854 MinShAmt = &ShAmt; 2855 } 2856 return MinShAmt; 2857 } 2858 2859 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2860 SDValue V, const APInt &DemandedElts) const { 2861 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2862 V.getOpcode() == ISD::SRA) && 2863 "Unknown shift node"); 2864 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2865 return ValidAmt; 2866 unsigned BitWidth = V.getScalarValueSizeInBits(); 2867 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2868 if (!BV) 2869 return nullptr; 2870 const APInt *MaxShAmt = nullptr; 2871 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2872 if (!DemandedElts[i]) 2873 continue; 2874 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2875 if (!SA) 2876 return nullptr; 2877 // Shifting more than the bitwidth is not valid. 2878 const APInt &ShAmt = SA->getAPIntValue(); 2879 if (ShAmt.uge(BitWidth)) 2880 return nullptr; 2881 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2882 continue; 2883 MaxShAmt = &ShAmt; 2884 } 2885 return MaxShAmt; 2886 } 2887 2888 /// Determine which bits of Op are known to be either zero or one and return 2889 /// them in Known. For vectors, the known bits are those that are shared by 2890 /// every vector element. 2891 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2892 EVT VT = Op.getValueType(); 2893 2894 // TOOD: Until we have a plan for how to represent demanded elements for 2895 // scalable vectors, we can just bail out for now. 2896 if (Op.getValueType().isScalableVector()) { 2897 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2898 return KnownBits(BitWidth); 2899 } 2900 2901 APInt DemandedElts = VT.isVector() 2902 ? APInt::getAllOnes(VT.getVectorNumElements()) 2903 : APInt(1, 1); 2904 return computeKnownBits(Op, DemandedElts, Depth); 2905 } 2906 2907 /// Determine which bits of Op are known to be either zero or one and return 2908 /// them in Known. The DemandedElts argument allows us to only collect the known 2909 /// bits that are shared by the requested vector elements. 2910 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2911 unsigned Depth) const { 2912 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2913 2914 KnownBits Known(BitWidth); // Don't know anything. 2915 2916 // TOOD: Until we have a plan for how to represent demanded elements for 2917 // scalable vectors, we can just bail out for now. 2918 if (Op.getValueType().isScalableVector()) 2919 return Known; 2920 2921 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2922 // We know all of the bits for a constant! 2923 return KnownBits::makeConstant(C->getAPIntValue()); 2924 } 2925 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2926 // We know all of the bits for a constant fp! 2927 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2928 } 2929 2930 if (Depth >= MaxRecursionDepth) 2931 return Known; // Limit search depth. 2932 2933 KnownBits Known2; 2934 unsigned NumElts = DemandedElts.getBitWidth(); 2935 assert((!Op.getValueType().isVector() || 2936 NumElts == Op.getValueType().getVectorNumElements()) && 2937 "Unexpected vector size"); 2938 2939 if (!DemandedElts) 2940 return Known; // No demanded elts, better to assume we don't know anything. 2941 2942 unsigned Opcode = Op.getOpcode(); 2943 switch (Opcode) { 2944 case ISD::BUILD_VECTOR: 2945 // Collect the known bits that are shared by every demanded vector element. 2946 Known.Zero.setAllBits(); Known.One.setAllBits(); 2947 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2948 if (!DemandedElts[i]) 2949 continue; 2950 2951 SDValue SrcOp = Op.getOperand(i); 2952 Known2 = computeKnownBits(SrcOp, Depth + 1); 2953 2954 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2955 if (SrcOp.getValueSizeInBits() != BitWidth) { 2956 assert(SrcOp.getValueSizeInBits() > BitWidth && 2957 "Expected BUILD_VECTOR implicit truncation"); 2958 Known2 = Known2.trunc(BitWidth); 2959 } 2960 2961 // Known bits are the values that are shared by every demanded element. 2962 Known = KnownBits::commonBits(Known, Known2); 2963 2964 // If we don't know any bits, early out. 2965 if (Known.isUnknown()) 2966 break; 2967 } 2968 break; 2969 case ISD::VECTOR_SHUFFLE: { 2970 // Collect the known bits that are shared by every vector element referenced 2971 // by the shuffle. 2972 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2973 Known.Zero.setAllBits(); Known.One.setAllBits(); 2974 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2975 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2976 for (unsigned i = 0; i != NumElts; ++i) { 2977 if (!DemandedElts[i]) 2978 continue; 2979 2980 int M = SVN->getMaskElt(i); 2981 if (M < 0) { 2982 // For UNDEF elements, we don't know anything about the common state of 2983 // the shuffle result. 2984 Known.resetAll(); 2985 DemandedLHS.clearAllBits(); 2986 DemandedRHS.clearAllBits(); 2987 break; 2988 } 2989 2990 if ((unsigned)M < NumElts) 2991 DemandedLHS.setBit((unsigned)M % NumElts); 2992 else 2993 DemandedRHS.setBit((unsigned)M % NumElts); 2994 } 2995 // Known bits are the values that are shared by every demanded element. 2996 if (!!DemandedLHS) { 2997 SDValue LHS = Op.getOperand(0); 2998 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2999 Known = KnownBits::commonBits(Known, Known2); 3000 } 3001 // If we don't know any bits, early out. 3002 if (Known.isUnknown()) 3003 break; 3004 if (!!DemandedRHS) { 3005 SDValue RHS = Op.getOperand(1); 3006 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3007 Known = KnownBits::commonBits(Known, Known2); 3008 } 3009 break; 3010 } 3011 case ISD::CONCAT_VECTORS: { 3012 // Split DemandedElts and test each of the demanded subvectors. 3013 Known.Zero.setAllBits(); Known.One.setAllBits(); 3014 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3015 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3016 unsigned NumSubVectors = Op.getNumOperands(); 3017 for (unsigned i = 0; i != NumSubVectors; ++i) { 3018 APInt DemandedSub = 3019 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3020 if (!!DemandedSub) { 3021 SDValue Sub = Op.getOperand(i); 3022 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3023 Known = KnownBits::commonBits(Known, Known2); 3024 } 3025 // If we don't know any bits, early out. 3026 if (Known.isUnknown()) 3027 break; 3028 } 3029 break; 3030 } 3031 case ISD::INSERT_SUBVECTOR: { 3032 // Demand any elements from the subvector and the remainder from the src its 3033 // inserted into. 3034 SDValue Src = Op.getOperand(0); 3035 SDValue Sub = Op.getOperand(1); 3036 uint64_t Idx = Op.getConstantOperandVal(2); 3037 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3038 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3039 APInt DemandedSrcElts = DemandedElts; 3040 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3041 3042 Known.One.setAllBits(); 3043 Known.Zero.setAllBits(); 3044 if (!!DemandedSubElts) { 3045 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3046 if (Known.isUnknown()) 3047 break; // early-out. 3048 } 3049 if (!!DemandedSrcElts) { 3050 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3051 Known = KnownBits::commonBits(Known, Known2); 3052 } 3053 break; 3054 } 3055 case ISD::EXTRACT_SUBVECTOR: { 3056 // Offset the demanded elts by the subvector index. 3057 SDValue Src = Op.getOperand(0); 3058 // Bail until we can represent demanded elements for scalable vectors. 3059 if (Src.getValueType().isScalableVector()) 3060 break; 3061 uint64_t Idx = Op.getConstantOperandVal(1); 3062 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3063 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 3064 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3065 break; 3066 } 3067 case ISD::SCALAR_TO_VECTOR: { 3068 // We know about scalar_to_vector as much as we know about it source, 3069 // which becomes the first element of otherwise unknown vector. 3070 if (DemandedElts != 1) 3071 break; 3072 3073 SDValue N0 = Op.getOperand(0); 3074 Known = computeKnownBits(N0, Depth + 1); 3075 if (N0.getValueSizeInBits() != BitWidth) 3076 Known = Known.trunc(BitWidth); 3077 3078 break; 3079 } 3080 case ISD::BITCAST: { 3081 SDValue N0 = Op.getOperand(0); 3082 EVT SubVT = N0.getValueType(); 3083 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3084 3085 // Ignore bitcasts from unsupported types. 3086 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3087 break; 3088 3089 // Fast handling of 'identity' bitcasts. 3090 if (BitWidth == SubBitWidth) { 3091 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3092 break; 3093 } 3094 3095 bool IsLE = getDataLayout().isLittleEndian(); 3096 3097 // Bitcast 'small element' vector to 'large element' scalar/vector. 3098 if ((BitWidth % SubBitWidth) == 0) { 3099 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3100 3101 // Collect known bits for the (larger) output by collecting the known 3102 // bits from each set of sub elements and shift these into place. 3103 // We need to separately call computeKnownBits for each set of 3104 // sub elements as the knownbits for each is likely to be different. 3105 unsigned SubScale = BitWidth / SubBitWidth; 3106 APInt SubDemandedElts(NumElts * SubScale, 0); 3107 for (unsigned i = 0; i != NumElts; ++i) 3108 if (DemandedElts[i]) 3109 SubDemandedElts.setBit(i * SubScale); 3110 3111 for (unsigned i = 0; i != SubScale; ++i) { 3112 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3113 Depth + 1); 3114 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3115 Known.insertBits(Known2, SubBitWidth * Shifts); 3116 } 3117 } 3118 3119 // Bitcast 'large element' scalar/vector to 'small element' vector. 3120 if ((SubBitWidth % BitWidth) == 0) { 3121 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3122 3123 // Collect known bits for the (smaller) output by collecting the known 3124 // bits from the overlapping larger input elements and extracting the 3125 // sub sections we actually care about. 3126 unsigned SubScale = SubBitWidth / BitWidth; 3127 APInt SubDemandedElts = 3128 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3129 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3130 3131 Known.Zero.setAllBits(); Known.One.setAllBits(); 3132 for (unsigned i = 0; i != NumElts; ++i) 3133 if (DemandedElts[i]) { 3134 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3135 unsigned Offset = (Shifts % SubScale) * BitWidth; 3136 Known = KnownBits::commonBits(Known, 3137 Known2.extractBits(BitWidth, Offset)); 3138 // If we don't know any bits, early out. 3139 if (Known.isUnknown()) 3140 break; 3141 } 3142 } 3143 break; 3144 } 3145 case ISD::AND: 3146 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3147 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3148 3149 Known &= Known2; 3150 break; 3151 case ISD::OR: 3152 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3153 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3154 3155 Known |= Known2; 3156 break; 3157 case ISD::XOR: 3158 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3159 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3160 3161 Known ^= Known2; 3162 break; 3163 case ISD::MUL: { 3164 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3165 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3166 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3167 // TODO: SelfMultiply can be poison, but not undef. 3168 if (SelfMultiply) 3169 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3170 Op.getOperand(0), DemandedElts, false, Depth + 1); 3171 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3172 break; 3173 } 3174 case ISD::MULHU: { 3175 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3176 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3177 Known = KnownBits::mulhu(Known, Known2); 3178 break; 3179 } 3180 case ISD::MULHS: { 3181 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3182 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3183 Known = KnownBits::mulhs(Known, Known2); 3184 break; 3185 } 3186 case ISD::UMUL_LOHI: { 3187 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3188 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3189 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3190 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3191 if (Op.getResNo() == 0) 3192 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3193 else 3194 Known = KnownBits::mulhu(Known, Known2); 3195 break; 3196 } 3197 case ISD::SMUL_LOHI: { 3198 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3199 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3200 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3201 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3202 if (Op.getResNo() == 0) 3203 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3204 else 3205 Known = KnownBits::mulhs(Known, Known2); 3206 break; 3207 } 3208 case ISD::UDIV: { 3209 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3210 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3211 Known = KnownBits::udiv(Known, Known2); 3212 break; 3213 } 3214 case ISD::AVGCEILU: { 3215 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3216 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3217 Known = Known.zext(BitWidth + 1); 3218 Known2 = Known2.zext(BitWidth + 1); 3219 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3220 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3221 Known = Known.extractBits(BitWidth, 1); 3222 break; 3223 } 3224 case ISD::SELECT: 3225 case ISD::VSELECT: 3226 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3227 // If we don't know any bits, early out. 3228 if (Known.isUnknown()) 3229 break; 3230 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3231 3232 // Only known if known in both the LHS and RHS. 3233 Known = KnownBits::commonBits(Known, Known2); 3234 break; 3235 case ISD::SELECT_CC: 3236 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3237 // If we don't know any bits, early out. 3238 if (Known.isUnknown()) 3239 break; 3240 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3241 3242 // Only known if known in both the LHS and RHS. 3243 Known = KnownBits::commonBits(Known, Known2); 3244 break; 3245 case ISD::SMULO: 3246 case ISD::UMULO: 3247 if (Op.getResNo() != 1) 3248 break; 3249 // The boolean result conforms to getBooleanContents. 3250 // If we know the result of a setcc has the top bits zero, use this info. 3251 // We know that we have an integer-based boolean since these operations 3252 // are only available for integer. 3253 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3254 TargetLowering::ZeroOrOneBooleanContent && 3255 BitWidth > 1) 3256 Known.Zero.setBitsFrom(1); 3257 break; 3258 case ISD::SETCC: 3259 case ISD::STRICT_FSETCC: 3260 case ISD::STRICT_FSETCCS: { 3261 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3262 // If we know the result of a setcc has the top bits zero, use this info. 3263 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3264 TargetLowering::ZeroOrOneBooleanContent && 3265 BitWidth > 1) 3266 Known.Zero.setBitsFrom(1); 3267 break; 3268 } 3269 case ISD::SHL: 3270 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3271 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3272 Known = KnownBits::shl(Known, Known2); 3273 3274 // Minimum shift low bits are known zero. 3275 if (const APInt *ShMinAmt = 3276 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3277 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3278 break; 3279 case ISD::SRL: 3280 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3281 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3282 Known = KnownBits::lshr(Known, Known2); 3283 3284 // Minimum shift high bits are known zero. 3285 if (const APInt *ShMinAmt = 3286 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3287 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3288 break; 3289 case ISD::SRA: 3290 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3291 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3292 Known = KnownBits::ashr(Known, Known2); 3293 // TODO: Add minimum shift high known sign bits. 3294 break; 3295 case ISD::FSHL: 3296 case ISD::FSHR: 3297 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3298 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3299 3300 // For fshl, 0-shift returns the 1st arg. 3301 // For fshr, 0-shift returns the 2nd arg. 3302 if (Amt == 0) { 3303 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3304 DemandedElts, Depth + 1); 3305 break; 3306 } 3307 3308 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3309 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3310 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3311 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3312 if (Opcode == ISD::FSHL) { 3313 Known.One <<= Amt; 3314 Known.Zero <<= Amt; 3315 Known2.One.lshrInPlace(BitWidth - Amt); 3316 Known2.Zero.lshrInPlace(BitWidth - Amt); 3317 } else { 3318 Known.One <<= BitWidth - Amt; 3319 Known.Zero <<= BitWidth - Amt; 3320 Known2.One.lshrInPlace(Amt); 3321 Known2.Zero.lshrInPlace(Amt); 3322 } 3323 Known.One |= Known2.One; 3324 Known.Zero |= Known2.Zero; 3325 } 3326 break; 3327 case ISD::SIGN_EXTEND_INREG: { 3328 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3329 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3330 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3331 break; 3332 } 3333 case ISD::CTTZ: 3334 case ISD::CTTZ_ZERO_UNDEF: { 3335 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3336 // If we have a known 1, its position is our upper bound. 3337 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3338 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3339 Known.Zero.setBitsFrom(LowBits); 3340 break; 3341 } 3342 case ISD::CTLZ: 3343 case ISD::CTLZ_ZERO_UNDEF: { 3344 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3345 // If we have a known 1, its position is our upper bound. 3346 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3347 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3348 Known.Zero.setBitsFrom(LowBits); 3349 break; 3350 } 3351 case ISD::CTPOP: { 3352 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3353 // If we know some of the bits are zero, they can't be one. 3354 unsigned PossibleOnes = Known2.countMaxPopulation(); 3355 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3356 break; 3357 } 3358 case ISD::PARITY: { 3359 // Parity returns 0 everywhere but the LSB. 3360 Known.Zero.setBitsFrom(1); 3361 break; 3362 } 3363 case ISD::LOAD: { 3364 LoadSDNode *LD = cast<LoadSDNode>(Op); 3365 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3366 if (ISD::isNON_EXTLoad(LD) && Cst) { 3367 // Determine any common known bits from the loaded constant pool value. 3368 Type *CstTy = Cst->getType(); 3369 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3370 // If its a vector splat, then we can (quickly) reuse the scalar path. 3371 // NOTE: We assume all elements match and none are UNDEF. 3372 if (CstTy->isVectorTy()) { 3373 if (const Constant *Splat = Cst->getSplatValue()) { 3374 Cst = Splat; 3375 CstTy = Cst->getType(); 3376 } 3377 } 3378 // TODO - do we need to handle different bitwidths? 3379 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3380 // Iterate across all vector elements finding common known bits. 3381 Known.One.setAllBits(); 3382 Known.Zero.setAllBits(); 3383 for (unsigned i = 0; i != NumElts; ++i) { 3384 if (!DemandedElts[i]) 3385 continue; 3386 if (Constant *Elt = Cst->getAggregateElement(i)) { 3387 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3388 const APInt &Value = CInt->getValue(); 3389 Known.One &= Value; 3390 Known.Zero &= ~Value; 3391 continue; 3392 } 3393 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3394 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3395 Known.One &= Value; 3396 Known.Zero &= ~Value; 3397 continue; 3398 } 3399 } 3400 Known.One.clearAllBits(); 3401 Known.Zero.clearAllBits(); 3402 break; 3403 } 3404 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3405 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3406 Known = KnownBits::makeConstant(CInt->getValue()); 3407 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3408 Known = 3409 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3410 } 3411 } 3412 } 3413 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3414 // If this is a ZEXTLoad and we are looking at the loaded value. 3415 EVT VT = LD->getMemoryVT(); 3416 unsigned MemBits = VT.getScalarSizeInBits(); 3417 Known.Zero.setBitsFrom(MemBits); 3418 } else if (const MDNode *Ranges = LD->getRanges()) { 3419 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3420 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3421 } 3422 break; 3423 } 3424 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3425 EVT InVT = Op.getOperand(0).getValueType(); 3426 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3427 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3428 Known = Known.zext(BitWidth); 3429 break; 3430 } 3431 case ISD::ZERO_EXTEND: { 3432 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3433 Known = Known.zext(BitWidth); 3434 break; 3435 } 3436 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3437 EVT InVT = Op.getOperand(0).getValueType(); 3438 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3439 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3440 // If the sign bit is known to be zero or one, then sext will extend 3441 // it to the top bits, else it will just zext. 3442 Known = Known.sext(BitWidth); 3443 break; 3444 } 3445 case ISD::SIGN_EXTEND: { 3446 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3447 // If the sign bit is known to be zero or one, then sext will extend 3448 // it to the top bits, else it will just zext. 3449 Known = Known.sext(BitWidth); 3450 break; 3451 } 3452 case ISD::ANY_EXTEND_VECTOR_INREG: { 3453 EVT InVT = Op.getOperand(0).getValueType(); 3454 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3455 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3456 Known = Known.anyext(BitWidth); 3457 break; 3458 } 3459 case ISD::ANY_EXTEND: { 3460 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3461 Known = Known.anyext(BitWidth); 3462 break; 3463 } 3464 case ISD::TRUNCATE: { 3465 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3466 Known = Known.trunc(BitWidth); 3467 break; 3468 } 3469 case ISD::AssertZext: { 3470 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3471 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3472 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3473 Known.Zero |= (~InMask); 3474 Known.One &= (~Known.Zero); 3475 break; 3476 } 3477 case ISD::AssertAlign: { 3478 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3479 assert(LogOfAlign != 0); 3480 3481 // TODO: Should use maximum with source 3482 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3483 // well as clearing one bits. 3484 Known.Zero.setLowBits(LogOfAlign); 3485 Known.One.clearLowBits(LogOfAlign); 3486 break; 3487 } 3488 case ISD::FGETSIGN: 3489 // All bits are zero except the low bit. 3490 Known.Zero.setBitsFrom(1); 3491 break; 3492 case ISD::USUBO: 3493 case ISD::SSUBO: 3494 if (Op.getResNo() == 1) { 3495 // If we know the result of a setcc has the top bits zero, use this info. 3496 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3497 TargetLowering::ZeroOrOneBooleanContent && 3498 BitWidth > 1) 3499 Known.Zero.setBitsFrom(1); 3500 break; 3501 } 3502 LLVM_FALLTHROUGH; 3503 case ISD::SUB: 3504 case ISD::SUBC: { 3505 assert(Op.getResNo() == 0 && 3506 "We only compute knownbits for the difference here."); 3507 3508 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3509 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3510 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3511 Known, Known2); 3512 break; 3513 } 3514 case ISD::UADDO: 3515 case ISD::SADDO: 3516 case ISD::ADDCARRY: 3517 if (Op.getResNo() == 1) { 3518 // If we know the result of a setcc has the top bits zero, use this info. 3519 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3520 TargetLowering::ZeroOrOneBooleanContent && 3521 BitWidth > 1) 3522 Known.Zero.setBitsFrom(1); 3523 break; 3524 } 3525 LLVM_FALLTHROUGH; 3526 case ISD::ADD: 3527 case ISD::ADDC: 3528 case ISD::ADDE: { 3529 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3530 3531 // With ADDE and ADDCARRY, a carry bit may be added in. 3532 KnownBits Carry(1); 3533 if (Opcode == ISD::ADDE) 3534 // Can't track carry from glue, set carry to unknown. 3535 Carry.resetAll(); 3536 else if (Opcode == ISD::ADDCARRY) 3537 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3538 // the trouble (how often will we find a known carry bit). And I haven't 3539 // tested this very much yet, but something like this might work: 3540 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3541 // Carry = Carry.zextOrTrunc(1, false); 3542 Carry.resetAll(); 3543 else 3544 Carry.setAllZero(); 3545 3546 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3547 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3548 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3549 break; 3550 } 3551 case ISD::SREM: { 3552 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3553 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3554 Known = KnownBits::srem(Known, Known2); 3555 break; 3556 } 3557 case ISD::UREM: { 3558 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3559 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3560 Known = KnownBits::urem(Known, Known2); 3561 break; 3562 } 3563 case ISD::EXTRACT_ELEMENT: { 3564 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3565 const unsigned Index = Op.getConstantOperandVal(1); 3566 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3567 3568 // Remove low part of known bits mask 3569 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3570 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3571 3572 // Remove high part of known bit mask 3573 Known = Known.trunc(EltBitWidth); 3574 break; 3575 } 3576 case ISD::EXTRACT_VECTOR_ELT: { 3577 SDValue InVec = Op.getOperand(0); 3578 SDValue EltNo = Op.getOperand(1); 3579 EVT VecVT = InVec.getValueType(); 3580 // computeKnownBits not yet implemented for scalable vectors. 3581 if (VecVT.isScalableVector()) 3582 break; 3583 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3584 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3585 3586 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3587 // anything about the extended bits. 3588 if (BitWidth > EltBitWidth) 3589 Known = Known.trunc(EltBitWidth); 3590 3591 // If we know the element index, just demand that vector element, else for 3592 // an unknown element index, ignore DemandedElts and demand them all. 3593 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3594 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3595 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3596 DemandedSrcElts = 3597 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3598 3599 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3600 if (BitWidth > EltBitWidth) 3601 Known = Known.anyext(BitWidth); 3602 break; 3603 } 3604 case ISD::INSERT_VECTOR_ELT: { 3605 // If we know the element index, split the demand between the 3606 // source vector and the inserted element, otherwise assume we need 3607 // the original demanded vector elements and the value. 3608 SDValue InVec = Op.getOperand(0); 3609 SDValue InVal = Op.getOperand(1); 3610 SDValue EltNo = Op.getOperand(2); 3611 bool DemandedVal = true; 3612 APInt DemandedVecElts = DemandedElts; 3613 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3614 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3615 unsigned EltIdx = CEltNo->getZExtValue(); 3616 DemandedVal = !!DemandedElts[EltIdx]; 3617 DemandedVecElts.clearBit(EltIdx); 3618 } 3619 Known.One.setAllBits(); 3620 Known.Zero.setAllBits(); 3621 if (DemandedVal) { 3622 Known2 = computeKnownBits(InVal, Depth + 1); 3623 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3624 } 3625 if (!!DemandedVecElts) { 3626 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3627 Known = KnownBits::commonBits(Known, Known2); 3628 } 3629 break; 3630 } 3631 case ISD::BITREVERSE: { 3632 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3633 Known = Known2.reverseBits(); 3634 break; 3635 } 3636 case ISD::BSWAP: { 3637 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3638 Known = Known2.byteSwap(); 3639 break; 3640 } 3641 case ISD::ABS: { 3642 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3643 Known = Known2.abs(); 3644 break; 3645 } 3646 case ISD::USUBSAT: { 3647 // The result of usubsat will never be larger than the LHS. 3648 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3649 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3650 break; 3651 } 3652 case ISD::UMIN: { 3653 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3654 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3655 Known = KnownBits::umin(Known, Known2); 3656 break; 3657 } 3658 case ISD::UMAX: { 3659 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3660 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3661 Known = KnownBits::umax(Known, Known2); 3662 break; 3663 } 3664 case ISD::SMIN: 3665 case ISD::SMAX: { 3666 // If we have a clamp pattern, we know that the number of sign bits will be 3667 // the minimum of the clamp min/max range. 3668 bool IsMax = (Opcode == ISD::SMAX); 3669 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3670 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3671 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3672 CstHigh = 3673 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3674 if (CstLow && CstHigh) { 3675 if (!IsMax) 3676 std::swap(CstLow, CstHigh); 3677 3678 const APInt &ValueLow = CstLow->getAPIntValue(); 3679 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3680 if (ValueLow.sle(ValueHigh)) { 3681 unsigned LowSignBits = ValueLow.getNumSignBits(); 3682 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3683 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3684 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3685 Known.One.setHighBits(MinSignBits); 3686 break; 3687 } 3688 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3689 Known.Zero.setHighBits(MinSignBits); 3690 break; 3691 } 3692 } 3693 } 3694 3695 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3696 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3697 if (IsMax) 3698 Known = KnownBits::smax(Known, Known2); 3699 else 3700 Known = KnownBits::smin(Known, Known2); 3701 break; 3702 } 3703 case ISD::FP_TO_UINT_SAT: { 3704 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3705 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3706 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3707 break; 3708 } 3709 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3710 if (Op.getResNo() == 1) { 3711 // The boolean result conforms to getBooleanContents. 3712 // If we know the result of a setcc has the top bits zero, use this info. 3713 // We know that we have an integer-based boolean since these operations 3714 // are only available for integer. 3715 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3716 TargetLowering::ZeroOrOneBooleanContent && 3717 BitWidth > 1) 3718 Known.Zero.setBitsFrom(1); 3719 break; 3720 } 3721 LLVM_FALLTHROUGH; 3722 case ISD::ATOMIC_CMP_SWAP: 3723 case ISD::ATOMIC_SWAP: 3724 case ISD::ATOMIC_LOAD_ADD: 3725 case ISD::ATOMIC_LOAD_SUB: 3726 case ISD::ATOMIC_LOAD_AND: 3727 case ISD::ATOMIC_LOAD_CLR: 3728 case ISD::ATOMIC_LOAD_OR: 3729 case ISD::ATOMIC_LOAD_XOR: 3730 case ISD::ATOMIC_LOAD_NAND: 3731 case ISD::ATOMIC_LOAD_MIN: 3732 case ISD::ATOMIC_LOAD_MAX: 3733 case ISD::ATOMIC_LOAD_UMIN: 3734 case ISD::ATOMIC_LOAD_UMAX: 3735 case ISD::ATOMIC_LOAD: { 3736 unsigned MemBits = 3737 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3738 // If we are looking at the loaded value. 3739 if (Op.getResNo() == 0) { 3740 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3741 Known.Zero.setBitsFrom(MemBits); 3742 } 3743 break; 3744 } 3745 case ISD::FrameIndex: 3746 case ISD::TargetFrameIndex: 3747 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3748 Known, getMachineFunction()); 3749 break; 3750 3751 default: 3752 if (Opcode < ISD::BUILTIN_OP_END) 3753 break; 3754 LLVM_FALLTHROUGH; 3755 case ISD::INTRINSIC_WO_CHAIN: 3756 case ISD::INTRINSIC_W_CHAIN: 3757 case ISD::INTRINSIC_VOID: 3758 // Allow the target to implement this method for its nodes. 3759 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3760 break; 3761 } 3762 3763 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3764 return Known; 3765 } 3766 3767 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3768 SDValue N1) const { 3769 // X + 0 never overflow 3770 if (isNullConstant(N1)) 3771 return OFK_Never; 3772 3773 KnownBits N1Known = computeKnownBits(N1); 3774 if (N1Known.Zero.getBoolValue()) { 3775 KnownBits N0Known = computeKnownBits(N0); 3776 3777 bool overflow; 3778 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3779 if (!overflow) 3780 return OFK_Never; 3781 } 3782 3783 // mulhi + 1 never overflow 3784 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3785 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3786 return OFK_Never; 3787 3788 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3789 KnownBits N0Known = computeKnownBits(N0); 3790 3791 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3792 return OFK_Never; 3793 } 3794 3795 return OFK_Sometime; 3796 } 3797 3798 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3799 EVT OpVT = Val.getValueType(); 3800 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3801 3802 // Is the constant a known power of 2? 3803 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3804 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3805 3806 // A left-shift of a constant one will have exactly one bit set because 3807 // shifting the bit off the end is undefined. 3808 if (Val.getOpcode() == ISD::SHL) { 3809 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3810 if (C && C->getAPIntValue() == 1) 3811 return true; 3812 } 3813 3814 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3815 // one bit set. 3816 if (Val.getOpcode() == ISD::SRL) { 3817 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3818 if (C && C->getAPIntValue().isSignMask()) 3819 return true; 3820 } 3821 3822 // Are all operands of a build vector constant powers of two? 3823 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3824 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3825 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3826 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3827 return false; 3828 })) 3829 return true; 3830 3831 // Is the operand of a splat vector a constant power of two? 3832 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3833 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3834 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3835 return true; 3836 3837 // More could be done here, though the above checks are enough 3838 // to handle some common cases. 3839 3840 // Fall back to computeKnownBits to catch other known cases. 3841 KnownBits Known = computeKnownBits(Val); 3842 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3843 } 3844 3845 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3846 EVT VT = Op.getValueType(); 3847 3848 // TODO: Assume we don't know anything for now. 3849 if (VT.isScalableVector()) 3850 return 1; 3851 3852 APInt DemandedElts = VT.isVector() 3853 ? APInt::getAllOnes(VT.getVectorNumElements()) 3854 : APInt(1, 1); 3855 return ComputeNumSignBits(Op, DemandedElts, Depth); 3856 } 3857 3858 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3859 unsigned Depth) const { 3860 EVT VT = Op.getValueType(); 3861 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3862 unsigned VTBits = VT.getScalarSizeInBits(); 3863 unsigned NumElts = DemandedElts.getBitWidth(); 3864 unsigned Tmp, Tmp2; 3865 unsigned FirstAnswer = 1; 3866 3867 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3868 const APInt &Val = C->getAPIntValue(); 3869 return Val.getNumSignBits(); 3870 } 3871 3872 if (Depth >= MaxRecursionDepth) 3873 return 1; // Limit search depth. 3874 3875 if (!DemandedElts || VT.isScalableVector()) 3876 return 1; // No demanded elts, better to assume we don't know anything. 3877 3878 unsigned Opcode = Op.getOpcode(); 3879 switch (Opcode) { 3880 default: break; 3881 case ISD::AssertSext: 3882 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3883 return VTBits-Tmp+1; 3884 case ISD::AssertZext: 3885 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3886 return VTBits-Tmp; 3887 3888 case ISD::BUILD_VECTOR: 3889 Tmp = VTBits; 3890 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3891 if (!DemandedElts[i]) 3892 continue; 3893 3894 SDValue SrcOp = Op.getOperand(i); 3895 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3896 3897 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3898 if (SrcOp.getValueSizeInBits() != VTBits) { 3899 assert(SrcOp.getValueSizeInBits() > VTBits && 3900 "Expected BUILD_VECTOR implicit truncation"); 3901 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3902 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3903 } 3904 Tmp = std::min(Tmp, Tmp2); 3905 } 3906 return Tmp; 3907 3908 case ISD::VECTOR_SHUFFLE: { 3909 // Collect the minimum number of sign bits that are shared by every vector 3910 // element referenced by the shuffle. 3911 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3912 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3913 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3914 for (unsigned i = 0; i != NumElts; ++i) { 3915 int M = SVN->getMaskElt(i); 3916 if (!DemandedElts[i]) 3917 continue; 3918 // For UNDEF elements, we don't know anything about the common state of 3919 // the shuffle result. 3920 if (M < 0) 3921 return 1; 3922 if ((unsigned)M < NumElts) 3923 DemandedLHS.setBit((unsigned)M % NumElts); 3924 else 3925 DemandedRHS.setBit((unsigned)M % NumElts); 3926 } 3927 Tmp = std::numeric_limits<unsigned>::max(); 3928 if (!!DemandedLHS) 3929 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3930 if (!!DemandedRHS) { 3931 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3932 Tmp = std::min(Tmp, Tmp2); 3933 } 3934 // If we don't know anything, early out and try computeKnownBits fall-back. 3935 if (Tmp == 1) 3936 break; 3937 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3938 return Tmp; 3939 } 3940 3941 case ISD::BITCAST: { 3942 SDValue N0 = Op.getOperand(0); 3943 EVT SrcVT = N0.getValueType(); 3944 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3945 3946 // Ignore bitcasts from unsupported types.. 3947 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3948 break; 3949 3950 // Fast handling of 'identity' bitcasts. 3951 if (VTBits == SrcBits) 3952 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3953 3954 bool IsLE = getDataLayout().isLittleEndian(); 3955 3956 // Bitcast 'large element' scalar/vector to 'small element' vector. 3957 if ((SrcBits % VTBits) == 0) { 3958 assert(VT.isVector() && "Expected bitcast to vector"); 3959 3960 unsigned Scale = SrcBits / VTBits; 3961 APInt SrcDemandedElts = 3962 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3963 3964 // Fast case - sign splat can be simply split across the small elements. 3965 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3966 if (Tmp == SrcBits) 3967 return VTBits; 3968 3969 // Slow case - determine how far the sign extends into each sub-element. 3970 Tmp2 = VTBits; 3971 for (unsigned i = 0; i != NumElts; ++i) 3972 if (DemandedElts[i]) { 3973 unsigned SubOffset = i % Scale; 3974 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3975 SubOffset = SubOffset * VTBits; 3976 if (Tmp <= SubOffset) 3977 return 1; 3978 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3979 } 3980 return Tmp2; 3981 } 3982 break; 3983 } 3984 3985 case ISD::FP_TO_SINT_SAT: 3986 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 3987 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3988 return VTBits - Tmp + 1; 3989 case ISD::SIGN_EXTEND: 3990 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3991 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3992 case ISD::SIGN_EXTEND_INREG: 3993 // Max of the input and what this extends. 3994 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3995 Tmp = VTBits-Tmp+1; 3996 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3997 return std::max(Tmp, Tmp2); 3998 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3999 SDValue Src = Op.getOperand(0); 4000 EVT SrcVT = Src.getValueType(); 4001 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 4002 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4003 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4004 } 4005 case ISD::SRA: 4006 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4007 // SRA X, C -> adds C sign bits. 4008 if (const APInt *ShAmt = 4009 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4010 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4011 return Tmp; 4012 case ISD::SHL: 4013 if (const APInt *ShAmt = 4014 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4015 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4016 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4017 if (ShAmt->ult(Tmp)) 4018 return Tmp - ShAmt->getZExtValue(); 4019 } 4020 break; 4021 case ISD::AND: 4022 case ISD::OR: 4023 case ISD::XOR: // NOT is handled here. 4024 // Logical binary ops preserve the number of sign bits at the worst. 4025 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4026 if (Tmp != 1) { 4027 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4028 FirstAnswer = std::min(Tmp, Tmp2); 4029 // We computed what we know about the sign bits as our first 4030 // answer. Now proceed to the generic code that uses 4031 // computeKnownBits, and pick whichever answer is better. 4032 } 4033 break; 4034 4035 case ISD::SELECT: 4036 case ISD::VSELECT: 4037 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4038 if (Tmp == 1) return 1; // Early out. 4039 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4040 return std::min(Tmp, Tmp2); 4041 case ISD::SELECT_CC: 4042 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4043 if (Tmp == 1) return 1; // Early out. 4044 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4045 return std::min(Tmp, Tmp2); 4046 4047 case ISD::SMIN: 4048 case ISD::SMAX: { 4049 // If we have a clamp pattern, we know that the number of sign bits will be 4050 // the minimum of the clamp min/max range. 4051 bool IsMax = (Opcode == ISD::SMAX); 4052 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4053 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4054 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4055 CstHigh = 4056 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4057 if (CstLow && CstHigh) { 4058 if (!IsMax) 4059 std::swap(CstLow, CstHigh); 4060 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4061 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4062 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4063 return std::min(Tmp, Tmp2); 4064 } 4065 } 4066 4067 // Fallback - just get the minimum number of sign bits of the operands. 4068 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4069 if (Tmp == 1) 4070 return 1; // Early out. 4071 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4072 return std::min(Tmp, Tmp2); 4073 } 4074 case ISD::UMIN: 4075 case ISD::UMAX: 4076 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4077 if (Tmp == 1) 4078 return 1; // Early out. 4079 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4080 return std::min(Tmp, Tmp2); 4081 case ISD::SADDO: 4082 case ISD::UADDO: 4083 case ISD::SSUBO: 4084 case ISD::USUBO: 4085 case ISD::SMULO: 4086 case ISD::UMULO: 4087 if (Op.getResNo() != 1) 4088 break; 4089 // The boolean result conforms to getBooleanContents. Fall through. 4090 // If setcc returns 0/-1, all bits are sign bits. 4091 // We know that we have an integer-based boolean since these operations 4092 // are only available for integer. 4093 if (TLI->getBooleanContents(VT.isVector(), false) == 4094 TargetLowering::ZeroOrNegativeOneBooleanContent) 4095 return VTBits; 4096 break; 4097 case ISD::SETCC: 4098 case ISD::STRICT_FSETCC: 4099 case ISD::STRICT_FSETCCS: { 4100 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4101 // If setcc returns 0/-1, all bits are sign bits. 4102 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4103 TargetLowering::ZeroOrNegativeOneBooleanContent) 4104 return VTBits; 4105 break; 4106 } 4107 case ISD::ROTL: 4108 case ISD::ROTR: 4109 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4110 4111 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4112 if (Tmp == VTBits) 4113 return VTBits; 4114 4115 if (ConstantSDNode *C = 4116 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4117 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4118 4119 // Handle rotate right by N like a rotate left by 32-N. 4120 if (Opcode == ISD::ROTR) 4121 RotAmt = (VTBits - RotAmt) % VTBits; 4122 4123 // If we aren't rotating out all of the known-in sign bits, return the 4124 // number that are left. This handles rotl(sext(x), 1) for example. 4125 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4126 } 4127 break; 4128 case ISD::ADD: 4129 case ISD::ADDC: 4130 // Add can have at most one carry bit. Thus we know that the output 4131 // is, at worst, one more bit than the inputs. 4132 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4133 if (Tmp == 1) return 1; // Early out. 4134 4135 // Special case decrementing a value (ADD X, -1): 4136 if (ConstantSDNode *CRHS = 4137 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4138 if (CRHS->isAllOnes()) { 4139 KnownBits Known = 4140 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4141 4142 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4143 // sign bits set. 4144 if ((Known.Zero | 1).isAllOnes()) 4145 return VTBits; 4146 4147 // If we are subtracting one from a positive number, there is no carry 4148 // out of the result. 4149 if (Known.isNonNegative()) 4150 return Tmp; 4151 } 4152 4153 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4154 if (Tmp2 == 1) return 1; // Early out. 4155 return std::min(Tmp, Tmp2) - 1; 4156 case ISD::SUB: 4157 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4158 if (Tmp2 == 1) return 1; // Early out. 4159 4160 // Handle NEG. 4161 if (ConstantSDNode *CLHS = 4162 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4163 if (CLHS->isZero()) { 4164 KnownBits Known = 4165 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4166 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4167 // sign bits set. 4168 if ((Known.Zero | 1).isAllOnes()) 4169 return VTBits; 4170 4171 // If the input is known to be positive (the sign bit is known clear), 4172 // the output of the NEG has the same number of sign bits as the input. 4173 if (Known.isNonNegative()) 4174 return Tmp2; 4175 4176 // Otherwise, we treat this like a SUB. 4177 } 4178 4179 // Sub can have at most one carry bit. Thus we know that the output 4180 // is, at worst, one more bit than the inputs. 4181 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4182 if (Tmp == 1) return 1; // Early out. 4183 return std::min(Tmp, Tmp2) - 1; 4184 case ISD::MUL: { 4185 // The output of the Mul can be at most twice the valid bits in the inputs. 4186 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4187 if (SignBitsOp0 == 1) 4188 break; 4189 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4190 if (SignBitsOp1 == 1) 4191 break; 4192 unsigned OutValidBits = 4193 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4194 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4195 } 4196 case ISD::SREM: 4197 // The sign bit is the LHS's sign bit, except when the result of the 4198 // remainder is zero. The magnitude of the result should be less than or 4199 // equal to the magnitude of the LHS. Therefore, the result should have 4200 // at least as many sign bits as the left hand side. 4201 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4202 case ISD::TRUNCATE: { 4203 // Check if the sign bits of source go down as far as the truncated value. 4204 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4205 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4206 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4207 return NumSrcSignBits - (NumSrcBits - VTBits); 4208 break; 4209 } 4210 case ISD::EXTRACT_ELEMENT: { 4211 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4212 const int BitWidth = Op.getValueSizeInBits(); 4213 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4214 4215 // Get reverse index (starting from 1), Op1 value indexes elements from 4216 // little end. Sign starts at big end. 4217 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4218 4219 // If the sign portion ends in our element the subtraction gives correct 4220 // result. Otherwise it gives either negative or > bitwidth result 4221 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4222 } 4223 case ISD::INSERT_VECTOR_ELT: { 4224 // If we know the element index, split the demand between the 4225 // source vector and the inserted element, otherwise assume we need 4226 // the original demanded vector elements and the value. 4227 SDValue InVec = Op.getOperand(0); 4228 SDValue InVal = Op.getOperand(1); 4229 SDValue EltNo = Op.getOperand(2); 4230 bool DemandedVal = true; 4231 APInt DemandedVecElts = DemandedElts; 4232 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4233 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4234 unsigned EltIdx = CEltNo->getZExtValue(); 4235 DemandedVal = !!DemandedElts[EltIdx]; 4236 DemandedVecElts.clearBit(EltIdx); 4237 } 4238 Tmp = std::numeric_limits<unsigned>::max(); 4239 if (DemandedVal) { 4240 // TODO - handle implicit truncation of inserted elements. 4241 if (InVal.getScalarValueSizeInBits() != VTBits) 4242 break; 4243 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4244 Tmp = std::min(Tmp, Tmp2); 4245 } 4246 if (!!DemandedVecElts) { 4247 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4248 Tmp = std::min(Tmp, Tmp2); 4249 } 4250 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4251 return Tmp; 4252 } 4253 case ISD::EXTRACT_VECTOR_ELT: { 4254 SDValue InVec = Op.getOperand(0); 4255 SDValue EltNo = Op.getOperand(1); 4256 EVT VecVT = InVec.getValueType(); 4257 // ComputeNumSignBits not yet implemented for scalable vectors. 4258 if (VecVT.isScalableVector()) 4259 break; 4260 const unsigned BitWidth = Op.getValueSizeInBits(); 4261 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4262 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4263 4264 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4265 // anything about sign bits. But if the sizes match we can derive knowledge 4266 // about sign bits from the vector operand. 4267 if (BitWidth != EltBitWidth) 4268 break; 4269 4270 // If we know the element index, just demand that vector element, else for 4271 // an unknown element index, ignore DemandedElts and demand them all. 4272 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4273 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4274 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4275 DemandedSrcElts = 4276 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4277 4278 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4279 } 4280 case ISD::EXTRACT_SUBVECTOR: { 4281 // Offset the demanded elts by the subvector index. 4282 SDValue Src = Op.getOperand(0); 4283 // Bail until we can represent demanded elements for scalable vectors. 4284 if (Src.getValueType().isScalableVector()) 4285 break; 4286 uint64_t Idx = Op.getConstantOperandVal(1); 4287 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4288 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4289 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4290 } 4291 case ISD::CONCAT_VECTORS: { 4292 // Determine the minimum number of sign bits across all demanded 4293 // elts of the input vectors. Early out if the result is already 1. 4294 Tmp = std::numeric_limits<unsigned>::max(); 4295 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4296 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4297 unsigned NumSubVectors = Op.getNumOperands(); 4298 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4299 APInt DemandedSub = 4300 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4301 if (!DemandedSub) 4302 continue; 4303 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4304 Tmp = std::min(Tmp, Tmp2); 4305 } 4306 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4307 return Tmp; 4308 } 4309 case ISD::INSERT_SUBVECTOR: { 4310 // Demand any elements from the subvector and the remainder from the src its 4311 // inserted into. 4312 SDValue Src = Op.getOperand(0); 4313 SDValue Sub = Op.getOperand(1); 4314 uint64_t Idx = Op.getConstantOperandVal(2); 4315 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4316 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4317 APInt DemandedSrcElts = DemandedElts; 4318 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4319 4320 Tmp = std::numeric_limits<unsigned>::max(); 4321 if (!!DemandedSubElts) { 4322 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4323 if (Tmp == 1) 4324 return 1; // early-out 4325 } 4326 if (!!DemandedSrcElts) { 4327 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4328 Tmp = std::min(Tmp, Tmp2); 4329 } 4330 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4331 return Tmp; 4332 } 4333 case ISD::ATOMIC_CMP_SWAP: 4334 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4335 case ISD::ATOMIC_SWAP: 4336 case ISD::ATOMIC_LOAD_ADD: 4337 case ISD::ATOMIC_LOAD_SUB: 4338 case ISD::ATOMIC_LOAD_AND: 4339 case ISD::ATOMIC_LOAD_CLR: 4340 case ISD::ATOMIC_LOAD_OR: 4341 case ISD::ATOMIC_LOAD_XOR: 4342 case ISD::ATOMIC_LOAD_NAND: 4343 case ISD::ATOMIC_LOAD_MIN: 4344 case ISD::ATOMIC_LOAD_MAX: 4345 case ISD::ATOMIC_LOAD_UMIN: 4346 case ISD::ATOMIC_LOAD_UMAX: 4347 case ISD::ATOMIC_LOAD: { 4348 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4349 // If we are looking at the loaded value. 4350 if (Op.getResNo() == 0) { 4351 if (Tmp == VTBits) 4352 return 1; // early-out 4353 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4354 return VTBits - Tmp + 1; 4355 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4356 return VTBits - Tmp; 4357 } 4358 break; 4359 } 4360 } 4361 4362 // If we are looking at the loaded value of the SDNode. 4363 if (Op.getResNo() == 0) { 4364 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4365 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4366 unsigned ExtType = LD->getExtensionType(); 4367 switch (ExtType) { 4368 default: break; 4369 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4370 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4371 return VTBits - Tmp + 1; 4372 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4373 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4374 return VTBits - Tmp; 4375 case ISD::NON_EXTLOAD: 4376 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4377 // We only need to handle vectors - computeKnownBits should handle 4378 // scalar cases. 4379 Type *CstTy = Cst->getType(); 4380 if (CstTy->isVectorTy() && 4381 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4382 VTBits == CstTy->getScalarSizeInBits()) { 4383 Tmp = VTBits; 4384 for (unsigned i = 0; i != NumElts; ++i) { 4385 if (!DemandedElts[i]) 4386 continue; 4387 if (Constant *Elt = Cst->getAggregateElement(i)) { 4388 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4389 const APInt &Value = CInt->getValue(); 4390 Tmp = std::min(Tmp, Value.getNumSignBits()); 4391 continue; 4392 } 4393 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4394 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4395 Tmp = std::min(Tmp, Value.getNumSignBits()); 4396 continue; 4397 } 4398 } 4399 // Unknown type. Conservatively assume no bits match sign bit. 4400 return 1; 4401 } 4402 return Tmp; 4403 } 4404 } 4405 break; 4406 } 4407 } 4408 } 4409 4410 // Allow the target to implement this method for its nodes. 4411 if (Opcode >= ISD::BUILTIN_OP_END || 4412 Opcode == ISD::INTRINSIC_WO_CHAIN || 4413 Opcode == ISD::INTRINSIC_W_CHAIN || 4414 Opcode == ISD::INTRINSIC_VOID) { 4415 unsigned NumBits = 4416 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4417 if (NumBits > 1) 4418 FirstAnswer = std::max(FirstAnswer, NumBits); 4419 } 4420 4421 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4422 // use this information. 4423 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4424 return std::max(FirstAnswer, Known.countMinSignBits()); 4425 } 4426 4427 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4428 unsigned Depth) const { 4429 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4430 return Op.getScalarValueSizeInBits() - SignBits + 1; 4431 } 4432 4433 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4434 const APInt &DemandedElts, 4435 unsigned Depth) const { 4436 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4437 return Op.getScalarValueSizeInBits() - SignBits + 1; 4438 } 4439 4440 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4441 unsigned Depth) const { 4442 // Early out for FREEZE. 4443 if (Op.getOpcode() == ISD::FREEZE) 4444 return true; 4445 4446 // TODO: Assume we don't know anything for now. 4447 EVT VT = Op.getValueType(); 4448 if (VT.isScalableVector()) 4449 return false; 4450 4451 APInt DemandedElts = VT.isVector() 4452 ? APInt::getAllOnes(VT.getVectorNumElements()) 4453 : APInt(1, 1); 4454 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4455 } 4456 4457 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4458 const APInt &DemandedElts, 4459 bool PoisonOnly, 4460 unsigned Depth) const { 4461 unsigned Opcode = Op.getOpcode(); 4462 4463 // Early out for FREEZE. 4464 if (Opcode == ISD::FREEZE) 4465 return true; 4466 4467 if (Depth >= MaxRecursionDepth) 4468 return false; // Limit search depth. 4469 4470 if (isIntOrFPConstant(Op)) 4471 return true; 4472 4473 switch (Opcode) { 4474 case ISD::UNDEF: 4475 return PoisonOnly; 4476 4477 case ISD::BUILD_VECTOR: 4478 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4479 // this shouldn't affect the result. 4480 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4481 if (!DemandedElts[i]) 4482 continue; 4483 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4484 Depth + 1)) 4485 return false; 4486 } 4487 return true; 4488 4489 // TODO: Search for noundef attributes from library functions. 4490 4491 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4492 4493 default: 4494 // Allow the target to implement this method for its nodes. 4495 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4496 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4497 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4498 Op, DemandedElts, *this, PoisonOnly, Depth); 4499 break; 4500 } 4501 4502 return false; 4503 } 4504 4505 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4506 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4507 !isa<ConstantSDNode>(Op.getOperand(1))) 4508 return false; 4509 4510 if (Op.getOpcode() == ISD::OR && 4511 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4512 return false; 4513 4514 return true; 4515 } 4516 4517 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4518 // If we're told that NaNs won't happen, assume they won't. 4519 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4520 return true; 4521 4522 if (Depth >= MaxRecursionDepth) 4523 return false; // Limit search depth. 4524 4525 // TODO: Handle vectors. 4526 // If the value is a constant, we can obviously see if it is a NaN or not. 4527 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4528 return !C->getValueAPF().isNaN() || 4529 (SNaN && !C->getValueAPF().isSignaling()); 4530 } 4531 4532 unsigned Opcode = Op.getOpcode(); 4533 switch (Opcode) { 4534 case ISD::FADD: 4535 case ISD::FSUB: 4536 case ISD::FMUL: 4537 case ISD::FDIV: 4538 case ISD::FREM: 4539 case ISD::FSIN: 4540 case ISD::FCOS: { 4541 if (SNaN) 4542 return true; 4543 // TODO: Need isKnownNeverInfinity 4544 return false; 4545 } 4546 case ISD::FCANONICALIZE: 4547 case ISD::FEXP: 4548 case ISD::FEXP2: 4549 case ISD::FTRUNC: 4550 case ISD::FFLOOR: 4551 case ISD::FCEIL: 4552 case ISD::FROUND: 4553 case ISD::FROUNDEVEN: 4554 case ISD::FRINT: 4555 case ISD::FNEARBYINT: { 4556 if (SNaN) 4557 return true; 4558 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4559 } 4560 case ISD::FABS: 4561 case ISD::FNEG: 4562 case ISD::FCOPYSIGN: { 4563 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4564 } 4565 case ISD::SELECT: 4566 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4567 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4568 case ISD::FP_EXTEND: 4569 case ISD::FP_ROUND: { 4570 if (SNaN) 4571 return true; 4572 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4573 } 4574 case ISD::SINT_TO_FP: 4575 case ISD::UINT_TO_FP: 4576 return true; 4577 case ISD::FMA: 4578 case ISD::FMAD: { 4579 if (SNaN) 4580 return true; 4581 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4582 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4583 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4584 } 4585 case ISD::FSQRT: // Need is known positive 4586 case ISD::FLOG: 4587 case ISD::FLOG2: 4588 case ISD::FLOG10: 4589 case ISD::FPOWI: 4590 case ISD::FPOW: { 4591 if (SNaN) 4592 return true; 4593 // TODO: Refine on operand 4594 return false; 4595 } 4596 case ISD::FMINNUM: 4597 case ISD::FMAXNUM: { 4598 // Only one needs to be known not-nan, since it will be returned if the 4599 // other ends up being one. 4600 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4601 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4602 } 4603 case ISD::FMINNUM_IEEE: 4604 case ISD::FMAXNUM_IEEE: { 4605 if (SNaN) 4606 return true; 4607 // This can return a NaN if either operand is an sNaN, or if both operands 4608 // are NaN. 4609 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4610 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4611 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4612 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4613 } 4614 case ISD::FMINIMUM: 4615 case ISD::FMAXIMUM: { 4616 // TODO: Does this quiet or return the origina NaN as-is? 4617 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4618 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4619 } 4620 case ISD::EXTRACT_VECTOR_ELT: { 4621 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4622 } 4623 default: 4624 if (Opcode >= ISD::BUILTIN_OP_END || 4625 Opcode == ISD::INTRINSIC_WO_CHAIN || 4626 Opcode == ISD::INTRINSIC_W_CHAIN || 4627 Opcode == ISD::INTRINSIC_VOID) { 4628 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4629 } 4630 4631 return false; 4632 } 4633 } 4634 4635 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4636 assert(Op.getValueType().isFloatingPoint() && 4637 "Floating point type expected"); 4638 4639 // If the value is a constant, we can obviously see if it is a zero or not. 4640 // TODO: Add BuildVector support. 4641 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4642 return !C->isZero(); 4643 return false; 4644 } 4645 4646 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4647 assert(!Op.getValueType().isFloatingPoint() && 4648 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4649 4650 // If the value is a constant, we can obviously see if it is a zero or not. 4651 if (ISD::matchUnaryPredicate(Op, 4652 [](ConstantSDNode *C) { return !C->isZero(); })) 4653 return true; 4654 4655 // TODO: Recognize more cases here. 4656 switch (Op.getOpcode()) { 4657 default: break; 4658 case ISD::OR: 4659 if (isKnownNeverZero(Op.getOperand(1)) || 4660 isKnownNeverZero(Op.getOperand(0))) 4661 return true; 4662 break; 4663 } 4664 4665 return false; 4666 } 4667 4668 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4669 // Check the obvious case. 4670 if (A == B) return true; 4671 4672 // For for negative and positive zero. 4673 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4674 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4675 if (CA->isZero() && CB->isZero()) return true; 4676 4677 // Otherwise they may not be equal. 4678 return false; 4679 } 4680 4681 // FIXME: unify with llvm::haveNoCommonBitsSet. 4682 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4683 assert(A.getValueType() == B.getValueType() && 4684 "Values must have the same type"); 4685 // Match masked merge pattern (X & ~M) op (Y & M) 4686 if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) { 4687 auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) { 4688 if (isBitwiseNot(NotM, true)) { 4689 SDValue NotOperand = NotM->getOperand(0); 4690 return NotOperand == And->getOperand(0) || 4691 NotOperand == And->getOperand(1); 4692 } 4693 return false; 4694 }; 4695 if (MatchNoCommonBitsPattern(A->getOperand(0), B) || 4696 MatchNoCommonBitsPattern(A->getOperand(1), B) || 4697 MatchNoCommonBitsPattern(B->getOperand(0), A) || 4698 MatchNoCommonBitsPattern(B->getOperand(1), A)) 4699 return true; 4700 } 4701 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4702 computeKnownBits(B)); 4703 } 4704 4705 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4706 SelectionDAG &DAG) { 4707 if (cast<ConstantSDNode>(Step)->isZero()) 4708 return DAG.getConstant(0, DL, VT); 4709 4710 return SDValue(); 4711 } 4712 4713 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4714 ArrayRef<SDValue> Ops, 4715 SelectionDAG &DAG) { 4716 int NumOps = Ops.size(); 4717 assert(NumOps != 0 && "Can't build an empty vector!"); 4718 assert(!VT.isScalableVector() && 4719 "BUILD_VECTOR cannot be used with scalable types"); 4720 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4721 "Incorrect element count in BUILD_VECTOR!"); 4722 4723 // BUILD_VECTOR of UNDEFs is UNDEF. 4724 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4725 return DAG.getUNDEF(VT); 4726 4727 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4728 SDValue IdentitySrc; 4729 bool IsIdentity = true; 4730 for (int i = 0; i != NumOps; ++i) { 4731 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4732 Ops[i].getOperand(0).getValueType() != VT || 4733 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4734 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4735 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4736 IsIdentity = false; 4737 break; 4738 } 4739 IdentitySrc = Ops[i].getOperand(0); 4740 } 4741 if (IsIdentity) 4742 return IdentitySrc; 4743 4744 return SDValue(); 4745 } 4746 4747 /// Try to simplify vector concatenation to an input value, undef, or build 4748 /// vector. 4749 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4750 ArrayRef<SDValue> Ops, 4751 SelectionDAG &DAG) { 4752 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4753 assert(llvm::all_of(Ops, 4754 [Ops](SDValue Op) { 4755 return Ops[0].getValueType() == Op.getValueType(); 4756 }) && 4757 "Concatenation of vectors with inconsistent value types!"); 4758 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4759 VT.getVectorElementCount() && 4760 "Incorrect element count in vector concatenation!"); 4761 4762 if (Ops.size() == 1) 4763 return Ops[0]; 4764 4765 // Concat of UNDEFs is UNDEF. 4766 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4767 return DAG.getUNDEF(VT); 4768 4769 // Scan the operands and look for extract operations from a single source 4770 // that correspond to insertion at the same location via this concatenation: 4771 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4772 SDValue IdentitySrc; 4773 bool IsIdentity = true; 4774 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4775 SDValue Op = Ops[i]; 4776 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4777 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4778 Op.getOperand(0).getValueType() != VT || 4779 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4780 Op.getConstantOperandVal(1) != IdentityIndex) { 4781 IsIdentity = false; 4782 break; 4783 } 4784 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4785 "Unexpected identity source vector for concat of extracts"); 4786 IdentitySrc = Op.getOperand(0); 4787 } 4788 if (IsIdentity) { 4789 assert(IdentitySrc && "Failed to set source vector of extracts"); 4790 return IdentitySrc; 4791 } 4792 4793 // The code below this point is only designed to work for fixed width 4794 // vectors, so we bail out for now. 4795 if (VT.isScalableVector()) 4796 return SDValue(); 4797 4798 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4799 // simplified to one big BUILD_VECTOR. 4800 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4801 EVT SVT = VT.getScalarType(); 4802 SmallVector<SDValue, 16> Elts; 4803 for (SDValue Op : Ops) { 4804 EVT OpVT = Op.getValueType(); 4805 if (Op.isUndef()) 4806 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4807 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4808 Elts.append(Op->op_begin(), Op->op_end()); 4809 else 4810 return SDValue(); 4811 } 4812 4813 // BUILD_VECTOR requires all inputs to be of the same type, find the 4814 // maximum type and extend them all. 4815 for (SDValue Op : Elts) 4816 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4817 4818 if (SVT.bitsGT(VT.getScalarType())) { 4819 for (SDValue &Op : Elts) { 4820 if (Op.isUndef()) 4821 Op = DAG.getUNDEF(SVT); 4822 else 4823 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4824 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4825 : DAG.getSExtOrTrunc(Op, DL, SVT); 4826 } 4827 } 4828 4829 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4830 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4831 return V; 4832 } 4833 4834 /// Gets or creates the specified node. 4835 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4836 FoldingSetNodeID ID; 4837 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4838 void *IP = nullptr; 4839 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4840 return SDValue(E, 0); 4841 4842 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4843 getVTList(VT)); 4844 CSEMap.InsertNode(N, IP); 4845 4846 InsertNode(N); 4847 SDValue V = SDValue(N, 0); 4848 NewSDValueDbgMsg(V, "Creating new node: ", this); 4849 return V; 4850 } 4851 4852 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4853 SDValue Operand) { 4854 SDNodeFlags Flags; 4855 if (Inserter) 4856 Flags = Inserter->getFlags(); 4857 return getNode(Opcode, DL, VT, Operand, Flags); 4858 } 4859 4860 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4861 SDValue Operand, const SDNodeFlags Flags) { 4862 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4863 "Operand is DELETED_NODE!"); 4864 // Constant fold unary operations with an integer constant operand. Even 4865 // opaque constant will be folded, because the folding of unary operations 4866 // doesn't create new constants with different values. Nevertheless, the 4867 // opaque flag is preserved during folding to prevent future folding with 4868 // other constants. 4869 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4870 const APInt &Val = C->getAPIntValue(); 4871 switch (Opcode) { 4872 default: break; 4873 case ISD::SIGN_EXTEND: 4874 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4875 C->isTargetOpcode(), C->isOpaque()); 4876 case ISD::TRUNCATE: 4877 if (C->isOpaque()) 4878 break; 4879 LLVM_FALLTHROUGH; 4880 case ISD::ZERO_EXTEND: 4881 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4882 C->isTargetOpcode(), C->isOpaque()); 4883 case ISD::ANY_EXTEND: 4884 // Some targets like RISCV prefer to sign extend some types. 4885 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4886 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4887 C->isTargetOpcode(), C->isOpaque()); 4888 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4889 C->isTargetOpcode(), C->isOpaque()); 4890 case ISD::UINT_TO_FP: 4891 case ISD::SINT_TO_FP: { 4892 APFloat apf(EVTToAPFloatSemantics(VT), 4893 APInt::getZero(VT.getSizeInBits())); 4894 (void)apf.convertFromAPInt(Val, 4895 Opcode==ISD::SINT_TO_FP, 4896 APFloat::rmNearestTiesToEven); 4897 return getConstantFP(apf, DL, VT); 4898 } 4899 case ISD::BITCAST: 4900 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4901 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4902 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4903 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4904 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4905 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4906 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4907 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4908 break; 4909 case ISD::ABS: 4910 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4911 C->isOpaque()); 4912 case ISD::BITREVERSE: 4913 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4914 C->isOpaque()); 4915 case ISD::BSWAP: 4916 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4917 C->isOpaque()); 4918 case ISD::CTPOP: 4919 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4920 C->isOpaque()); 4921 case ISD::CTLZ: 4922 case ISD::CTLZ_ZERO_UNDEF: 4923 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4924 C->isOpaque()); 4925 case ISD::CTTZ: 4926 case ISD::CTTZ_ZERO_UNDEF: 4927 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4928 C->isOpaque()); 4929 case ISD::FP16_TO_FP: { 4930 bool Ignored; 4931 APFloat FPV(APFloat::IEEEhalf(), 4932 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4933 4934 // This can return overflow, underflow, or inexact; we don't care. 4935 // FIXME need to be more flexible about rounding mode. 4936 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4937 APFloat::rmNearestTiesToEven, &Ignored); 4938 return getConstantFP(FPV, DL, VT); 4939 } 4940 case ISD::STEP_VECTOR: { 4941 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4942 return V; 4943 break; 4944 } 4945 } 4946 } 4947 4948 // Constant fold unary operations with a floating point constant operand. 4949 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4950 APFloat V = C->getValueAPF(); // make copy 4951 switch (Opcode) { 4952 case ISD::FNEG: 4953 V.changeSign(); 4954 return getConstantFP(V, DL, VT); 4955 case ISD::FABS: 4956 V.clearSign(); 4957 return getConstantFP(V, DL, VT); 4958 case ISD::FCEIL: { 4959 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4960 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4961 return getConstantFP(V, DL, VT); 4962 break; 4963 } 4964 case ISD::FTRUNC: { 4965 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4966 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4967 return getConstantFP(V, DL, VT); 4968 break; 4969 } 4970 case ISD::FFLOOR: { 4971 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4972 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4973 return getConstantFP(V, DL, VT); 4974 break; 4975 } 4976 case ISD::FP_EXTEND: { 4977 bool ignored; 4978 // This can return overflow, underflow, or inexact; we don't care. 4979 // FIXME need to be more flexible about rounding mode. 4980 (void)V.convert(EVTToAPFloatSemantics(VT), 4981 APFloat::rmNearestTiesToEven, &ignored); 4982 return getConstantFP(V, DL, VT); 4983 } 4984 case ISD::FP_TO_SINT: 4985 case ISD::FP_TO_UINT: { 4986 bool ignored; 4987 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4988 // FIXME need to be more flexible about rounding mode. 4989 APFloat::opStatus s = 4990 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4991 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4992 break; 4993 return getConstant(IntVal, DL, VT); 4994 } 4995 case ISD::BITCAST: 4996 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4997 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4998 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4999 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5000 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 5001 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5002 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 5003 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5004 break; 5005 case ISD::FP_TO_FP16: { 5006 bool Ignored; 5007 // This can return overflow, underflow, or inexact; we don't care. 5008 // FIXME need to be more flexible about rounding mode. 5009 (void)V.convert(APFloat::IEEEhalf(), 5010 APFloat::rmNearestTiesToEven, &Ignored); 5011 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5012 } 5013 } 5014 } 5015 5016 // Constant fold unary operations with a vector integer or float operand. 5017 switch (Opcode) { 5018 default: 5019 // FIXME: Entirely reasonable to perform folding of other unary 5020 // operations here as the need arises. 5021 break; 5022 case ISD::FNEG: 5023 case ISD::FABS: 5024 case ISD::FCEIL: 5025 case ISD::FTRUNC: 5026 case ISD::FFLOOR: 5027 case ISD::FP_EXTEND: 5028 case ISD::FP_TO_SINT: 5029 case ISD::FP_TO_UINT: 5030 case ISD::TRUNCATE: 5031 case ISD::ANY_EXTEND: 5032 case ISD::ZERO_EXTEND: 5033 case ISD::SIGN_EXTEND: 5034 case ISD::UINT_TO_FP: 5035 case ISD::SINT_TO_FP: 5036 case ISD::ABS: 5037 case ISD::BITREVERSE: 5038 case ISD::BSWAP: 5039 case ISD::CTLZ: 5040 case ISD::CTLZ_ZERO_UNDEF: 5041 case ISD::CTTZ: 5042 case ISD::CTTZ_ZERO_UNDEF: 5043 case ISD::CTPOP: { 5044 SDValue Ops = {Operand}; 5045 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5046 return Fold; 5047 } 5048 } 5049 5050 unsigned OpOpcode = Operand.getNode()->getOpcode(); 5051 switch (Opcode) { 5052 case ISD::STEP_VECTOR: 5053 assert(VT.isScalableVector() && 5054 "STEP_VECTOR can only be used with scalable types"); 5055 assert(OpOpcode == ISD::TargetConstant && 5056 VT.getVectorElementType() == Operand.getValueType() && 5057 "Unexpected step operand"); 5058 break; 5059 case ISD::FREEZE: 5060 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5061 break; 5062 case ISD::TokenFactor: 5063 case ISD::MERGE_VALUES: 5064 case ISD::CONCAT_VECTORS: 5065 return Operand; // Factor, merge or concat of one node? No need. 5066 case ISD::BUILD_VECTOR: { 5067 // Attempt to simplify BUILD_VECTOR. 5068 SDValue Ops[] = {Operand}; 5069 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5070 return V; 5071 break; 5072 } 5073 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5074 case ISD::FP_EXTEND: 5075 assert(VT.isFloatingPoint() && 5076 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 5077 if (Operand.getValueType() == VT) return Operand; // noop conversion. 5078 assert((!VT.isVector() || 5079 VT.getVectorElementCount() == 5080 Operand.getValueType().getVectorElementCount()) && 5081 "Vector element count mismatch!"); 5082 assert(Operand.getValueType().bitsLT(VT) && 5083 "Invalid fpext node, dst < src!"); 5084 if (Operand.isUndef()) 5085 return getUNDEF(VT); 5086 break; 5087 case ISD::FP_TO_SINT: 5088 case ISD::FP_TO_UINT: 5089 if (Operand.isUndef()) 5090 return getUNDEF(VT); 5091 break; 5092 case ISD::SINT_TO_FP: 5093 case ISD::UINT_TO_FP: 5094 // [us]itofp(undef) = 0, because the result value is bounded. 5095 if (Operand.isUndef()) 5096 return getConstantFP(0.0, DL, VT); 5097 break; 5098 case ISD::SIGN_EXTEND: 5099 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5100 "Invalid SIGN_EXTEND!"); 5101 assert(VT.isVector() == Operand.getValueType().isVector() && 5102 "SIGN_EXTEND result type type should be vector iff the operand " 5103 "type is vector!"); 5104 if (Operand.getValueType() == VT) return Operand; // noop extension 5105 assert((!VT.isVector() || 5106 VT.getVectorElementCount() == 5107 Operand.getValueType().getVectorElementCount()) && 5108 "Vector element count mismatch!"); 5109 assert(Operand.getValueType().bitsLT(VT) && 5110 "Invalid sext node, dst < src!"); 5111 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5112 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5113 if (OpOpcode == ISD::UNDEF) 5114 // sext(undef) = 0, because the top bits will all be the same. 5115 return getConstant(0, DL, VT); 5116 break; 5117 case ISD::ZERO_EXTEND: 5118 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5119 "Invalid ZERO_EXTEND!"); 5120 assert(VT.isVector() == Operand.getValueType().isVector() && 5121 "ZERO_EXTEND result type type should be vector iff the operand " 5122 "type is vector!"); 5123 if (Operand.getValueType() == VT) return Operand; // noop extension 5124 assert((!VT.isVector() || 5125 VT.getVectorElementCount() == 5126 Operand.getValueType().getVectorElementCount()) && 5127 "Vector element count mismatch!"); 5128 assert(Operand.getValueType().bitsLT(VT) && 5129 "Invalid zext node, dst < src!"); 5130 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5131 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5132 if (OpOpcode == ISD::UNDEF) 5133 // zext(undef) = 0, because the top bits will be zero. 5134 return getConstant(0, DL, VT); 5135 break; 5136 case ISD::ANY_EXTEND: 5137 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5138 "Invalid ANY_EXTEND!"); 5139 assert(VT.isVector() == Operand.getValueType().isVector() && 5140 "ANY_EXTEND result type type should be vector iff the operand " 5141 "type is vector!"); 5142 if (Operand.getValueType() == VT) return Operand; // noop extension 5143 assert((!VT.isVector() || 5144 VT.getVectorElementCount() == 5145 Operand.getValueType().getVectorElementCount()) && 5146 "Vector element count mismatch!"); 5147 assert(Operand.getValueType().bitsLT(VT) && 5148 "Invalid anyext node, dst < src!"); 5149 5150 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5151 OpOpcode == ISD::ANY_EXTEND) 5152 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5153 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5154 if (OpOpcode == ISD::UNDEF) 5155 return getUNDEF(VT); 5156 5157 // (ext (trunc x)) -> x 5158 if (OpOpcode == ISD::TRUNCATE) { 5159 SDValue OpOp = Operand.getOperand(0); 5160 if (OpOp.getValueType() == VT) { 5161 transferDbgValues(Operand, OpOp); 5162 return OpOp; 5163 } 5164 } 5165 break; 5166 case ISD::TRUNCATE: 5167 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5168 "Invalid TRUNCATE!"); 5169 assert(VT.isVector() == Operand.getValueType().isVector() && 5170 "TRUNCATE result type type should be vector iff the operand " 5171 "type is vector!"); 5172 if (Operand.getValueType() == VT) return Operand; // noop truncate 5173 assert((!VT.isVector() || 5174 VT.getVectorElementCount() == 5175 Operand.getValueType().getVectorElementCount()) && 5176 "Vector element count mismatch!"); 5177 assert(Operand.getValueType().bitsGT(VT) && 5178 "Invalid truncate node, src < dst!"); 5179 if (OpOpcode == ISD::TRUNCATE) 5180 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5181 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5182 OpOpcode == ISD::ANY_EXTEND) { 5183 // If the source is smaller than the dest, we still need an extend. 5184 if (Operand.getOperand(0).getValueType().getScalarType() 5185 .bitsLT(VT.getScalarType())) 5186 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5187 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5188 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5189 return Operand.getOperand(0); 5190 } 5191 if (OpOpcode == ISD::UNDEF) 5192 return getUNDEF(VT); 5193 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5194 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5195 break; 5196 case ISD::ANY_EXTEND_VECTOR_INREG: 5197 case ISD::ZERO_EXTEND_VECTOR_INREG: 5198 case ISD::SIGN_EXTEND_VECTOR_INREG: 5199 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5200 assert(Operand.getValueType().bitsLE(VT) && 5201 "The input must be the same size or smaller than the result."); 5202 assert(VT.getVectorMinNumElements() < 5203 Operand.getValueType().getVectorMinNumElements() && 5204 "The destination vector type must have fewer lanes than the input."); 5205 break; 5206 case ISD::ABS: 5207 assert(VT.isInteger() && VT == Operand.getValueType() && 5208 "Invalid ABS!"); 5209 if (OpOpcode == ISD::UNDEF) 5210 return getUNDEF(VT); 5211 break; 5212 case ISD::BSWAP: 5213 assert(VT.isInteger() && VT == Operand.getValueType() && 5214 "Invalid BSWAP!"); 5215 assert((VT.getScalarSizeInBits() % 16 == 0) && 5216 "BSWAP types must be a multiple of 16 bits!"); 5217 if (OpOpcode == ISD::UNDEF) 5218 return getUNDEF(VT); 5219 // bswap(bswap(X)) -> X. 5220 if (OpOpcode == ISD::BSWAP) 5221 return Operand.getOperand(0); 5222 break; 5223 case ISD::BITREVERSE: 5224 assert(VT.isInteger() && VT == Operand.getValueType() && 5225 "Invalid BITREVERSE!"); 5226 if (OpOpcode == ISD::UNDEF) 5227 return getUNDEF(VT); 5228 break; 5229 case ISD::BITCAST: 5230 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5231 "Cannot BITCAST between types of different sizes!"); 5232 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5233 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5234 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5235 if (OpOpcode == ISD::UNDEF) 5236 return getUNDEF(VT); 5237 break; 5238 case ISD::SCALAR_TO_VECTOR: 5239 assert(VT.isVector() && !Operand.getValueType().isVector() && 5240 (VT.getVectorElementType() == Operand.getValueType() || 5241 (VT.getVectorElementType().isInteger() && 5242 Operand.getValueType().isInteger() && 5243 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5244 "Illegal SCALAR_TO_VECTOR node!"); 5245 if (OpOpcode == ISD::UNDEF) 5246 return getUNDEF(VT); 5247 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5248 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5249 isa<ConstantSDNode>(Operand.getOperand(1)) && 5250 Operand.getConstantOperandVal(1) == 0 && 5251 Operand.getOperand(0).getValueType() == VT) 5252 return Operand.getOperand(0); 5253 break; 5254 case ISD::FNEG: 5255 // Negation of an unknown bag of bits is still completely undefined. 5256 if (OpOpcode == ISD::UNDEF) 5257 return getUNDEF(VT); 5258 5259 if (OpOpcode == ISD::FNEG) // --X -> X 5260 return Operand.getOperand(0); 5261 break; 5262 case ISD::FABS: 5263 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5264 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5265 break; 5266 case ISD::VSCALE: 5267 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5268 break; 5269 case ISD::CTPOP: 5270 if (Operand.getValueType().getScalarType() == MVT::i1) 5271 return Operand; 5272 break; 5273 case ISD::CTLZ: 5274 case ISD::CTTZ: 5275 if (Operand.getValueType().getScalarType() == MVT::i1) 5276 return getNOT(DL, Operand, Operand.getValueType()); 5277 break; 5278 case ISD::VECREDUCE_SMIN: 5279 case ISD::VECREDUCE_UMAX: 5280 if (Operand.getValueType().getScalarType() == MVT::i1) 5281 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5282 break; 5283 case ISD::VECREDUCE_SMAX: 5284 case ISD::VECREDUCE_UMIN: 5285 if (Operand.getValueType().getScalarType() == MVT::i1) 5286 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5287 break; 5288 } 5289 5290 SDNode *N; 5291 SDVTList VTs = getVTList(VT); 5292 SDValue Ops[] = {Operand}; 5293 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5294 FoldingSetNodeID ID; 5295 AddNodeIDNode(ID, Opcode, VTs, Ops); 5296 void *IP = nullptr; 5297 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5298 E->intersectFlagsWith(Flags); 5299 return SDValue(E, 0); 5300 } 5301 5302 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5303 N->setFlags(Flags); 5304 createOperands(N, Ops); 5305 CSEMap.InsertNode(N, IP); 5306 } else { 5307 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5308 createOperands(N, Ops); 5309 } 5310 5311 InsertNode(N); 5312 SDValue V = SDValue(N, 0); 5313 NewSDValueDbgMsg(V, "Creating new node: ", this); 5314 return V; 5315 } 5316 5317 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5318 const APInt &C2) { 5319 switch (Opcode) { 5320 case ISD::ADD: return C1 + C2; 5321 case ISD::SUB: return C1 - C2; 5322 case ISD::MUL: return C1 * C2; 5323 case ISD::AND: return C1 & C2; 5324 case ISD::OR: return C1 | C2; 5325 case ISD::XOR: return C1 ^ C2; 5326 case ISD::SHL: return C1 << C2; 5327 case ISD::SRL: return C1.lshr(C2); 5328 case ISD::SRA: return C1.ashr(C2); 5329 case ISD::ROTL: return C1.rotl(C2); 5330 case ISD::ROTR: return C1.rotr(C2); 5331 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5332 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5333 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5334 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5335 case ISD::SADDSAT: return C1.sadd_sat(C2); 5336 case ISD::UADDSAT: return C1.uadd_sat(C2); 5337 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5338 case ISD::USUBSAT: return C1.usub_sat(C2); 5339 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5340 case ISD::USHLSAT: return C1.ushl_sat(C2); 5341 case ISD::UDIV: 5342 if (!C2.getBoolValue()) 5343 break; 5344 return C1.udiv(C2); 5345 case ISD::UREM: 5346 if (!C2.getBoolValue()) 5347 break; 5348 return C1.urem(C2); 5349 case ISD::SDIV: 5350 if (!C2.getBoolValue()) 5351 break; 5352 return C1.sdiv(C2); 5353 case ISD::SREM: 5354 if (!C2.getBoolValue()) 5355 break; 5356 return C1.srem(C2); 5357 case ISD::MULHS: { 5358 unsigned FullWidth = C1.getBitWidth() * 2; 5359 APInt C1Ext = C1.sext(FullWidth); 5360 APInt C2Ext = C2.sext(FullWidth); 5361 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5362 } 5363 case ISD::MULHU: { 5364 unsigned FullWidth = C1.getBitWidth() * 2; 5365 APInt C1Ext = C1.zext(FullWidth); 5366 APInt C2Ext = C2.zext(FullWidth); 5367 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5368 } 5369 case ISD::AVGFLOORS: { 5370 unsigned FullWidth = C1.getBitWidth() + 1; 5371 APInt C1Ext = C1.sext(FullWidth); 5372 APInt C2Ext = C2.sext(FullWidth); 5373 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5374 } 5375 case ISD::AVGFLOORU: { 5376 unsigned FullWidth = C1.getBitWidth() + 1; 5377 APInt C1Ext = C1.zext(FullWidth); 5378 APInt C2Ext = C2.zext(FullWidth); 5379 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5380 } 5381 case ISD::AVGCEILS: { 5382 unsigned FullWidth = C1.getBitWidth() + 1; 5383 APInt C1Ext = C1.sext(FullWidth); 5384 APInt C2Ext = C2.sext(FullWidth); 5385 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5386 } 5387 case ISD::AVGCEILU: { 5388 unsigned FullWidth = C1.getBitWidth() + 1; 5389 APInt C1Ext = C1.zext(FullWidth); 5390 APInt C2Ext = C2.zext(FullWidth); 5391 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5392 } 5393 } 5394 return llvm::None; 5395 } 5396 5397 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5398 const GlobalAddressSDNode *GA, 5399 const SDNode *N2) { 5400 if (GA->getOpcode() != ISD::GlobalAddress) 5401 return SDValue(); 5402 if (!TLI->isOffsetFoldingLegal(GA)) 5403 return SDValue(); 5404 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5405 if (!C2) 5406 return SDValue(); 5407 int64_t Offset = C2->getSExtValue(); 5408 switch (Opcode) { 5409 case ISD::ADD: break; 5410 case ISD::SUB: Offset = -uint64_t(Offset); break; 5411 default: return SDValue(); 5412 } 5413 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5414 GA->getOffset() + uint64_t(Offset)); 5415 } 5416 5417 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5418 switch (Opcode) { 5419 case ISD::SDIV: 5420 case ISD::UDIV: 5421 case ISD::SREM: 5422 case ISD::UREM: { 5423 // If a divisor is zero/undef or any element of a divisor vector is 5424 // zero/undef, the whole op is undef. 5425 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5426 SDValue Divisor = Ops[1]; 5427 if (Divisor.isUndef() || isNullConstant(Divisor)) 5428 return true; 5429 5430 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5431 llvm::any_of(Divisor->op_values(), 5432 [](SDValue V) { return V.isUndef() || 5433 isNullConstant(V); }); 5434 // TODO: Handle signed overflow. 5435 } 5436 // TODO: Handle oversized shifts. 5437 default: 5438 return false; 5439 } 5440 } 5441 5442 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5443 EVT VT, ArrayRef<SDValue> Ops) { 5444 // If the opcode is a target-specific ISD node, there's nothing we can 5445 // do here and the operand rules may not line up with the below, so 5446 // bail early. 5447 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5448 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5449 // foldCONCAT_VECTORS in getNode before this is called. 5450 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5451 return SDValue(); 5452 5453 unsigned NumOps = Ops.size(); 5454 if (NumOps == 0) 5455 return SDValue(); 5456 5457 if (isUndef(Opcode, Ops)) 5458 return getUNDEF(VT); 5459 5460 // Handle binops special cases. 5461 if (NumOps == 2) { 5462 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5463 return CFP; 5464 5465 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5466 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5467 if (C1->isOpaque() || C2->isOpaque()) 5468 return SDValue(); 5469 5470 Optional<APInt> FoldAttempt = 5471 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5472 if (!FoldAttempt) 5473 return SDValue(); 5474 5475 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5476 assert((!Folded || !VT.isVector()) && 5477 "Can't fold vectors ops with scalar operands"); 5478 return Folded; 5479 } 5480 } 5481 5482 // fold (add Sym, c) -> Sym+c 5483 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5484 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5485 if (TLI->isCommutativeBinOp(Opcode)) 5486 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5487 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5488 } 5489 5490 // This is for vector folding only from here on. 5491 if (!VT.isVector()) 5492 return SDValue(); 5493 5494 ElementCount NumElts = VT.getVectorElementCount(); 5495 5496 // See if we can fold through bitcasted integer ops. 5497 // TODO: Can we handle undef elements? 5498 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5499 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5500 Ops[0].getOpcode() == ISD::BITCAST && 5501 Ops[1].getOpcode() == ISD::BITCAST) { 5502 SDValue N1 = peekThroughBitcasts(Ops[0]); 5503 SDValue N2 = peekThroughBitcasts(Ops[1]); 5504 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5505 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5506 EVT BVVT = N1.getValueType(); 5507 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5508 bool IsLE = getDataLayout().isLittleEndian(); 5509 unsigned EltBits = VT.getScalarSizeInBits(); 5510 SmallVector<APInt> RawBits1, RawBits2; 5511 BitVector UndefElts1, UndefElts2; 5512 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5513 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5514 UndefElts1.none() && UndefElts2.none()) { 5515 SmallVector<APInt> RawBits; 5516 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5517 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5518 if (!Fold) 5519 break; 5520 RawBits.push_back(Fold.getValue()); 5521 } 5522 if (RawBits.size() == NumElts.getFixedValue()) { 5523 // We have constant folded, but we need to cast this again back to 5524 // the original (possibly legalized) type. 5525 SmallVector<APInt> DstBits; 5526 BitVector DstUndefs; 5527 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5528 DstBits, RawBits, DstUndefs, 5529 BitVector(RawBits.size(), false)); 5530 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5531 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5532 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5533 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5534 if (DstUndefs[I]) 5535 continue; 5536 Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT); 5537 } 5538 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5539 } 5540 } 5541 } 5542 } 5543 5544 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5545 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5546 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5547 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5548 APInt RHSVal; 5549 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5550 APInt NewStep = Opcode == ISD::MUL 5551 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5552 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5553 return getStepVector(DL, VT, NewStep); 5554 } 5555 } 5556 5557 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5558 return !Op.getValueType().isVector() || 5559 Op.getValueType().getVectorElementCount() == NumElts; 5560 }; 5561 5562 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5563 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5564 Op.getOpcode() == ISD::BUILD_VECTOR || 5565 Op.getOpcode() == ISD::SPLAT_VECTOR; 5566 }; 5567 5568 // All operands must be vector types with the same number of elements as 5569 // the result type and must be either UNDEF or a build/splat vector 5570 // or UNDEF scalars. 5571 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5572 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5573 return SDValue(); 5574 5575 // If we are comparing vectors, then the result needs to be a i1 boolean 5576 // that is then sign-extended back to the legal result type. 5577 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5578 5579 // Find legal integer scalar type for constant promotion and 5580 // ensure that its scalar size is at least as large as source. 5581 EVT LegalSVT = VT.getScalarType(); 5582 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5583 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5584 if (LegalSVT.bitsLT(VT.getScalarType())) 5585 return SDValue(); 5586 } 5587 5588 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5589 // only have one operand to check. For fixed-length vector types we may have 5590 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5591 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5592 5593 // Constant fold each scalar lane separately. 5594 SmallVector<SDValue, 4> ScalarResults; 5595 for (unsigned I = 0; I != NumVectorElts; I++) { 5596 SmallVector<SDValue, 4> ScalarOps; 5597 for (SDValue Op : Ops) { 5598 EVT InSVT = Op.getValueType().getScalarType(); 5599 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5600 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5601 if (Op.isUndef()) 5602 ScalarOps.push_back(getUNDEF(InSVT)); 5603 else 5604 ScalarOps.push_back(Op); 5605 continue; 5606 } 5607 5608 SDValue ScalarOp = 5609 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5610 EVT ScalarVT = ScalarOp.getValueType(); 5611 5612 // Build vector (integer) scalar operands may need implicit 5613 // truncation - do this before constant folding. 5614 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5615 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5616 5617 ScalarOps.push_back(ScalarOp); 5618 } 5619 5620 // Constant fold the scalar operands. 5621 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5622 5623 // Legalize the (integer) scalar constant if necessary. 5624 if (LegalSVT != SVT) 5625 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5626 5627 // Scalar folding only succeeded if the result is a constant or UNDEF. 5628 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5629 ScalarResult.getOpcode() != ISD::ConstantFP) 5630 return SDValue(); 5631 ScalarResults.push_back(ScalarResult); 5632 } 5633 5634 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5635 : getBuildVector(VT, DL, ScalarResults); 5636 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5637 return V; 5638 } 5639 5640 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5641 EVT VT, SDValue N1, SDValue N2) { 5642 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5643 // should. That will require dealing with a potentially non-default 5644 // rounding mode, checking the "opStatus" return value from the APFloat 5645 // math calculations, and possibly other variations. 5646 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5647 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5648 if (N1CFP && N2CFP) { 5649 APFloat C1 = N1CFP->getValueAPF(); // make copy 5650 const APFloat &C2 = N2CFP->getValueAPF(); 5651 switch (Opcode) { 5652 case ISD::FADD: 5653 C1.add(C2, APFloat::rmNearestTiesToEven); 5654 return getConstantFP(C1, DL, VT); 5655 case ISD::FSUB: 5656 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5657 return getConstantFP(C1, DL, VT); 5658 case ISD::FMUL: 5659 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5660 return getConstantFP(C1, DL, VT); 5661 case ISD::FDIV: 5662 C1.divide(C2, APFloat::rmNearestTiesToEven); 5663 return getConstantFP(C1, DL, VT); 5664 case ISD::FREM: 5665 C1.mod(C2); 5666 return getConstantFP(C1, DL, VT); 5667 case ISD::FCOPYSIGN: 5668 C1.copySign(C2); 5669 return getConstantFP(C1, DL, VT); 5670 case ISD::FMINNUM: 5671 return getConstantFP(minnum(C1, C2), DL, VT); 5672 case ISD::FMAXNUM: 5673 return getConstantFP(maxnum(C1, C2), DL, VT); 5674 case ISD::FMINIMUM: 5675 return getConstantFP(minimum(C1, C2), DL, VT); 5676 case ISD::FMAXIMUM: 5677 return getConstantFP(maximum(C1, C2), DL, VT); 5678 default: break; 5679 } 5680 } 5681 if (N1CFP && Opcode == ISD::FP_ROUND) { 5682 APFloat C1 = N1CFP->getValueAPF(); // make copy 5683 bool Unused; 5684 // This can return overflow, underflow, or inexact; we don't care. 5685 // FIXME need to be more flexible about rounding mode. 5686 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5687 &Unused); 5688 return getConstantFP(C1, DL, VT); 5689 } 5690 5691 switch (Opcode) { 5692 case ISD::FSUB: 5693 // -0.0 - undef --> undef (consistent with "fneg undef") 5694 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5695 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5696 return getUNDEF(VT); 5697 LLVM_FALLTHROUGH; 5698 5699 case ISD::FADD: 5700 case ISD::FMUL: 5701 case ISD::FDIV: 5702 case ISD::FREM: 5703 // If both operands are undef, the result is undef. If 1 operand is undef, 5704 // the result is NaN. This should match the behavior of the IR optimizer. 5705 if (N1.isUndef() && N2.isUndef()) 5706 return getUNDEF(VT); 5707 if (N1.isUndef() || N2.isUndef()) 5708 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5709 } 5710 return SDValue(); 5711 } 5712 5713 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5714 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5715 5716 // There's no need to assert on a byte-aligned pointer. All pointers are at 5717 // least byte aligned. 5718 if (A == Align(1)) 5719 return Val; 5720 5721 FoldingSetNodeID ID; 5722 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5723 ID.AddInteger(A.value()); 5724 5725 void *IP = nullptr; 5726 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5727 return SDValue(E, 0); 5728 5729 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5730 Val.getValueType(), A); 5731 createOperands(N, {Val}); 5732 5733 CSEMap.InsertNode(N, IP); 5734 InsertNode(N); 5735 5736 SDValue V(N, 0); 5737 NewSDValueDbgMsg(V, "Creating new node: ", this); 5738 return V; 5739 } 5740 5741 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5742 SDValue N1, SDValue N2) { 5743 SDNodeFlags Flags; 5744 if (Inserter) 5745 Flags = Inserter->getFlags(); 5746 return getNode(Opcode, DL, VT, N1, N2, Flags); 5747 } 5748 5749 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5750 SDValue &N2) const { 5751 if (!TLI->isCommutativeBinOp(Opcode)) 5752 return; 5753 5754 // Canonicalize: 5755 // binop(const, nonconst) -> binop(nonconst, const) 5756 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5757 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5758 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5759 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5760 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5761 std::swap(N1, N2); 5762 5763 // Canonicalize: 5764 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5765 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5766 N2.getOpcode() == ISD::STEP_VECTOR) 5767 std::swap(N1, N2); 5768 } 5769 5770 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5771 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5772 assert(N1.getOpcode() != ISD::DELETED_NODE && 5773 N2.getOpcode() != ISD::DELETED_NODE && 5774 "Operand is DELETED_NODE!"); 5775 5776 canonicalizeCommutativeBinop(Opcode, N1, N2); 5777 5778 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5779 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5780 5781 // Don't allow undefs in vector splats - we might be returning N2 when folding 5782 // to zero etc. 5783 ConstantSDNode *N2CV = 5784 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5785 5786 switch (Opcode) { 5787 default: break; 5788 case ISD::TokenFactor: 5789 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5790 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5791 // Fold trivial token factors. 5792 if (N1.getOpcode() == ISD::EntryToken) return N2; 5793 if (N2.getOpcode() == ISD::EntryToken) return N1; 5794 if (N1 == N2) return N1; 5795 break; 5796 case ISD::BUILD_VECTOR: { 5797 // Attempt to simplify BUILD_VECTOR. 5798 SDValue Ops[] = {N1, N2}; 5799 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5800 return V; 5801 break; 5802 } 5803 case ISD::CONCAT_VECTORS: { 5804 SDValue Ops[] = {N1, N2}; 5805 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5806 return V; 5807 break; 5808 } 5809 case ISD::AND: 5810 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5811 assert(N1.getValueType() == N2.getValueType() && 5812 N1.getValueType() == VT && "Binary operator types must match!"); 5813 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5814 // worth handling here. 5815 if (N2CV && N2CV->isZero()) 5816 return N2; 5817 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5818 return N1; 5819 break; 5820 case ISD::OR: 5821 case ISD::XOR: 5822 case ISD::ADD: 5823 case ISD::SUB: 5824 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5825 assert(N1.getValueType() == N2.getValueType() && 5826 N1.getValueType() == VT && "Binary operator types must match!"); 5827 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5828 // it's worth handling here. 5829 if (N2CV && N2CV->isZero()) 5830 return N1; 5831 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5832 VT.getVectorElementType() == MVT::i1) 5833 return getNode(ISD::XOR, DL, VT, N1, N2); 5834 break; 5835 case ISD::MUL: 5836 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5837 assert(N1.getValueType() == N2.getValueType() && 5838 N1.getValueType() == VT && "Binary operator types must match!"); 5839 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5840 return getNode(ISD::AND, DL, VT, N1, N2); 5841 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5842 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5843 const APInt &N2CImm = N2C->getAPIntValue(); 5844 return getVScale(DL, VT, MulImm * N2CImm); 5845 } 5846 break; 5847 case ISD::UDIV: 5848 case ISD::UREM: 5849 case ISD::MULHU: 5850 case ISD::MULHS: 5851 case ISD::SDIV: 5852 case ISD::SREM: 5853 case ISD::SADDSAT: 5854 case ISD::SSUBSAT: 5855 case ISD::UADDSAT: 5856 case ISD::USUBSAT: 5857 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5858 assert(N1.getValueType() == N2.getValueType() && 5859 N1.getValueType() == VT && "Binary operator types must match!"); 5860 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5861 // fold (add_sat x, y) -> (or x, y) for bool types. 5862 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5863 return getNode(ISD::OR, DL, VT, N1, N2); 5864 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5865 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5866 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5867 } 5868 break; 5869 case ISD::SMIN: 5870 case ISD::UMAX: 5871 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5872 assert(N1.getValueType() == N2.getValueType() && 5873 N1.getValueType() == VT && "Binary operator types must match!"); 5874 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5875 return getNode(ISD::OR, DL, VT, N1, N2); 5876 break; 5877 case ISD::SMAX: 5878 case ISD::UMIN: 5879 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5880 assert(N1.getValueType() == N2.getValueType() && 5881 N1.getValueType() == VT && "Binary operator types must match!"); 5882 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5883 return getNode(ISD::AND, DL, VT, N1, N2); 5884 break; 5885 case ISD::FADD: 5886 case ISD::FSUB: 5887 case ISD::FMUL: 5888 case ISD::FDIV: 5889 case ISD::FREM: 5890 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5891 assert(N1.getValueType() == N2.getValueType() && 5892 N1.getValueType() == VT && "Binary operator types must match!"); 5893 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5894 return V; 5895 break; 5896 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5897 assert(N1.getValueType() == VT && 5898 N1.getValueType().isFloatingPoint() && 5899 N2.getValueType().isFloatingPoint() && 5900 "Invalid FCOPYSIGN!"); 5901 break; 5902 case ISD::SHL: 5903 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5904 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5905 const APInt &ShiftImm = N2C->getAPIntValue(); 5906 return getVScale(DL, VT, MulImm << ShiftImm); 5907 } 5908 LLVM_FALLTHROUGH; 5909 case ISD::SRA: 5910 case ISD::SRL: 5911 if (SDValue V = simplifyShift(N1, N2)) 5912 return V; 5913 LLVM_FALLTHROUGH; 5914 case ISD::ROTL: 5915 case ISD::ROTR: 5916 assert(VT == N1.getValueType() && 5917 "Shift operators return type must be the same as their first arg"); 5918 assert(VT.isInteger() && N2.getValueType().isInteger() && 5919 "Shifts only work on integers"); 5920 assert((!VT.isVector() || VT == N2.getValueType()) && 5921 "Vector shift amounts must be in the same as their first arg"); 5922 // Verify that the shift amount VT is big enough to hold valid shift 5923 // amounts. This catches things like trying to shift an i1024 value by an 5924 // i8, which is easy to fall into in generic code that uses 5925 // TLI.getShiftAmount(). 5926 assert(N2.getValueType().getScalarSizeInBits() >= 5927 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5928 "Invalid use of small shift amount with oversized value!"); 5929 5930 // Always fold shifts of i1 values so the code generator doesn't need to 5931 // handle them. Since we know the size of the shift has to be less than the 5932 // size of the value, the shift/rotate count is guaranteed to be zero. 5933 if (VT == MVT::i1) 5934 return N1; 5935 if (N2CV && N2CV->isZero()) 5936 return N1; 5937 break; 5938 case ISD::FP_ROUND: 5939 assert(VT.isFloatingPoint() && 5940 N1.getValueType().isFloatingPoint() && 5941 VT.bitsLE(N1.getValueType()) && 5942 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5943 "Invalid FP_ROUND!"); 5944 if (N1.getValueType() == VT) return N1; // noop conversion. 5945 break; 5946 case ISD::AssertSext: 5947 case ISD::AssertZext: { 5948 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5949 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5950 assert(VT.isInteger() && EVT.isInteger() && 5951 "Cannot *_EXTEND_INREG FP types"); 5952 assert(!EVT.isVector() && 5953 "AssertSExt/AssertZExt type should be the vector element type " 5954 "rather than the vector type!"); 5955 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5956 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5957 break; 5958 } 5959 case ISD::SIGN_EXTEND_INREG: { 5960 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5961 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5962 assert(VT.isInteger() && EVT.isInteger() && 5963 "Cannot *_EXTEND_INREG FP types"); 5964 assert(EVT.isVector() == VT.isVector() && 5965 "SIGN_EXTEND_INREG type should be vector iff the operand " 5966 "type is vector!"); 5967 assert((!EVT.isVector() || 5968 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5969 "Vector element counts must match in SIGN_EXTEND_INREG"); 5970 assert(EVT.bitsLE(VT) && "Not extending!"); 5971 if (EVT == VT) return N1; // Not actually extending 5972 5973 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5974 unsigned FromBits = EVT.getScalarSizeInBits(); 5975 Val <<= Val.getBitWidth() - FromBits; 5976 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5977 return getConstant(Val, DL, ConstantVT); 5978 }; 5979 5980 if (N1C) { 5981 const APInt &Val = N1C->getAPIntValue(); 5982 return SignExtendInReg(Val, VT); 5983 } 5984 5985 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5986 SmallVector<SDValue, 8> Ops; 5987 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5988 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5989 SDValue Op = N1.getOperand(i); 5990 if (Op.isUndef()) { 5991 Ops.push_back(getUNDEF(OpVT)); 5992 continue; 5993 } 5994 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5995 APInt Val = C->getAPIntValue(); 5996 Ops.push_back(SignExtendInReg(Val, OpVT)); 5997 } 5998 return getBuildVector(VT, DL, Ops); 5999 } 6000 break; 6001 } 6002 case ISD::FP_TO_SINT_SAT: 6003 case ISD::FP_TO_UINT_SAT: { 6004 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6005 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6006 assert(N1.getValueType().isVector() == VT.isVector() && 6007 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6008 "vector!"); 6009 assert((!VT.isVector() || VT.getVectorNumElements() == 6010 N1.getValueType().getVectorNumElements()) && 6011 "Vector element counts must match in FP_TO_*INT_SAT"); 6012 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6013 "Type to saturate to must be a scalar."); 6014 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6015 "Not extending!"); 6016 break; 6017 } 6018 case ISD::EXTRACT_VECTOR_ELT: 6019 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6020 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6021 element type of the vector."); 6022 6023 // Extract from an undefined value or using an undefined index is undefined. 6024 if (N1.isUndef() || N2.isUndef()) 6025 return getUNDEF(VT); 6026 6027 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6028 // vectors. For scalable vectors we will provide appropriate support for 6029 // dealing with arbitrary indices. 6030 if (N2C && N1.getValueType().isFixedLengthVector() && 6031 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6032 return getUNDEF(VT); 6033 6034 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6035 // expanding copies of large vectors from registers. This only works for 6036 // fixed length vectors, since we need to know the exact number of 6037 // elements. 6038 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6039 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6040 unsigned Factor = 6041 N1.getOperand(0).getValueType().getVectorNumElements(); 6042 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6043 N1.getOperand(N2C->getZExtValue() / Factor), 6044 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6045 } 6046 6047 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6048 // lowering is expanding large vector constants. 6049 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6050 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6051 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6052 N1.getValueType().isFixedLengthVector()) && 6053 "BUILD_VECTOR used for scalable vectors"); 6054 unsigned Index = 6055 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6056 SDValue Elt = N1.getOperand(Index); 6057 6058 if (VT != Elt.getValueType()) 6059 // If the vector element type is not legal, the BUILD_VECTOR operands 6060 // are promoted and implicitly truncated, and the result implicitly 6061 // extended. Make that explicit here. 6062 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6063 6064 return Elt; 6065 } 6066 6067 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6068 // operations are lowered to scalars. 6069 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6070 // If the indices are the same, return the inserted element else 6071 // if the indices are known different, extract the element from 6072 // the original vector. 6073 SDValue N1Op2 = N1.getOperand(2); 6074 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6075 6076 if (N1Op2C && N2C) { 6077 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6078 if (VT == N1.getOperand(1).getValueType()) 6079 return N1.getOperand(1); 6080 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6081 } 6082 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6083 } 6084 } 6085 6086 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6087 // when vector types are scalarized and v1iX is legal. 6088 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6089 // Here we are completely ignoring the extract element index (N2), 6090 // which is fine for fixed width vectors, since any index other than 0 6091 // is undefined anyway. However, this cannot be ignored for scalable 6092 // vectors - in theory we could support this, but we don't want to do this 6093 // without a profitability check. 6094 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6095 N1.getValueType().isFixedLengthVector() && 6096 N1.getValueType().getVectorNumElements() == 1) { 6097 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6098 N1.getOperand(1)); 6099 } 6100 break; 6101 case ISD::EXTRACT_ELEMENT: 6102 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6103 assert(!N1.getValueType().isVector() && !VT.isVector() && 6104 (N1.getValueType().isInteger() == VT.isInteger()) && 6105 N1.getValueType() != VT && 6106 "Wrong types for EXTRACT_ELEMENT!"); 6107 6108 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6109 // 64-bit integers into 32-bit parts. Instead of building the extract of 6110 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6111 if (N1.getOpcode() == ISD::BUILD_PAIR) 6112 return N1.getOperand(N2C->getZExtValue()); 6113 6114 // EXTRACT_ELEMENT of a constant int is also very common. 6115 if (N1C) { 6116 unsigned ElementSize = VT.getSizeInBits(); 6117 unsigned Shift = ElementSize * N2C->getZExtValue(); 6118 const APInt &Val = N1C->getAPIntValue(); 6119 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6120 } 6121 break; 6122 case ISD::EXTRACT_SUBVECTOR: { 6123 EVT N1VT = N1.getValueType(); 6124 assert(VT.isVector() && N1VT.isVector() && 6125 "Extract subvector VTs must be vectors!"); 6126 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6127 "Extract subvector VTs must have the same element type!"); 6128 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6129 "Cannot extract a scalable vector from a fixed length vector!"); 6130 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6131 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6132 "Extract subvector must be from larger vector to smaller vector!"); 6133 assert(N2C && "Extract subvector index must be a constant"); 6134 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6135 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6136 N1VT.getVectorMinNumElements()) && 6137 "Extract subvector overflow!"); 6138 assert(N2C->getAPIntValue().getBitWidth() == 6139 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6140 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6141 6142 // Trivial extraction. 6143 if (VT == N1VT) 6144 return N1; 6145 6146 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6147 if (N1.isUndef()) 6148 return getUNDEF(VT); 6149 6150 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6151 // the concat have the same type as the extract. 6152 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6153 VT == N1.getOperand(0).getValueType()) { 6154 unsigned Factor = VT.getVectorMinNumElements(); 6155 return N1.getOperand(N2C->getZExtValue() / Factor); 6156 } 6157 6158 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6159 // during shuffle legalization. 6160 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6161 VT == N1.getOperand(1).getValueType()) 6162 return N1.getOperand(1); 6163 break; 6164 } 6165 } 6166 6167 // Perform trivial constant folding. 6168 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6169 return SV; 6170 6171 // Canonicalize an UNDEF to the RHS, even over a constant. 6172 if (N1.isUndef()) { 6173 if (TLI->isCommutativeBinOp(Opcode)) { 6174 std::swap(N1, N2); 6175 } else { 6176 switch (Opcode) { 6177 case ISD::SIGN_EXTEND_INREG: 6178 case ISD::SUB: 6179 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6180 case ISD::UDIV: 6181 case ISD::SDIV: 6182 case ISD::UREM: 6183 case ISD::SREM: 6184 case ISD::SSUBSAT: 6185 case ISD::USUBSAT: 6186 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6187 } 6188 } 6189 } 6190 6191 // Fold a bunch of operators when the RHS is undef. 6192 if (N2.isUndef()) { 6193 switch (Opcode) { 6194 case ISD::XOR: 6195 if (N1.isUndef()) 6196 // Handle undef ^ undef -> 0 special case. This is a common 6197 // idiom (misuse). 6198 return getConstant(0, DL, VT); 6199 LLVM_FALLTHROUGH; 6200 case ISD::ADD: 6201 case ISD::SUB: 6202 case ISD::UDIV: 6203 case ISD::SDIV: 6204 case ISD::UREM: 6205 case ISD::SREM: 6206 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6207 case ISD::MUL: 6208 case ISD::AND: 6209 case ISD::SSUBSAT: 6210 case ISD::USUBSAT: 6211 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6212 case ISD::OR: 6213 case ISD::SADDSAT: 6214 case ISD::UADDSAT: 6215 return getAllOnesConstant(DL, VT); 6216 } 6217 } 6218 6219 // Memoize this node if possible. 6220 SDNode *N; 6221 SDVTList VTs = getVTList(VT); 6222 SDValue Ops[] = {N1, N2}; 6223 if (VT != MVT::Glue) { 6224 FoldingSetNodeID ID; 6225 AddNodeIDNode(ID, Opcode, VTs, Ops); 6226 void *IP = nullptr; 6227 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6228 E->intersectFlagsWith(Flags); 6229 return SDValue(E, 0); 6230 } 6231 6232 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6233 N->setFlags(Flags); 6234 createOperands(N, Ops); 6235 CSEMap.InsertNode(N, IP); 6236 } else { 6237 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6238 createOperands(N, Ops); 6239 } 6240 6241 InsertNode(N); 6242 SDValue V = SDValue(N, 0); 6243 NewSDValueDbgMsg(V, "Creating new node: ", this); 6244 return V; 6245 } 6246 6247 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6248 SDValue N1, SDValue N2, SDValue N3) { 6249 SDNodeFlags Flags; 6250 if (Inserter) 6251 Flags = Inserter->getFlags(); 6252 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6253 } 6254 6255 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6256 SDValue N1, SDValue N2, SDValue N3, 6257 const SDNodeFlags Flags) { 6258 assert(N1.getOpcode() != ISD::DELETED_NODE && 6259 N2.getOpcode() != ISD::DELETED_NODE && 6260 N3.getOpcode() != ISD::DELETED_NODE && 6261 "Operand is DELETED_NODE!"); 6262 // Perform various simplifications. 6263 switch (Opcode) { 6264 case ISD::FMA: { 6265 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6266 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6267 N3.getValueType() == VT && "FMA types must match!"); 6268 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6269 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6270 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6271 if (N1CFP && N2CFP && N3CFP) { 6272 APFloat V1 = N1CFP->getValueAPF(); 6273 const APFloat &V2 = N2CFP->getValueAPF(); 6274 const APFloat &V3 = N3CFP->getValueAPF(); 6275 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6276 return getConstantFP(V1, DL, VT); 6277 } 6278 break; 6279 } 6280 case ISD::BUILD_VECTOR: { 6281 // Attempt to simplify BUILD_VECTOR. 6282 SDValue Ops[] = {N1, N2, N3}; 6283 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6284 return V; 6285 break; 6286 } 6287 case ISD::CONCAT_VECTORS: { 6288 SDValue Ops[] = {N1, N2, N3}; 6289 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6290 return V; 6291 break; 6292 } 6293 case ISD::SETCC: { 6294 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6295 assert(N1.getValueType() == N2.getValueType() && 6296 "SETCC operands must have the same type!"); 6297 assert(VT.isVector() == N1.getValueType().isVector() && 6298 "SETCC type should be vector iff the operand type is vector!"); 6299 assert((!VT.isVector() || VT.getVectorElementCount() == 6300 N1.getValueType().getVectorElementCount()) && 6301 "SETCC vector element counts must match!"); 6302 // Use FoldSetCC to simplify SETCC's. 6303 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6304 return V; 6305 // Vector constant folding. 6306 SDValue Ops[] = {N1, N2, N3}; 6307 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6308 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6309 return V; 6310 } 6311 break; 6312 } 6313 case ISD::SELECT: 6314 case ISD::VSELECT: 6315 if (SDValue V = simplifySelect(N1, N2, N3)) 6316 return V; 6317 break; 6318 case ISD::VECTOR_SHUFFLE: 6319 llvm_unreachable("should use getVectorShuffle constructor!"); 6320 case ISD::VECTOR_SPLICE: { 6321 if (cast<ConstantSDNode>(N3)->isNullValue()) 6322 return N1; 6323 break; 6324 } 6325 case ISD::INSERT_VECTOR_ELT: { 6326 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6327 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6328 // for scalable vectors where we will generate appropriate code to 6329 // deal with out-of-bounds cases correctly. 6330 if (N3C && N1.getValueType().isFixedLengthVector() && 6331 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6332 return getUNDEF(VT); 6333 6334 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6335 if (N3.isUndef()) 6336 return getUNDEF(VT); 6337 6338 // If the inserted element is an UNDEF, just use the input vector. 6339 if (N2.isUndef()) 6340 return N1; 6341 6342 break; 6343 } 6344 case ISD::INSERT_SUBVECTOR: { 6345 // Inserting undef into undef is still undef. 6346 if (N1.isUndef() && N2.isUndef()) 6347 return getUNDEF(VT); 6348 6349 EVT N2VT = N2.getValueType(); 6350 assert(VT == N1.getValueType() && 6351 "Dest and insert subvector source types must match!"); 6352 assert(VT.isVector() && N2VT.isVector() && 6353 "Insert subvector VTs must be vectors!"); 6354 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6355 "Cannot insert a scalable vector into a fixed length vector!"); 6356 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6357 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6358 "Insert subvector must be from smaller vector to larger vector!"); 6359 assert(isa<ConstantSDNode>(N3) && 6360 "Insert subvector index must be constant"); 6361 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6362 (N2VT.getVectorMinNumElements() + 6363 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6364 VT.getVectorMinNumElements()) && 6365 "Insert subvector overflow!"); 6366 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6367 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6368 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6369 6370 // Trivial insertion. 6371 if (VT == N2VT) 6372 return N2; 6373 6374 // If this is an insert of an extracted vector into an undef vector, we 6375 // can just use the input to the extract. 6376 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6377 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6378 return N2.getOperand(0); 6379 break; 6380 } 6381 case ISD::BITCAST: 6382 // Fold bit_convert nodes from a type to themselves. 6383 if (N1.getValueType() == VT) 6384 return N1; 6385 break; 6386 } 6387 6388 // Memoize node if it doesn't produce a flag. 6389 SDNode *N; 6390 SDVTList VTs = getVTList(VT); 6391 SDValue Ops[] = {N1, N2, N3}; 6392 if (VT != MVT::Glue) { 6393 FoldingSetNodeID ID; 6394 AddNodeIDNode(ID, Opcode, VTs, Ops); 6395 void *IP = nullptr; 6396 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6397 E->intersectFlagsWith(Flags); 6398 return SDValue(E, 0); 6399 } 6400 6401 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6402 N->setFlags(Flags); 6403 createOperands(N, Ops); 6404 CSEMap.InsertNode(N, IP); 6405 } else { 6406 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6407 createOperands(N, Ops); 6408 } 6409 6410 InsertNode(N); 6411 SDValue V = SDValue(N, 0); 6412 NewSDValueDbgMsg(V, "Creating new node: ", this); 6413 return V; 6414 } 6415 6416 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6417 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6418 SDValue Ops[] = { N1, N2, N3, N4 }; 6419 return getNode(Opcode, DL, VT, Ops); 6420 } 6421 6422 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6423 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6424 SDValue N5) { 6425 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6426 return getNode(Opcode, DL, VT, Ops); 6427 } 6428 6429 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6430 /// the incoming stack arguments to be loaded from the stack. 6431 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6432 SmallVector<SDValue, 8> ArgChains; 6433 6434 // Include the original chain at the beginning of the list. When this is 6435 // used by target LowerCall hooks, this helps legalize find the 6436 // CALLSEQ_BEGIN node. 6437 ArgChains.push_back(Chain); 6438 6439 // Add a chain value for each stack argument. 6440 for (SDNode *U : getEntryNode().getNode()->uses()) 6441 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6442 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6443 if (FI->getIndex() < 0) 6444 ArgChains.push_back(SDValue(L, 1)); 6445 6446 // Build a tokenfactor for all the chains. 6447 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6448 } 6449 6450 /// getMemsetValue - Vectorized representation of the memset value 6451 /// operand. 6452 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6453 const SDLoc &dl) { 6454 assert(!Value.isUndef()); 6455 6456 unsigned NumBits = VT.getScalarSizeInBits(); 6457 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6458 assert(C->getAPIntValue().getBitWidth() == 8); 6459 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6460 if (VT.isInteger()) { 6461 bool IsOpaque = VT.getSizeInBits() > 64 || 6462 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6463 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6464 } 6465 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6466 VT); 6467 } 6468 6469 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6470 EVT IntVT = VT.getScalarType(); 6471 if (!IntVT.isInteger()) 6472 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6473 6474 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6475 if (NumBits > 8) { 6476 // Use a multiplication with 0x010101... to extend the input to the 6477 // required length. 6478 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6479 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6480 DAG.getConstant(Magic, dl, IntVT)); 6481 } 6482 6483 if (VT != Value.getValueType() && !VT.isInteger()) 6484 Value = DAG.getBitcast(VT.getScalarType(), Value); 6485 if (VT != Value.getValueType()) 6486 Value = DAG.getSplatBuildVector(VT, dl, Value); 6487 6488 return Value; 6489 } 6490 6491 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6492 /// used when a memcpy is turned into a memset when the source is a constant 6493 /// string ptr. 6494 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6495 const TargetLowering &TLI, 6496 const ConstantDataArraySlice &Slice) { 6497 // Handle vector with all elements zero. 6498 if (Slice.Array == nullptr) { 6499 if (VT.isInteger()) 6500 return DAG.getConstant(0, dl, VT); 6501 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6502 return DAG.getConstantFP(0.0, dl, VT); 6503 if (VT.isVector()) { 6504 unsigned NumElts = VT.getVectorNumElements(); 6505 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6506 return DAG.getNode(ISD::BITCAST, dl, VT, 6507 DAG.getConstant(0, dl, 6508 EVT::getVectorVT(*DAG.getContext(), 6509 EltVT, NumElts))); 6510 } 6511 llvm_unreachable("Expected type!"); 6512 } 6513 6514 assert(!VT.isVector() && "Can't handle vector type here!"); 6515 unsigned NumVTBits = VT.getSizeInBits(); 6516 unsigned NumVTBytes = NumVTBits / 8; 6517 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6518 6519 APInt Val(NumVTBits, 0); 6520 if (DAG.getDataLayout().isLittleEndian()) { 6521 for (unsigned i = 0; i != NumBytes; ++i) 6522 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6523 } else { 6524 for (unsigned i = 0; i != NumBytes; ++i) 6525 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6526 } 6527 6528 // If the "cost" of materializing the integer immediate is less than the cost 6529 // of a load, then it is cost effective to turn the load into the immediate. 6530 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6531 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6532 return DAG.getConstant(Val, dl, VT); 6533 return SDValue(); 6534 } 6535 6536 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6537 const SDLoc &DL, 6538 const SDNodeFlags Flags) { 6539 EVT VT = Base.getValueType(); 6540 SDValue Index; 6541 6542 if (Offset.isScalable()) 6543 Index = getVScale(DL, Base.getValueType(), 6544 APInt(Base.getValueSizeInBits().getFixedSize(), 6545 Offset.getKnownMinSize())); 6546 else 6547 Index = getConstant(Offset.getFixedSize(), DL, VT); 6548 6549 return getMemBasePlusOffset(Base, Index, DL, Flags); 6550 } 6551 6552 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6553 const SDLoc &DL, 6554 const SDNodeFlags Flags) { 6555 assert(Offset.getValueType().isInteger()); 6556 EVT BasePtrVT = Ptr.getValueType(); 6557 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6558 } 6559 6560 /// Returns true if memcpy source is constant data. 6561 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6562 uint64_t SrcDelta = 0; 6563 GlobalAddressSDNode *G = nullptr; 6564 if (Src.getOpcode() == ISD::GlobalAddress) 6565 G = cast<GlobalAddressSDNode>(Src); 6566 else if (Src.getOpcode() == ISD::ADD && 6567 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6568 Src.getOperand(1).getOpcode() == ISD::Constant) { 6569 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6570 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6571 } 6572 if (!G) 6573 return false; 6574 6575 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6576 SrcDelta + G->getOffset()); 6577 } 6578 6579 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6580 SelectionDAG &DAG) { 6581 // On Darwin, -Os means optimize for size without hurting performance, so 6582 // only really optimize for size when -Oz (MinSize) is used. 6583 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6584 return MF.getFunction().hasMinSize(); 6585 return DAG.shouldOptForSize(); 6586 } 6587 6588 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6589 SmallVector<SDValue, 32> &OutChains, unsigned From, 6590 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6591 SmallVector<SDValue, 16> &OutStoreChains) { 6592 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6593 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6594 SmallVector<SDValue, 16> GluedLoadChains; 6595 for (unsigned i = From; i < To; ++i) { 6596 OutChains.push_back(OutLoadChains[i]); 6597 GluedLoadChains.push_back(OutLoadChains[i]); 6598 } 6599 6600 // Chain for all loads. 6601 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6602 GluedLoadChains); 6603 6604 for (unsigned i = From; i < To; ++i) { 6605 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6606 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6607 ST->getBasePtr(), ST->getMemoryVT(), 6608 ST->getMemOperand()); 6609 OutChains.push_back(NewStore); 6610 } 6611 } 6612 6613 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6614 SDValue Chain, SDValue Dst, SDValue Src, 6615 uint64_t Size, Align Alignment, 6616 bool isVol, bool AlwaysInline, 6617 MachinePointerInfo DstPtrInfo, 6618 MachinePointerInfo SrcPtrInfo, 6619 const AAMDNodes &AAInfo) { 6620 // Turn a memcpy of undef to nop. 6621 // FIXME: We need to honor volatile even is Src is undef. 6622 if (Src.isUndef()) 6623 return Chain; 6624 6625 // Expand memcpy to a series of load and store ops if the size operand falls 6626 // below a certain threshold. 6627 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6628 // rather than maybe a humongous number of loads and stores. 6629 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6630 const DataLayout &DL = DAG.getDataLayout(); 6631 LLVMContext &C = *DAG.getContext(); 6632 std::vector<EVT> MemOps; 6633 bool DstAlignCanChange = false; 6634 MachineFunction &MF = DAG.getMachineFunction(); 6635 MachineFrameInfo &MFI = MF.getFrameInfo(); 6636 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6637 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6638 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6639 DstAlignCanChange = true; 6640 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6641 if (!SrcAlign || Alignment > *SrcAlign) 6642 SrcAlign = Alignment; 6643 assert(SrcAlign && "SrcAlign must be set"); 6644 ConstantDataArraySlice Slice; 6645 // If marked as volatile, perform a copy even when marked as constant. 6646 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6647 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6648 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6649 const MemOp Op = isZeroConstant 6650 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6651 /*IsZeroMemset*/ true, isVol) 6652 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6653 *SrcAlign, isVol, CopyFromConstant); 6654 if (!TLI.findOptimalMemOpLowering( 6655 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6656 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6657 return SDValue(); 6658 6659 if (DstAlignCanChange) { 6660 Type *Ty = MemOps[0].getTypeForEVT(C); 6661 Align NewAlign = DL.getABITypeAlign(Ty); 6662 6663 // Don't promote to an alignment that would require dynamic stack 6664 // realignment. 6665 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6666 if (!TRI->hasStackRealignment(MF)) 6667 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6668 NewAlign = NewAlign / 2; 6669 6670 if (NewAlign > Alignment) { 6671 // Give the stack frame object a larger alignment if needed. 6672 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6673 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6674 Alignment = NewAlign; 6675 } 6676 } 6677 6678 // Prepare AAInfo for loads/stores after lowering this memcpy. 6679 AAMDNodes NewAAInfo = AAInfo; 6680 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6681 6682 MachineMemOperand::Flags MMOFlags = 6683 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6684 SmallVector<SDValue, 16> OutLoadChains; 6685 SmallVector<SDValue, 16> OutStoreChains; 6686 SmallVector<SDValue, 32> OutChains; 6687 unsigned NumMemOps = MemOps.size(); 6688 uint64_t SrcOff = 0, DstOff = 0; 6689 for (unsigned i = 0; i != NumMemOps; ++i) { 6690 EVT VT = MemOps[i]; 6691 unsigned VTSize = VT.getSizeInBits() / 8; 6692 SDValue Value, Store; 6693 6694 if (VTSize > Size) { 6695 // Issuing an unaligned load / store pair that overlaps with the previous 6696 // pair. Adjust the offset accordingly. 6697 assert(i == NumMemOps-1 && i != 0); 6698 SrcOff -= VTSize - Size; 6699 DstOff -= VTSize - Size; 6700 } 6701 6702 if (CopyFromConstant && 6703 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6704 // It's unlikely a store of a vector immediate can be done in a single 6705 // instruction. It would require a load from a constantpool first. 6706 // We only handle zero vectors here. 6707 // FIXME: Handle other cases where store of vector immediate is done in 6708 // a single instruction. 6709 ConstantDataArraySlice SubSlice; 6710 if (SrcOff < Slice.Length) { 6711 SubSlice = Slice; 6712 SubSlice.move(SrcOff); 6713 } else { 6714 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6715 SubSlice.Array = nullptr; 6716 SubSlice.Offset = 0; 6717 SubSlice.Length = VTSize; 6718 } 6719 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6720 if (Value.getNode()) { 6721 Store = DAG.getStore( 6722 Chain, dl, Value, 6723 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6724 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6725 OutChains.push_back(Store); 6726 } 6727 } 6728 6729 if (!Store.getNode()) { 6730 // The type might not be legal for the target. This should only happen 6731 // if the type is smaller than a legal type, as on PPC, so the right 6732 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6733 // to Load/Store if NVT==VT. 6734 // FIXME does the case above also need this? 6735 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6736 assert(NVT.bitsGE(VT)); 6737 6738 bool isDereferenceable = 6739 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6740 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6741 if (isDereferenceable) 6742 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6743 6744 Value = DAG.getExtLoad( 6745 ISD::EXTLOAD, dl, NVT, Chain, 6746 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6747 SrcPtrInfo.getWithOffset(SrcOff), VT, 6748 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6749 OutLoadChains.push_back(Value.getValue(1)); 6750 6751 Store = DAG.getTruncStore( 6752 Chain, dl, Value, 6753 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6754 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6755 OutStoreChains.push_back(Store); 6756 } 6757 SrcOff += VTSize; 6758 DstOff += VTSize; 6759 Size -= VTSize; 6760 } 6761 6762 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6763 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6764 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6765 6766 if (NumLdStInMemcpy) { 6767 // It may be that memcpy might be converted to memset if it's memcpy 6768 // of constants. In such a case, we won't have loads and stores, but 6769 // just stores. In the absence of loads, there is nothing to gang up. 6770 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6771 // If target does not care, just leave as it. 6772 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6773 OutChains.push_back(OutLoadChains[i]); 6774 OutChains.push_back(OutStoreChains[i]); 6775 } 6776 } else { 6777 // Ld/St less than/equal limit set by target. 6778 if (NumLdStInMemcpy <= GluedLdStLimit) { 6779 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6780 NumLdStInMemcpy, OutLoadChains, 6781 OutStoreChains); 6782 } else { 6783 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6784 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6785 unsigned GlueIter = 0; 6786 6787 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6788 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6789 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6790 6791 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6792 OutLoadChains, OutStoreChains); 6793 GlueIter += GluedLdStLimit; 6794 } 6795 6796 // Residual ld/st. 6797 if (RemainingLdStInMemcpy) { 6798 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6799 RemainingLdStInMemcpy, OutLoadChains, 6800 OutStoreChains); 6801 } 6802 } 6803 } 6804 } 6805 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6806 } 6807 6808 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6809 SDValue Chain, SDValue Dst, SDValue Src, 6810 uint64_t Size, Align Alignment, 6811 bool isVol, bool AlwaysInline, 6812 MachinePointerInfo DstPtrInfo, 6813 MachinePointerInfo SrcPtrInfo, 6814 const AAMDNodes &AAInfo) { 6815 // Turn a memmove of undef to nop. 6816 // FIXME: We need to honor volatile even is Src is undef. 6817 if (Src.isUndef()) 6818 return Chain; 6819 6820 // Expand memmove to a series of load and store ops if the size operand falls 6821 // below a certain threshold. 6822 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6823 const DataLayout &DL = DAG.getDataLayout(); 6824 LLVMContext &C = *DAG.getContext(); 6825 std::vector<EVT> MemOps; 6826 bool DstAlignCanChange = false; 6827 MachineFunction &MF = DAG.getMachineFunction(); 6828 MachineFrameInfo &MFI = MF.getFrameInfo(); 6829 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6830 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6831 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6832 DstAlignCanChange = true; 6833 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6834 if (!SrcAlign || Alignment > *SrcAlign) 6835 SrcAlign = Alignment; 6836 assert(SrcAlign && "SrcAlign must be set"); 6837 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6838 if (!TLI.findOptimalMemOpLowering( 6839 MemOps, Limit, 6840 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6841 /*IsVolatile*/ true), 6842 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6843 MF.getFunction().getAttributes())) 6844 return SDValue(); 6845 6846 if (DstAlignCanChange) { 6847 Type *Ty = MemOps[0].getTypeForEVT(C); 6848 Align NewAlign = DL.getABITypeAlign(Ty); 6849 if (NewAlign > Alignment) { 6850 // Give the stack frame object a larger alignment if needed. 6851 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6852 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6853 Alignment = NewAlign; 6854 } 6855 } 6856 6857 // Prepare AAInfo for loads/stores after lowering this memmove. 6858 AAMDNodes NewAAInfo = AAInfo; 6859 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6860 6861 MachineMemOperand::Flags MMOFlags = 6862 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6863 uint64_t SrcOff = 0, DstOff = 0; 6864 SmallVector<SDValue, 8> LoadValues; 6865 SmallVector<SDValue, 8> LoadChains; 6866 SmallVector<SDValue, 8> OutChains; 6867 unsigned NumMemOps = MemOps.size(); 6868 for (unsigned i = 0; i < NumMemOps; i++) { 6869 EVT VT = MemOps[i]; 6870 unsigned VTSize = VT.getSizeInBits() / 8; 6871 SDValue Value; 6872 6873 bool isDereferenceable = 6874 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6875 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6876 if (isDereferenceable) 6877 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6878 6879 Value = DAG.getLoad( 6880 VT, dl, Chain, 6881 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6882 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6883 LoadValues.push_back(Value); 6884 LoadChains.push_back(Value.getValue(1)); 6885 SrcOff += VTSize; 6886 } 6887 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6888 OutChains.clear(); 6889 for (unsigned i = 0; i < NumMemOps; i++) { 6890 EVT VT = MemOps[i]; 6891 unsigned VTSize = VT.getSizeInBits() / 8; 6892 SDValue Store; 6893 6894 Store = DAG.getStore( 6895 Chain, dl, LoadValues[i], 6896 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6897 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6898 OutChains.push_back(Store); 6899 DstOff += VTSize; 6900 } 6901 6902 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6903 } 6904 6905 /// Lower the call to 'memset' intrinsic function into a series of store 6906 /// operations. 6907 /// 6908 /// \param DAG Selection DAG where lowered code is placed. 6909 /// \param dl Link to corresponding IR location. 6910 /// \param Chain Control flow dependency. 6911 /// \param Dst Pointer to destination memory location. 6912 /// \param Src Value of byte to write into the memory. 6913 /// \param Size Number of bytes to write. 6914 /// \param Alignment Alignment of the destination in bytes. 6915 /// \param isVol True if destination is volatile. 6916 /// \param DstPtrInfo IR information on the memory pointer. 6917 /// \returns New head in the control flow, if lowering was successful, empty 6918 /// SDValue otherwise. 6919 /// 6920 /// The function tries to replace 'llvm.memset' intrinsic with several store 6921 /// operations and value calculation code. This is usually profitable for small 6922 /// memory size. 6923 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6924 SDValue Chain, SDValue Dst, SDValue Src, 6925 uint64_t Size, Align Alignment, bool isVol, 6926 MachinePointerInfo DstPtrInfo, 6927 const AAMDNodes &AAInfo) { 6928 // Turn a memset of undef to nop. 6929 // FIXME: We need to honor volatile even is Src is undef. 6930 if (Src.isUndef()) 6931 return Chain; 6932 6933 // Expand memset to a series of load/store ops if the size operand 6934 // falls below a certain threshold. 6935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6936 std::vector<EVT> MemOps; 6937 bool DstAlignCanChange = false; 6938 MachineFunction &MF = DAG.getMachineFunction(); 6939 MachineFrameInfo &MFI = MF.getFrameInfo(); 6940 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6941 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6942 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6943 DstAlignCanChange = true; 6944 bool IsZeroVal = 6945 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6946 if (!TLI.findOptimalMemOpLowering( 6947 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6948 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6949 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6950 return SDValue(); 6951 6952 if (DstAlignCanChange) { 6953 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6954 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6955 if (NewAlign > Alignment) { 6956 // Give the stack frame object a larger alignment if needed. 6957 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6958 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6959 Alignment = NewAlign; 6960 } 6961 } 6962 6963 SmallVector<SDValue, 8> OutChains; 6964 uint64_t DstOff = 0; 6965 unsigned NumMemOps = MemOps.size(); 6966 6967 // Find the largest store and generate the bit pattern for it. 6968 EVT LargestVT = MemOps[0]; 6969 for (unsigned i = 1; i < NumMemOps; i++) 6970 if (MemOps[i].bitsGT(LargestVT)) 6971 LargestVT = MemOps[i]; 6972 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6973 6974 // Prepare AAInfo for loads/stores after lowering this memset. 6975 AAMDNodes NewAAInfo = AAInfo; 6976 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6977 6978 for (unsigned i = 0; i < NumMemOps; i++) { 6979 EVT VT = MemOps[i]; 6980 unsigned VTSize = VT.getSizeInBits() / 8; 6981 if (VTSize > Size) { 6982 // Issuing an unaligned load / store pair that overlaps with the previous 6983 // pair. Adjust the offset accordingly. 6984 assert(i == NumMemOps-1 && i != 0); 6985 DstOff -= VTSize - Size; 6986 } 6987 6988 // If this store is smaller than the largest store see whether we can get 6989 // the smaller value for free with a truncate. 6990 SDValue Value = MemSetValue; 6991 if (VT.bitsLT(LargestVT)) { 6992 if (!LargestVT.isVector() && !VT.isVector() && 6993 TLI.isTruncateFree(LargestVT, VT)) 6994 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6995 else 6996 Value = getMemsetValue(Src, VT, DAG, dl); 6997 } 6998 assert(Value.getValueType() == VT && "Value with wrong type."); 6999 SDValue Store = DAG.getStore( 7000 Chain, dl, Value, 7001 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7002 DstPtrInfo.getWithOffset(DstOff), Alignment, 7003 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7004 NewAAInfo); 7005 OutChains.push_back(Store); 7006 DstOff += VT.getSizeInBits() / 8; 7007 Size -= VTSize; 7008 } 7009 7010 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7011 } 7012 7013 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7014 unsigned AS) { 7015 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7016 // pointer operands can be losslessly bitcasted to pointers of address space 0 7017 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7018 report_fatal_error("cannot lower memory intrinsic in address space " + 7019 Twine(AS)); 7020 } 7021 } 7022 7023 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7024 SDValue Src, SDValue Size, Align Alignment, 7025 bool isVol, bool AlwaysInline, bool isTailCall, 7026 MachinePointerInfo DstPtrInfo, 7027 MachinePointerInfo SrcPtrInfo, 7028 const AAMDNodes &AAInfo) { 7029 // Check to see if we should lower the memcpy to loads and stores first. 7030 // For cases within the target-specified limits, this is the best choice. 7031 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7032 if (ConstantSize) { 7033 // Memcpy with size zero? Just return the original chain. 7034 if (ConstantSize->isZero()) 7035 return Chain; 7036 7037 SDValue Result = getMemcpyLoadsAndStores( 7038 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7039 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7040 if (Result.getNode()) 7041 return Result; 7042 } 7043 7044 // Then check to see if we should lower the memcpy with target-specific 7045 // code. If the target chooses to do this, this is the next best. 7046 if (TSI) { 7047 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7048 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7049 DstPtrInfo, SrcPtrInfo); 7050 if (Result.getNode()) 7051 return Result; 7052 } 7053 7054 // If we really need inline code and the target declined to provide it, 7055 // use a (potentially long) sequence of loads and stores. 7056 if (AlwaysInline) { 7057 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7058 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 7059 ConstantSize->getZExtValue(), Alignment, 7060 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 7061 } 7062 7063 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7064 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7065 7066 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7067 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7068 // respect volatile, so they may do things like read or write memory 7069 // beyond the given memory regions. But fixing this isn't easy, and most 7070 // people don't care. 7071 7072 // Emit a library call. 7073 TargetLowering::ArgListTy Args; 7074 TargetLowering::ArgListEntry Entry; 7075 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7076 Entry.Node = Dst; Args.push_back(Entry); 7077 Entry.Node = Src; Args.push_back(Entry); 7078 7079 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7080 Entry.Node = Size; Args.push_back(Entry); 7081 // FIXME: pass in SDLoc 7082 TargetLowering::CallLoweringInfo CLI(*this); 7083 CLI.setDebugLoc(dl) 7084 .setChain(Chain) 7085 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7086 Dst.getValueType().getTypeForEVT(*getContext()), 7087 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7088 TLI->getPointerTy(getDataLayout())), 7089 std::move(Args)) 7090 .setDiscardResult() 7091 .setTailCall(isTailCall); 7092 7093 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7094 return CallResult.second; 7095 } 7096 7097 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7098 SDValue Dst, unsigned DstAlign, 7099 SDValue Src, unsigned SrcAlign, 7100 SDValue Size, Type *SizeTy, 7101 unsigned ElemSz, bool isTailCall, 7102 MachinePointerInfo DstPtrInfo, 7103 MachinePointerInfo SrcPtrInfo) { 7104 // Emit a library call. 7105 TargetLowering::ArgListTy Args; 7106 TargetLowering::ArgListEntry Entry; 7107 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7108 Entry.Node = Dst; 7109 Args.push_back(Entry); 7110 7111 Entry.Node = Src; 7112 Args.push_back(Entry); 7113 7114 Entry.Ty = SizeTy; 7115 Entry.Node = Size; 7116 Args.push_back(Entry); 7117 7118 RTLIB::Libcall LibraryCall = 7119 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7120 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7121 report_fatal_error("Unsupported element size"); 7122 7123 TargetLowering::CallLoweringInfo CLI(*this); 7124 CLI.setDebugLoc(dl) 7125 .setChain(Chain) 7126 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7127 Type::getVoidTy(*getContext()), 7128 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7129 TLI->getPointerTy(getDataLayout())), 7130 std::move(Args)) 7131 .setDiscardResult() 7132 .setTailCall(isTailCall); 7133 7134 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7135 return CallResult.second; 7136 } 7137 7138 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7139 SDValue Src, SDValue Size, Align Alignment, 7140 bool isVol, bool isTailCall, 7141 MachinePointerInfo DstPtrInfo, 7142 MachinePointerInfo SrcPtrInfo, 7143 const AAMDNodes &AAInfo) { 7144 // Check to see if we should lower the memmove to loads and stores first. 7145 // For cases within the target-specified limits, this is the best choice. 7146 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7147 if (ConstantSize) { 7148 // Memmove with size zero? Just return the original chain. 7149 if (ConstantSize->isZero()) 7150 return Chain; 7151 7152 SDValue Result = getMemmoveLoadsAndStores( 7153 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7154 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7155 if (Result.getNode()) 7156 return Result; 7157 } 7158 7159 // Then check to see if we should lower the memmove with target-specific 7160 // code. If the target chooses to do this, this is the next best. 7161 if (TSI) { 7162 SDValue Result = 7163 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7164 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7165 if (Result.getNode()) 7166 return Result; 7167 } 7168 7169 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7170 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7171 7172 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7173 // not be safe. See memcpy above for more details. 7174 7175 // Emit a library call. 7176 TargetLowering::ArgListTy Args; 7177 TargetLowering::ArgListEntry Entry; 7178 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7179 Entry.Node = Dst; Args.push_back(Entry); 7180 Entry.Node = Src; Args.push_back(Entry); 7181 7182 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7183 Entry.Node = Size; Args.push_back(Entry); 7184 // FIXME: pass in SDLoc 7185 TargetLowering::CallLoweringInfo CLI(*this); 7186 CLI.setDebugLoc(dl) 7187 .setChain(Chain) 7188 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7189 Dst.getValueType().getTypeForEVT(*getContext()), 7190 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7191 TLI->getPointerTy(getDataLayout())), 7192 std::move(Args)) 7193 .setDiscardResult() 7194 .setTailCall(isTailCall); 7195 7196 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7197 return CallResult.second; 7198 } 7199 7200 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7201 SDValue Dst, unsigned DstAlign, 7202 SDValue Src, unsigned SrcAlign, 7203 SDValue Size, Type *SizeTy, 7204 unsigned ElemSz, bool isTailCall, 7205 MachinePointerInfo DstPtrInfo, 7206 MachinePointerInfo SrcPtrInfo) { 7207 // Emit a library call. 7208 TargetLowering::ArgListTy Args; 7209 TargetLowering::ArgListEntry Entry; 7210 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7211 Entry.Node = Dst; 7212 Args.push_back(Entry); 7213 7214 Entry.Node = Src; 7215 Args.push_back(Entry); 7216 7217 Entry.Ty = SizeTy; 7218 Entry.Node = Size; 7219 Args.push_back(Entry); 7220 7221 RTLIB::Libcall LibraryCall = 7222 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7223 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7224 report_fatal_error("Unsupported element size"); 7225 7226 TargetLowering::CallLoweringInfo CLI(*this); 7227 CLI.setDebugLoc(dl) 7228 .setChain(Chain) 7229 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7230 Type::getVoidTy(*getContext()), 7231 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7232 TLI->getPointerTy(getDataLayout())), 7233 std::move(Args)) 7234 .setDiscardResult() 7235 .setTailCall(isTailCall); 7236 7237 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7238 return CallResult.second; 7239 } 7240 7241 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7242 SDValue Src, SDValue Size, Align Alignment, 7243 bool isVol, bool isTailCall, 7244 MachinePointerInfo DstPtrInfo, 7245 const AAMDNodes &AAInfo) { 7246 // Check to see if we should lower the memset to stores first. 7247 // For cases within the target-specified limits, this is the best choice. 7248 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7249 if (ConstantSize) { 7250 // Memset with size zero? Just return the original chain. 7251 if (ConstantSize->isZero()) 7252 return Chain; 7253 7254 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7255 ConstantSize->getZExtValue(), Alignment, 7256 isVol, DstPtrInfo, AAInfo); 7257 7258 if (Result.getNode()) 7259 return Result; 7260 } 7261 7262 // Then check to see if we should lower the memset with target-specific 7263 // code. If the target chooses to do this, this is the next best. 7264 if (TSI) { 7265 SDValue Result = TSI->EmitTargetCodeForMemset( 7266 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7267 if (Result.getNode()) 7268 return Result; 7269 } 7270 7271 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7272 7273 // Emit a library call. 7274 TargetLowering::ArgListTy Args; 7275 TargetLowering::ArgListEntry Entry; 7276 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7277 Args.push_back(Entry); 7278 Entry.Node = Src; 7279 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7280 Args.push_back(Entry); 7281 Entry.Node = Size; 7282 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7283 Args.push_back(Entry); 7284 7285 // FIXME: pass in SDLoc 7286 TargetLowering::CallLoweringInfo CLI(*this); 7287 CLI.setDebugLoc(dl) 7288 .setChain(Chain) 7289 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7290 Dst.getValueType().getTypeForEVT(*getContext()), 7291 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7292 TLI->getPointerTy(getDataLayout())), 7293 std::move(Args)) 7294 .setDiscardResult() 7295 .setTailCall(isTailCall); 7296 7297 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7298 return CallResult.second; 7299 } 7300 7301 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7302 SDValue Dst, unsigned DstAlign, 7303 SDValue Value, SDValue Size, Type *SizeTy, 7304 unsigned ElemSz, bool isTailCall, 7305 MachinePointerInfo DstPtrInfo) { 7306 // Emit a library call. 7307 TargetLowering::ArgListTy Args; 7308 TargetLowering::ArgListEntry Entry; 7309 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7310 Entry.Node = Dst; 7311 Args.push_back(Entry); 7312 7313 Entry.Ty = Type::getInt8Ty(*getContext()); 7314 Entry.Node = Value; 7315 Args.push_back(Entry); 7316 7317 Entry.Ty = SizeTy; 7318 Entry.Node = Size; 7319 Args.push_back(Entry); 7320 7321 RTLIB::Libcall LibraryCall = 7322 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7323 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7324 report_fatal_error("Unsupported element size"); 7325 7326 TargetLowering::CallLoweringInfo CLI(*this); 7327 CLI.setDebugLoc(dl) 7328 .setChain(Chain) 7329 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7330 Type::getVoidTy(*getContext()), 7331 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7332 TLI->getPointerTy(getDataLayout())), 7333 std::move(Args)) 7334 .setDiscardResult() 7335 .setTailCall(isTailCall); 7336 7337 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7338 return CallResult.second; 7339 } 7340 7341 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7342 SDVTList VTList, ArrayRef<SDValue> Ops, 7343 MachineMemOperand *MMO) { 7344 FoldingSetNodeID ID; 7345 ID.AddInteger(MemVT.getRawBits()); 7346 AddNodeIDNode(ID, Opcode, VTList, Ops); 7347 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7348 ID.AddInteger(MMO->getFlags()); 7349 void* IP = nullptr; 7350 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7351 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7352 return SDValue(E, 0); 7353 } 7354 7355 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7356 VTList, MemVT, MMO); 7357 createOperands(N, Ops); 7358 7359 CSEMap.InsertNode(N, IP); 7360 InsertNode(N); 7361 return SDValue(N, 0); 7362 } 7363 7364 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7365 EVT MemVT, SDVTList VTs, SDValue Chain, 7366 SDValue Ptr, SDValue Cmp, SDValue Swp, 7367 MachineMemOperand *MMO) { 7368 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7369 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7370 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7371 7372 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7373 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7374 } 7375 7376 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7377 SDValue Chain, SDValue Ptr, SDValue Val, 7378 MachineMemOperand *MMO) { 7379 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7380 Opcode == ISD::ATOMIC_LOAD_SUB || 7381 Opcode == ISD::ATOMIC_LOAD_AND || 7382 Opcode == ISD::ATOMIC_LOAD_CLR || 7383 Opcode == ISD::ATOMIC_LOAD_OR || 7384 Opcode == ISD::ATOMIC_LOAD_XOR || 7385 Opcode == ISD::ATOMIC_LOAD_NAND || 7386 Opcode == ISD::ATOMIC_LOAD_MIN || 7387 Opcode == ISD::ATOMIC_LOAD_MAX || 7388 Opcode == ISD::ATOMIC_LOAD_UMIN || 7389 Opcode == ISD::ATOMIC_LOAD_UMAX || 7390 Opcode == ISD::ATOMIC_LOAD_FADD || 7391 Opcode == ISD::ATOMIC_LOAD_FSUB || 7392 Opcode == ISD::ATOMIC_SWAP || 7393 Opcode == ISD::ATOMIC_STORE) && 7394 "Invalid Atomic Op"); 7395 7396 EVT VT = Val.getValueType(); 7397 7398 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7399 getVTList(VT, MVT::Other); 7400 SDValue Ops[] = {Chain, Ptr, Val}; 7401 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7402 } 7403 7404 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7405 EVT VT, SDValue Chain, SDValue Ptr, 7406 MachineMemOperand *MMO) { 7407 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7408 7409 SDVTList VTs = getVTList(VT, MVT::Other); 7410 SDValue Ops[] = {Chain, Ptr}; 7411 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7412 } 7413 7414 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7415 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7416 if (Ops.size() == 1) 7417 return Ops[0]; 7418 7419 SmallVector<EVT, 4> VTs; 7420 VTs.reserve(Ops.size()); 7421 for (const SDValue &Op : Ops) 7422 VTs.push_back(Op.getValueType()); 7423 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7424 } 7425 7426 SDValue SelectionDAG::getMemIntrinsicNode( 7427 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7428 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7429 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7430 if (!Size && MemVT.isScalableVector()) 7431 Size = MemoryLocation::UnknownSize; 7432 else if (!Size) 7433 Size = MemVT.getStoreSize(); 7434 7435 MachineFunction &MF = getMachineFunction(); 7436 MachineMemOperand *MMO = 7437 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7438 7439 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7440 } 7441 7442 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7443 SDVTList VTList, 7444 ArrayRef<SDValue> Ops, EVT MemVT, 7445 MachineMemOperand *MMO) { 7446 assert((Opcode == ISD::INTRINSIC_VOID || 7447 Opcode == ISD::INTRINSIC_W_CHAIN || 7448 Opcode == ISD::PREFETCH || 7449 ((int)Opcode <= std::numeric_limits<int>::max() && 7450 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7451 "Opcode is not a memory-accessing opcode!"); 7452 7453 // Memoize the node unless it returns a flag. 7454 MemIntrinsicSDNode *N; 7455 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7456 FoldingSetNodeID ID; 7457 AddNodeIDNode(ID, Opcode, VTList, Ops); 7458 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7459 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7460 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7461 ID.AddInteger(MMO->getFlags()); 7462 void *IP = nullptr; 7463 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7464 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7465 return SDValue(E, 0); 7466 } 7467 7468 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7469 VTList, MemVT, MMO); 7470 createOperands(N, Ops); 7471 7472 CSEMap.InsertNode(N, IP); 7473 } else { 7474 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7475 VTList, MemVT, MMO); 7476 createOperands(N, Ops); 7477 } 7478 InsertNode(N); 7479 SDValue V(N, 0); 7480 NewSDValueDbgMsg(V, "Creating new node: ", this); 7481 return V; 7482 } 7483 7484 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7485 SDValue Chain, int FrameIndex, 7486 int64_t Size, int64_t Offset) { 7487 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7488 const auto VTs = getVTList(MVT::Other); 7489 SDValue Ops[2] = { 7490 Chain, 7491 getFrameIndex(FrameIndex, 7492 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7493 true)}; 7494 7495 FoldingSetNodeID ID; 7496 AddNodeIDNode(ID, Opcode, VTs, Ops); 7497 ID.AddInteger(FrameIndex); 7498 ID.AddInteger(Size); 7499 ID.AddInteger(Offset); 7500 void *IP = nullptr; 7501 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7502 return SDValue(E, 0); 7503 7504 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7505 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7506 createOperands(N, Ops); 7507 CSEMap.InsertNode(N, IP); 7508 InsertNode(N); 7509 SDValue V(N, 0); 7510 NewSDValueDbgMsg(V, "Creating new node: ", this); 7511 return V; 7512 } 7513 7514 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7515 uint64_t Guid, uint64_t Index, 7516 uint32_t Attr) { 7517 const unsigned Opcode = ISD::PSEUDO_PROBE; 7518 const auto VTs = getVTList(MVT::Other); 7519 SDValue Ops[] = {Chain}; 7520 FoldingSetNodeID ID; 7521 AddNodeIDNode(ID, Opcode, VTs, Ops); 7522 ID.AddInteger(Guid); 7523 ID.AddInteger(Index); 7524 void *IP = nullptr; 7525 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7526 return SDValue(E, 0); 7527 7528 auto *N = newSDNode<PseudoProbeSDNode>( 7529 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7530 createOperands(N, Ops); 7531 CSEMap.InsertNode(N, IP); 7532 InsertNode(N); 7533 SDValue V(N, 0); 7534 NewSDValueDbgMsg(V, "Creating new node: ", this); 7535 return V; 7536 } 7537 7538 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7539 /// MachinePointerInfo record from it. This is particularly useful because the 7540 /// code generator has many cases where it doesn't bother passing in a 7541 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7542 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7543 SelectionDAG &DAG, SDValue Ptr, 7544 int64_t Offset = 0) { 7545 // If this is FI+Offset, we can model it. 7546 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7547 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7548 FI->getIndex(), Offset); 7549 7550 // If this is (FI+Offset1)+Offset2, we can model it. 7551 if (Ptr.getOpcode() != ISD::ADD || 7552 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7553 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7554 return Info; 7555 7556 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7557 return MachinePointerInfo::getFixedStack( 7558 DAG.getMachineFunction(), FI, 7559 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7560 } 7561 7562 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7563 /// MachinePointerInfo record from it. This is particularly useful because the 7564 /// code generator has many cases where it doesn't bother passing in a 7565 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7566 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7567 SelectionDAG &DAG, SDValue Ptr, 7568 SDValue OffsetOp) { 7569 // If the 'Offset' value isn't a constant, we can't handle this. 7570 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7571 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7572 if (OffsetOp.isUndef()) 7573 return InferPointerInfo(Info, DAG, Ptr); 7574 return Info; 7575 } 7576 7577 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7578 EVT VT, const SDLoc &dl, SDValue Chain, 7579 SDValue Ptr, SDValue Offset, 7580 MachinePointerInfo PtrInfo, EVT MemVT, 7581 Align Alignment, 7582 MachineMemOperand::Flags MMOFlags, 7583 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7584 assert(Chain.getValueType() == MVT::Other && 7585 "Invalid chain type"); 7586 7587 MMOFlags |= MachineMemOperand::MOLoad; 7588 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7589 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7590 // clients. 7591 if (PtrInfo.V.isNull()) 7592 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7593 7594 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7595 MachineFunction &MF = getMachineFunction(); 7596 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7597 Alignment, AAInfo, Ranges); 7598 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7599 } 7600 7601 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7602 EVT VT, const SDLoc &dl, SDValue Chain, 7603 SDValue Ptr, SDValue Offset, EVT MemVT, 7604 MachineMemOperand *MMO) { 7605 if (VT == MemVT) { 7606 ExtType = ISD::NON_EXTLOAD; 7607 } else if (ExtType == ISD::NON_EXTLOAD) { 7608 assert(VT == MemVT && "Non-extending load from different memory type!"); 7609 } else { 7610 // Extending load. 7611 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7612 "Should only be an extending load, not truncating!"); 7613 assert(VT.isInteger() == MemVT.isInteger() && 7614 "Cannot convert from FP to Int or Int -> FP!"); 7615 assert(VT.isVector() == MemVT.isVector() && 7616 "Cannot use an ext load to convert to or from a vector!"); 7617 assert((!VT.isVector() || 7618 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7619 "Cannot use an ext load to change the number of vector elements!"); 7620 } 7621 7622 bool Indexed = AM != ISD::UNINDEXED; 7623 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7624 7625 SDVTList VTs = Indexed ? 7626 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7627 SDValue Ops[] = { Chain, Ptr, Offset }; 7628 FoldingSetNodeID ID; 7629 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7630 ID.AddInteger(MemVT.getRawBits()); 7631 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7632 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7633 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7634 ID.AddInteger(MMO->getFlags()); 7635 void *IP = nullptr; 7636 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7637 cast<LoadSDNode>(E)->refineAlignment(MMO); 7638 return SDValue(E, 0); 7639 } 7640 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7641 ExtType, MemVT, MMO); 7642 createOperands(N, Ops); 7643 7644 CSEMap.InsertNode(N, IP); 7645 InsertNode(N); 7646 SDValue V(N, 0); 7647 NewSDValueDbgMsg(V, "Creating new node: ", this); 7648 return V; 7649 } 7650 7651 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7652 SDValue Ptr, MachinePointerInfo PtrInfo, 7653 MaybeAlign Alignment, 7654 MachineMemOperand::Flags MMOFlags, 7655 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7656 SDValue Undef = getUNDEF(Ptr.getValueType()); 7657 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7658 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7659 } 7660 7661 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7662 SDValue Ptr, MachineMemOperand *MMO) { 7663 SDValue Undef = getUNDEF(Ptr.getValueType()); 7664 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7665 VT, MMO); 7666 } 7667 7668 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7669 EVT VT, SDValue Chain, SDValue Ptr, 7670 MachinePointerInfo PtrInfo, EVT MemVT, 7671 MaybeAlign Alignment, 7672 MachineMemOperand::Flags MMOFlags, 7673 const AAMDNodes &AAInfo) { 7674 SDValue Undef = getUNDEF(Ptr.getValueType()); 7675 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7676 MemVT, Alignment, MMOFlags, AAInfo); 7677 } 7678 7679 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7680 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7681 MachineMemOperand *MMO) { 7682 SDValue Undef = getUNDEF(Ptr.getValueType()); 7683 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7684 MemVT, MMO); 7685 } 7686 7687 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7688 SDValue Base, SDValue Offset, 7689 ISD::MemIndexedMode AM) { 7690 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7691 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7692 // Don't propagate the invariant or dereferenceable flags. 7693 auto MMOFlags = 7694 LD->getMemOperand()->getFlags() & 7695 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7696 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7697 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7698 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7699 } 7700 7701 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7702 SDValue Ptr, MachinePointerInfo PtrInfo, 7703 Align Alignment, 7704 MachineMemOperand::Flags MMOFlags, 7705 const AAMDNodes &AAInfo) { 7706 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7707 7708 MMOFlags |= MachineMemOperand::MOStore; 7709 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7710 7711 if (PtrInfo.V.isNull()) 7712 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7713 7714 MachineFunction &MF = getMachineFunction(); 7715 uint64_t Size = 7716 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7717 MachineMemOperand *MMO = 7718 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7719 return getStore(Chain, dl, Val, Ptr, MMO); 7720 } 7721 7722 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7723 SDValue Ptr, MachineMemOperand *MMO) { 7724 assert(Chain.getValueType() == MVT::Other && 7725 "Invalid chain type"); 7726 EVT VT = Val.getValueType(); 7727 SDVTList VTs = getVTList(MVT::Other); 7728 SDValue Undef = getUNDEF(Ptr.getValueType()); 7729 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7730 FoldingSetNodeID ID; 7731 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7732 ID.AddInteger(VT.getRawBits()); 7733 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7734 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7735 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7736 ID.AddInteger(MMO->getFlags()); 7737 void *IP = nullptr; 7738 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7739 cast<StoreSDNode>(E)->refineAlignment(MMO); 7740 return SDValue(E, 0); 7741 } 7742 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7743 ISD::UNINDEXED, false, VT, MMO); 7744 createOperands(N, Ops); 7745 7746 CSEMap.InsertNode(N, IP); 7747 InsertNode(N); 7748 SDValue V(N, 0); 7749 NewSDValueDbgMsg(V, "Creating new node: ", this); 7750 return V; 7751 } 7752 7753 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7754 SDValue Ptr, MachinePointerInfo PtrInfo, 7755 EVT SVT, Align Alignment, 7756 MachineMemOperand::Flags MMOFlags, 7757 const AAMDNodes &AAInfo) { 7758 assert(Chain.getValueType() == MVT::Other && 7759 "Invalid chain type"); 7760 7761 MMOFlags |= MachineMemOperand::MOStore; 7762 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7763 7764 if (PtrInfo.V.isNull()) 7765 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7766 7767 MachineFunction &MF = getMachineFunction(); 7768 MachineMemOperand *MMO = MF.getMachineMemOperand( 7769 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7770 Alignment, AAInfo); 7771 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7772 } 7773 7774 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7775 SDValue Ptr, EVT SVT, 7776 MachineMemOperand *MMO) { 7777 EVT VT = Val.getValueType(); 7778 7779 assert(Chain.getValueType() == MVT::Other && 7780 "Invalid chain type"); 7781 if (VT == SVT) 7782 return getStore(Chain, dl, Val, Ptr, MMO); 7783 7784 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7785 "Should only be a truncating store, not extending!"); 7786 assert(VT.isInteger() == SVT.isInteger() && 7787 "Can't do FP-INT conversion!"); 7788 assert(VT.isVector() == SVT.isVector() && 7789 "Cannot use trunc store to convert to or from a vector!"); 7790 assert((!VT.isVector() || 7791 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7792 "Cannot use trunc store to change the number of vector elements!"); 7793 7794 SDVTList VTs = getVTList(MVT::Other); 7795 SDValue Undef = getUNDEF(Ptr.getValueType()); 7796 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7797 FoldingSetNodeID ID; 7798 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7799 ID.AddInteger(SVT.getRawBits()); 7800 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7801 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7802 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7803 ID.AddInteger(MMO->getFlags()); 7804 void *IP = nullptr; 7805 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7806 cast<StoreSDNode>(E)->refineAlignment(MMO); 7807 return SDValue(E, 0); 7808 } 7809 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7810 ISD::UNINDEXED, true, SVT, MMO); 7811 createOperands(N, Ops); 7812 7813 CSEMap.InsertNode(N, IP); 7814 InsertNode(N); 7815 SDValue V(N, 0); 7816 NewSDValueDbgMsg(V, "Creating new node: ", this); 7817 return V; 7818 } 7819 7820 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7821 SDValue Base, SDValue Offset, 7822 ISD::MemIndexedMode AM) { 7823 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7824 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7825 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7826 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7827 FoldingSetNodeID ID; 7828 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7829 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7830 ID.AddInteger(ST->getRawSubclassData()); 7831 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7832 ID.AddInteger(ST->getMemOperand()->getFlags()); 7833 void *IP = nullptr; 7834 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7835 return SDValue(E, 0); 7836 7837 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7838 ST->isTruncatingStore(), ST->getMemoryVT(), 7839 ST->getMemOperand()); 7840 createOperands(N, Ops); 7841 7842 CSEMap.InsertNode(N, IP); 7843 InsertNode(N); 7844 SDValue V(N, 0); 7845 NewSDValueDbgMsg(V, "Creating new node: ", this); 7846 return V; 7847 } 7848 7849 SDValue SelectionDAG::getLoadVP( 7850 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7851 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7852 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7853 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7854 const MDNode *Ranges, bool IsExpanding) { 7855 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7856 7857 MMOFlags |= MachineMemOperand::MOLoad; 7858 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7859 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7860 // clients. 7861 if (PtrInfo.V.isNull()) 7862 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7863 7864 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7865 MachineFunction &MF = getMachineFunction(); 7866 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7867 Alignment, AAInfo, Ranges); 7868 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7869 MMO, IsExpanding); 7870 } 7871 7872 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7873 ISD::LoadExtType ExtType, EVT VT, 7874 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7875 SDValue Offset, SDValue Mask, SDValue EVL, 7876 EVT MemVT, MachineMemOperand *MMO, 7877 bool IsExpanding) { 7878 bool Indexed = AM != ISD::UNINDEXED; 7879 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7880 7881 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7882 : getVTList(VT, MVT::Other); 7883 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7884 FoldingSetNodeID ID; 7885 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7886 ID.AddInteger(VT.getRawBits()); 7887 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7888 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7889 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7890 ID.AddInteger(MMO->getFlags()); 7891 void *IP = nullptr; 7892 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7893 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7894 return SDValue(E, 0); 7895 } 7896 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7897 ExtType, IsExpanding, MemVT, MMO); 7898 createOperands(N, Ops); 7899 7900 CSEMap.InsertNode(N, IP); 7901 InsertNode(N); 7902 SDValue V(N, 0); 7903 NewSDValueDbgMsg(V, "Creating new node: ", this); 7904 return V; 7905 } 7906 7907 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7908 SDValue Ptr, SDValue Mask, SDValue EVL, 7909 MachinePointerInfo PtrInfo, 7910 MaybeAlign Alignment, 7911 MachineMemOperand::Flags MMOFlags, 7912 const AAMDNodes &AAInfo, const MDNode *Ranges, 7913 bool IsExpanding) { 7914 SDValue Undef = getUNDEF(Ptr.getValueType()); 7915 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7916 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7917 IsExpanding); 7918 } 7919 7920 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7921 SDValue Ptr, SDValue Mask, SDValue EVL, 7922 MachineMemOperand *MMO, bool IsExpanding) { 7923 SDValue Undef = getUNDEF(Ptr.getValueType()); 7924 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7925 Mask, EVL, VT, MMO, IsExpanding); 7926 } 7927 7928 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7929 EVT VT, SDValue Chain, SDValue Ptr, 7930 SDValue Mask, SDValue EVL, 7931 MachinePointerInfo PtrInfo, EVT MemVT, 7932 MaybeAlign Alignment, 7933 MachineMemOperand::Flags MMOFlags, 7934 const AAMDNodes &AAInfo, bool IsExpanding) { 7935 SDValue Undef = getUNDEF(Ptr.getValueType()); 7936 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7937 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7938 IsExpanding); 7939 } 7940 7941 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7942 EVT VT, SDValue Chain, SDValue Ptr, 7943 SDValue Mask, SDValue EVL, EVT MemVT, 7944 MachineMemOperand *MMO, bool IsExpanding) { 7945 SDValue Undef = getUNDEF(Ptr.getValueType()); 7946 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7947 EVL, MemVT, MMO, IsExpanding); 7948 } 7949 7950 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7951 SDValue Base, SDValue Offset, 7952 ISD::MemIndexedMode AM) { 7953 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7954 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7955 // Don't propagate the invariant or dereferenceable flags. 7956 auto MMOFlags = 7957 LD->getMemOperand()->getFlags() & 7958 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7959 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7960 LD->getChain(), Base, Offset, LD->getMask(), 7961 LD->getVectorLength(), LD->getPointerInfo(), 7962 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7963 nullptr, LD->isExpandingLoad()); 7964 } 7965 7966 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7967 SDValue Ptr, SDValue Offset, SDValue Mask, 7968 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 7969 ISD::MemIndexedMode AM, bool IsTruncating, 7970 bool IsCompressing) { 7971 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7972 bool Indexed = AM != ISD::UNINDEXED; 7973 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 7974 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 7975 : getVTList(MVT::Other); 7976 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 7977 FoldingSetNodeID ID; 7978 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7979 ID.AddInteger(MemVT.getRawBits()); 7980 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7981 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7982 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7983 ID.AddInteger(MMO->getFlags()); 7984 void *IP = nullptr; 7985 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7986 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7987 return SDValue(E, 0); 7988 } 7989 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7990 IsTruncating, IsCompressing, MemVT, MMO); 7991 createOperands(N, Ops); 7992 7993 CSEMap.InsertNode(N, IP); 7994 InsertNode(N); 7995 SDValue V(N, 0); 7996 NewSDValueDbgMsg(V, "Creating new node: ", this); 7997 return V; 7998 } 7999 8000 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8001 SDValue Val, SDValue Ptr, SDValue Mask, 8002 SDValue EVL, MachinePointerInfo PtrInfo, 8003 EVT SVT, Align Alignment, 8004 MachineMemOperand::Flags MMOFlags, 8005 const AAMDNodes &AAInfo, 8006 bool IsCompressing) { 8007 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8008 8009 MMOFlags |= MachineMemOperand::MOStore; 8010 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8011 8012 if (PtrInfo.V.isNull()) 8013 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8014 8015 MachineFunction &MF = getMachineFunction(); 8016 MachineMemOperand *MMO = MF.getMachineMemOperand( 8017 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8018 Alignment, AAInfo); 8019 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8020 IsCompressing); 8021 } 8022 8023 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8024 SDValue Val, SDValue Ptr, SDValue Mask, 8025 SDValue EVL, EVT SVT, 8026 MachineMemOperand *MMO, 8027 bool IsCompressing) { 8028 EVT VT = Val.getValueType(); 8029 8030 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8031 if (VT == SVT) 8032 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8033 EVL, VT, MMO, ISD::UNINDEXED, 8034 /*IsTruncating*/ false, IsCompressing); 8035 8036 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8037 "Should only be a truncating store, not extending!"); 8038 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8039 assert(VT.isVector() == SVT.isVector() && 8040 "Cannot use trunc store to convert to or from a vector!"); 8041 assert((!VT.isVector() || 8042 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8043 "Cannot use trunc store to change the number of vector elements!"); 8044 8045 SDVTList VTs = getVTList(MVT::Other); 8046 SDValue Undef = getUNDEF(Ptr.getValueType()); 8047 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8048 FoldingSetNodeID ID; 8049 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8050 ID.AddInteger(SVT.getRawBits()); 8051 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8052 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8053 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8054 ID.AddInteger(MMO->getFlags()); 8055 void *IP = nullptr; 8056 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8057 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8058 return SDValue(E, 0); 8059 } 8060 auto *N = 8061 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8062 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8063 createOperands(N, Ops); 8064 8065 CSEMap.InsertNode(N, IP); 8066 InsertNode(N); 8067 SDValue V(N, 0); 8068 NewSDValueDbgMsg(V, "Creating new node: ", this); 8069 return V; 8070 } 8071 8072 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8073 SDValue Base, SDValue Offset, 8074 ISD::MemIndexedMode AM) { 8075 auto *ST = cast<VPStoreSDNode>(OrigStore); 8076 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8077 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8078 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8079 Offset, ST->getMask(), ST->getVectorLength()}; 8080 FoldingSetNodeID ID; 8081 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8082 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8083 ID.AddInteger(ST->getRawSubclassData()); 8084 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8085 ID.AddInteger(ST->getMemOperand()->getFlags()); 8086 void *IP = nullptr; 8087 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8088 return SDValue(E, 0); 8089 8090 auto *N = newSDNode<VPStoreSDNode>( 8091 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8092 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8093 createOperands(N, Ops); 8094 8095 CSEMap.InsertNode(N, IP); 8096 InsertNode(N); 8097 SDValue V(N, 0); 8098 NewSDValueDbgMsg(V, "Creating new node: ", this); 8099 return V; 8100 } 8101 8102 SDValue SelectionDAG::getStridedLoadVP( 8103 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8104 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8105 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8106 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8107 const MDNode *Ranges, bool IsExpanding) { 8108 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8109 8110 MMOFlags |= MachineMemOperand::MOLoad; 8111 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8112 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8113 // clients. 8114 if (PtrInfo.V.isNull()) 8115 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8116 8117 uint64_t Size = MemoryLocation::UnknownSize; 8118 MachineFunction &MF = getMachineFunction(); 8119 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8120 Alignment, AAInfo, Ranges); 8121 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8122 EVL, MemVT, MMO, IsExpanding); 8123 } 8124 8125 SDValue SelectionDAG::getStridedLoadVP( 8126 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8127 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8128 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8129 bool Indexed = AM != ISD::UNINDEXED; 8130 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8131 8132 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8133 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8134 : getVTList(VT, MVT::Other); 8135 FoldingSetNodeID ID; 8136 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8137 ID.AddInteger(VT.getRawBits()); 8138 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8139 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8140 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8141 8142 void *IP = nullptr; 8143 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8144 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8145 return SDValue(E, 0); 8146 } 8147 8148 auto *N = 8149 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8150 ExtType, IsExpanding, MemVT, MMO); 8151 createOperands(N, Ops); 8152 CSEMap.InsertNode(N, IP); 8153 InsertNode(N); 8154 SDValue V(N, 0); 8155 NewSDValueDbgMsg(V, "Creating new node: ", this); 8156 return V; 8157 } 8158 8159 SDValue SelectionDAG::getStridedLoadVP( 8160 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8161 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8162 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8163 const MDNode *Ranges, bool IsExpanding) { 8164 SDValue Undef = getUNDEF(Ptr.getValueType()); 8165 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8166 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8167 MMOFlags, AAInfo, Ranges, IsExpanding); 8168 } 8169 8170 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8171 SDValue Ptr, SDValue Stride, 8172 SDValue Mask, SDValue EVL, 8173 MachineMemOperand *MMO, 8174 bool IsExpanding) { 8175 SDValue Undef = getUNDEF(Ptr.getValueType()); 8176 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8177 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8178 } 8179 8180 SDValue SelectionDAG::getExtStridedLoadVP( 8181 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8182 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8183 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8184 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8185 bool IsExpanding) { 8186 SDValue Undef = getUNDEF(Ptr.getValueType()); 8187 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8188 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8189 MMOFlags, AAInfo, nullptr, IsExpanding); 8190 } 8191 8192 SDValue SelectionDAG::getExtStridedLoadVP( 8193 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8194 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8195 MachineMemOperand *MMO, bool IsExpanding) { 8196 SDValue Undef = getUNDEF(Ptr.getValueType()); 8197 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8198 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8199 } 8200 8201 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8202 SDValue Base, SDValue Offset, 8203 ISD::MemIndexedMode AM) { 8204 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8205 assert(SLD->getOffset().isUndef() && 8206 "Strided load is already a indexed load!"); 8207 // Don't propagate the invariant or dereferenceable flags. 8208 auto MMOFlags = 8209 SLD->getMemOperand()->getFlags() & 8210 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8211 return getStridedLoadVP( 8212 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8213 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8214 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8215 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8216 } 8217 8218 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8219 SDValue Val, SDValue Ptr, 8220 SDValue Offset, SDValue Stride, 8221 SDValue Mask, SDValue EVL, EVT MemVT, 8222 MachineMemOperand *MMO, 8223 ISD::MemIndexedMode AM, 8224 bool IsTruncating, bool IsCompressing) { 8225 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8226 bool Indexed = AM != ISD::UNINDEXED; 8227 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8228 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8229 : getVTList(MVT::Other); 8230 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8231 FoldingSetNodeID ID; 8232 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8233 ID.AddInteger(MemVT.getRawBits()); 8234 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8235 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8236 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8237 void *IP = nullptr; 8238 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8239 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8240 return SDValue(E, 0); 8241 } 8242 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8243 VTs, AM, IsTruncating, 8244 IsCompressing, MemVT, MMO); 8245 createOperands(N, Ops); 8246 8247 CSEMap.InsertNode(N, IP); 8248 InsertNode(N); 8249 SDValue V(N, 0); 8250 NewSDValueDbgMsg(V, "Creating new node: ", this); 8251 return V; 8252 } 8253 8254 SDValue SelectionDAG::getTruncStridedStoreVP( 8255 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8256 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8257 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8258 bool IsCompressing) { 8259 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8260 8261 MMOFlags |= MachineMemOperand::MOStore; 8262 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8263 8264 if (PtrInfo.V.isNull()) 8265 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8266 8267 MachineFunction &MF = getMachineFunction(); 8268 MachineMemOperand *MMO = MF.getMachineMemOperand( 8269 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8270 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8271 MMO, IsCompressing); 8272 } 8273 8274 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8275 SDValue Val, SDValue Ptr, 8276 SDValue Stride, SDValue Mask, 8277 SDValue EVL, EVT SVT, 8278 MachineMemOperand *MMO, 8279 bool IsCompressing) { 8280 EVT VT = Val.getValueType(); 8281 8282 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8283 if (VT == SVT) 8284 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8285 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8286 /*IsTruncating*/ false, IsCompressing); 8287 8288 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8289 "Should only be a truncating store, not extending!"); 8290 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8291 assert(VT.isVector() == SVT.isVector() && 8292 "Cannot use trunc store to convert to or from a vector!"); 8293 assert((!VT.isVector() || 8294 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8295 "Cannot use trunc store to change the number of vector elements!"); 8296 8297 SDVTList VTs = getVTList(MVT::Other); 8298 SDValue Undef = getUNDEF(Ptr.getValueType()); 8299 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8300 FoldingSetNodeID ID; 8301 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8302 ID.AddInteger(SVT.getRawBits()); 8303 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8304 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8305 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8306 void *IP = nullptr; 8307 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8308 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8309 return SDValue(E, 0); 8310 } 8311 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8312 VTs, ISD::UNINDEXED, true, 8313 IsCompressing, SVT, MMO); 8314 createOperands(N, Ops); 8315 8316 CSEMap.InsertNode(N, IP); 8317 InsertNode(N); 8318 SDValue V(N, 0); 8319 NewSDValueDbgMsg(V, "Creating new node: ", this); 8320 return V; 8321 } 8322 8323 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 8324 const SDLoc &DL, SDValue Base, 8325 SDValue Offset, 8326 ISD::MemIndexedMode AM) { 8327 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 8328 assert(SST->getOffset().isUndef() && 8329 "Strided store is already an indexed store!"); 8330 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8331 SDValue Ops[] = { 8332 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 8333 SST->getMask(), SST->getVectorLength()}; 8334 FoldingSetNodeID ID; 8335 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8336 ID.AddInteger(SST->getMemoryVT().getRawBits()); 8337 ID.AddInteger(SST->getRawSubclassData()); 8338 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 8339 void *IP = nullptr; 8340 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8341 return SDValue(E, 0); 8342 8343 auto *N = newSDNode<VPStridedStoreSDNode>( 8344 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 8345 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 8346 createOperands(N, Ops); 8347 8348 CSEMap.InsertNode(N, IP); 8349 InsertNode(N); 8350 SDValue V(N, 0); 8351 NewSDValueDbgMsg(V, "Creating new node: ", this); 8352 return V; 8353 } 8354 8355 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8356 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8357 ISD::MemIndexType IndexType) { 8358 assert(Ops.size() == 6 && "Incompatible number of operands"); 8359 8360 FoldingSetNodeID ID; 8361 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8362 ID.AddInteger(VT.getRawBits()); 8363 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8364 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8365 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8366 ID.AddInteger(MMO->getFlags()); 8367 void *IP = nullptr; 8368 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8369 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8370 return SDValue(E, 0); 8371 } 8372 8373 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8374 VT, MMO, IndexType); 8375 createOperands(N, Ops); 8376 8377 assert(N->getMask().getValueType().getVectorElementCount() == 8378 N->getValueType(0).getVectorElementCount() && 8379 "Vector width mismatch between mask and data"); 8380 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8381 N->getValueType(0).getVectorElementCount().isScalable() && 8382 "Scalable flags of index and data do not match"); 8383 assert(ElementCount::isKnownGE( 8384 N->getIndex().getValueType().getVectorElementCount(), 8385 N->getValueType(0).getVectorElementCount()) && 8386 "Vector width mismatch between index and data"); 8387 assert(isa<ConstantSDNode>(N->getScale()) && 8388 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8389 "Scale should be a constant power of 2"); 8390 8391 CSEMap.InsertNode(N, IP); 8392 InsertNode(N); 8393 SDValue V(N, 0); 8394 NewSDValueDbgMsg(V, "Creating new node: ", this); 8395 return V; 8396 } 8397 8398 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8399 ArrayRef<SDValue> Ops, 8400 MachineMemOperand *MMO, 8401 ISD::MemIndexType IndexType) { 8402 assert(Ops.size() == 7 && "Incompatible number of operands"); 8403 8404 FoldingSetNodeID ID; 8405 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8406 ID.AddInteger(VT.getRawBits()); 8407 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8408 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8409 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8410 ID.AddInteger(MMO->getFlags()); 8411 void *IP = nullptr; 8412 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8413 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8414 return SDValue(E, 0); 8415 } 8416 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8417 VT, MMO, IndexType); 8418 createOperands(N, Ops); 8419 8420 assert(N->getMask().getValueType().getVectorElementCount() == 8421 N->getValue().getValueType().getVectorElementCount() && 8422 "Vector width mismatch between mask and data"); 8423 assert( 8424 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8425 N->getValue().getValueType().getVectorElementCount().isScalable() && 8426 "Scalable flags of index and data do not match"); 8427 assert(ElementCount::isKnownGE( 8428 N->getIndex().getValueType().getVectorElementCount(), 8429 N->getValue().getValueType().getVectorElementCount()) && 8430 "Vector width mismatch between index and data"); 8431 assert(isa<ConstantSDNode>(N->getScale()) && 8432 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8433 "Scale should be a constant power of 2"); 8434 8435 CSEMap.InsertNode(N, IP); 8436 InsertNode(N); 8437 SDValue V(N, 0); 8438 NewSDValueDbgMsg(V, "Creating new node: ", this); 8439 return V; 8440 } 8441 8442 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8443 SDValue Base, SDValue Offset, SDValue Mask, 8444 SDValue PassThru, EVT MemVT, 8445 MachineMemOperand *MMO, 8446 ISD::MemIndexedMode AM, 8447 ISD::LoadExtType ExtTy, bool isExpanding) { 8448 bool Indexed = AM != ISD::UNINDEXED; 8449 assert((Indexed || Offset.isUndef()) && 8450 "Unindexed masked load with an offset!"); 8451 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8452 : getVTList(VT, MVT::Other); 8453 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8454 FoldingSetNodeID ID; 8455 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8456 ID.AddInteger(MemVT.getRawBits()); 8457 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8458 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8459 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8460 ID.AddInteger(MMO->getFlags()); 8461 void *IP = nullptr; 8462 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8463 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8464 return SDValue(E, 0); 8465 } 8466 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8467 AM, ExtTy, isExpanding, MemVT, MMO); 8468 createOperands(N, Ops); 8469 8470 CSEMap.InsertNode(N, IP); 8471 InsertNode(N); 8472 SDValue V(N, 0); 8473 NewSDValueDbgMsg(V, "Creating new node: ", this); 8474 return V; 8475 } 8476 8477 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8478 SDValue Base, SDValue Offset, 8479 ISD::MemIndexedMode AM) { 8480 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8481 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8482 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8483 Offset, LD->getMask(), LD->getPassThru(), 8484 LD->getMemoryVT(), LD->getMemOperand(), AM, 8485 LD->getExtensionType(), LD->isExpandingLoad()); 8486 } 8487 8488 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8489 SDValue Val, SDValue Base, SDValue Offset, 8490 SDValue Mask, EVT MemVT, 8491 MachineMemOperand *MMO, 8492 ISD::MemIndexedMode AM, bool IsTruncating, 8493 bool IsCompressing) { 8494 assert(Chain.getValueType() == MVT::Other && 8495 "Invalid chain type"); 8496 bool Indexed = AM != ISD::UNINDEXED; 8497 assert((Indexed || Offset.isUndef()) && 8498 "Unindexed masked store with an offset!"); 8499 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8500 : getVTList(MVT::Other); 8501 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8502 FoldingSetNodeID ID; 8503 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8504 ID.AddInteger(MemVT.getRawBits()); 8505 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8506 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8507 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8508 ID.AddInteger(MMO->getFlags()); 8509 void *IP = nullptr; 8510 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8511 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8512 return SDValue(E, 0); 8513 } 8514 auto *N = 8515 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8516 IsTruncating, IsCompressing, MemVT, MMO); 8517 createOperands(N, Ops); 8518 8519 CSEMap.InsertNode(N, IP); 8520 InsertNode(N); 8521 SDValue V(N, 0); 8522 NewSDValueDbgMsg(V, "Creating new node: ", this); 8523 return V; 8524 } 8525 8526 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8527 SDValue Base, SDValue Offset, 8528 ISD::MemIndexedMode AM) { 8529 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8530 assert(ST->getOffset().isUndef() && 8531 "Masked store is already a indexed store!"); 8532 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8533 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8534 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8535 } 8536 8537 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8538 ArrayRef<SDValue> Ops, 8539 MachineMemOperand *MMO, 8540 ISD::MemIndexType IndexType, 8541 ISD::LoadExtType ExtTy) { 8542 assert(Ops.size() == 6 && "Incompatible number of operands"); 8543 8544 FoldingSetNodeID ID; 8545 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8546 ID.AddInteger(MemVT.getRawBits()); 8547 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8548 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8549 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8550 ID.AddInteger(MMO->getFlags()); 8551 void *IP = nullptr; 8552 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8553 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8554 return SDValue(E, 0); 8555 } 8556 8557 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8558 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8559 VTs, MemVT, MMO, IndexType, ExtTy); 8560 createOperands(N, Ops); 8561 8562 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8563 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8564 assert(N->getMask().getValueType().getVectorElementCount() == 8565 N->getValueType(0).getVectorElementCount() && 8566 "Vector width mismatch between mask and data"); 8567 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8568 N->getValueType(0).getVectorElementCount().isScalable() && 8569 "Scalable flags of index and data do not match"); 8570 assert(ElementCount::isKnownGE( 8571 N->getIndex().getValueType().getVectorElementCount(), 8572 N->getValueType(0).getVectorElementCount()) && 8573 "Vector width mismatch between index and data"); 8574 assert(isa<ConstantSDNode>(N->getScale()) && 8575 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8576 "Scale should be a constant power of 2"); 8577 8578 CSEMap.InsertNode(N, IP); 8579 InsertNode(N); 8580 SDValue V(N, 0); 8581 NewSDValueDbgMsg(V, "Creating new node: ", this); 8582 return V; 8583 } 8584 8585 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8586 ArrayRef<SDValue> Ops, 8587 MachineMemOperand *MMO, 8588 ISD::MemIndexType IndexType, 8589 bool IsTrunc) { 8590 assert(Ops.size() == 6 && "Incompatible number of operands"); 8591 8592 FoldingSetNodeID ID; 8593 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8594 ID.AddInteger(MemVT.getRawBits()); 8595 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8596 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8597 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8598 ID.AddInteger(MMO->getFlags()); 8599 void *IP = nullptr; 8600 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8601 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8602 return SDValue(E, 0); 8603 } 8604 8605 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8606 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8607 VTs, MemVT, MMO, IndexType, IsTrunc); 8608 createOperands(N, Ops); 8609 8610 assert(N->getMask().getValueType().getVectorElementCount() == 8611 N->getValue().getValueType().getVectorElementCount() && 8612 "Vector width mismatch between mask and data"); 8613 assert( 8614 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8615 N->getValue().getValueType().getVectorElementCount().isScalable() && 8616 "Scalable flags of index and data do not match"); 8617 assert(ElementCount::isKnownGE( 8618 N->getIndex().getValueType().getVectorElementCount(), 8619 N->getValue().getValueType().getVectorElementCount()) && 8620 "Vector width mismatch between index and data"); 8621 assert(isa<ConstantSDNode>(N->getScale()) && 8622 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8623 "Scale should be a constant power of 2"); 8624 8625 CSEMap.InsertNode(N, IP); 8626 InsertNode(N); 8627 SDValue V(N, 0); 8628 NewSDValueDbgMsg(V, "Creating new node: ", this); 8629 return V; 8630 } 8631 8632 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8633 // select undef, T, F --> T (if T is a constant), otherwise F 8634 // select, ?, undef, F --> F 8635 // select, ?, T, undef --> T 8636 if (Cond.isUndef()) 8637 return isConstantValueOfAnyType(T) ? T : F; 8638 if (T.isUndef()) 8639 return F; 8640 if (F.isUndef()) 8641 return T; 8642 8643 // select true, T, F --> T 8644 // select false, T, F --> F 8645 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8646 return CondC->isZero() ? F : T; 8647 8648 // TODO: This should simplify VSELECT with constant condition using something 8649 // like this (but check boolean contents to be complete?): 8650 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8651 // return T; 8652 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8653 // return F; 8654 8655 // select ?, T, T --> T 8656 if (T == F) 8657 return T; 8658 8659 return SDValue(); 8660 } 8661 8662 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8663 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8664 if (X.isUndef()) 8665 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8666 // shift X, undef --> undef (because it may shift by the bitwidth) 8667 if (Y.isUndef()) 8668 return getUNDEF(X.getValueType()); 8669 8670 // shift 0, Y --> 0 8671 // shift X, 0 --> X 8672 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8673 return X; 8674 8675 // shift X, C >= bitwidth(X) --> undef 8676 // All vector elements must be too big (or undef) to avoid partial undefs. 8677 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8678 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8679 }; 8680 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8681 return getUNDEF(X.getValueType()); 8682 8683 return SDValue(); 8684 } 8685 8686 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8687 SDNodeFlags Flags) { 8688 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8689 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8690 // operation is poison. That result can be relaxed to undef. 8691 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8692 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8693 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8694 (YC && YC->getValueAPF().isNaN()); 8695 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8696 (YC && YC->getValueAPF().isInfinity()); 8697 8698 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8699 return getUNDEF(X.getValueType()); 8700 8701 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8702 return getUNDEF(X.getValueType()); 8703 8704 if (!YC) 8705 return SDValue(); 8706 8707 // X + -0.0 --> X 8708 if (Opcode == ISD::FADD) 8709 if (YC->getValueAPF().isNegZero()) 8710 return X; 8711 8712 // X - +0.0 --> X 8713 if (Opcode == ISD::FSUB) 8714 if (YC->getValueAPF().isPosZero()) 8715 return X; 8716 8717 // X * 1.0 --> X 8718 // X / 1.0 --> X 8719 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8720 if (YC->getValueAPF().isExactlyValue(1.0)) 8721 return X; 8722 8723 // X * 0.0 --> 0.0 8724 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8725 if (YC->getValueAPF().isZero()) 8726 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8727 8728 return SDValue(); 8729 } 8730 8731 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8732 SDValue Ptr, SDValue SV, unsigned Align) { 8733 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8734 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8735 } 8736 8737 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8738 ArrayRef<SDUse> Ops) { 8739 switch (Ops.size()) { 8740 case 0: return getNode(Opcode, DL, VT); 8741 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8742 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8743 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8744 default: break; 8745 } 8746 8747 // Copy from an SDUse array into an SDValue array for use with 8748 // the regular getNode logic. 8749 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8750 return getNode(Opcode, DL, VT, NewOps); 8751 } 8752 8753 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8754 ArrayRef<SDValue> Ops) { 8755 SDNodeFlags Flags; 8756 if (Inserter) 8757 Flags = Inserter->getFlags(); 8758 return getNode(Opcode, DL, VT, Ops, Flags); 8759 } 8760 8761 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8762 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8763 unsigned NumOps = Ops.size(); 8764 switch (NumOps) { 8765 case 0: return getNode(Opcode, DL, VT); 8766 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8767 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8768 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8769 default: break; 8770 } 8771 8772 #ifndef NDEBUG 8773 for (auto &Op : Ops) 8774 assert(Op.getOpcode() != ISD::DELETED_NODE && 8775 "Operand is DELETED_NODE!"); 8776 #endif 8777 8778 switch (Opcode) { 8779 default: break; 8780 case ISD::BUILD_VECTOR: 8781 // Attempt to simplify BUILD_VECTOR. 8782 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8783 return V; 8784 break; 8785 case ISD::CONCAT_VECTORS: 8786 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8787 return V; 8788 break; 8789 case ISD::SELECT_CC: 8790 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8791 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8792 "LHS and RHS of condition must have same type!"); 8793 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8794 "True and False arms of SelectCC must have same type!"); 8795 assert(Ops[2].getValueType() == VT && 8796 "select_cc node must be of same type as true and false value!"); 8797 break; 8798 case ISD::BR_CC: 8799 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8800 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8801 "LHS/RHS of comparison should match types!"); 8802 break; 8803 } 8804 8805 // Memoize nodes. 8806 SDNode *N; 8807 SDVTList VTs = getVTList(VT); 8808 8809 if (VT != MVT::Glue) { 8810 FoldingSetNodeID ID; 8811 AddNodeIDNode(ID, Opcode, VTs, Ops); 8812 void *IP = nullptr; 8813 8814 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8815 return SDValue(E, 0); 8816 8817 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8818 createOperands(N, Ops); 8819 8820 CSEMap.InsertNode(N, IP); 8821 } else { 8822 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8823 createOperands(N, Ops); 8824 } 8825 8826 N->setFlags(Flags); 8827 InsertNode(N); 8828 SDValue V(N, 0); 8829 NewSDValueDbgMsg(V, "Creating new node: ", this); 8830 return V; 8831 } 8832 8833 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8834 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8835 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8836 } 8837 8838 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8839 ArrayRef<SDValue> Ops) { 8840 SDNodeFlags Flags; 8841 if (Inserter) 8842 Flags = Inserter->getFlags(); 8843 return getNode(Opcode, DL, VTList, Ops, Flags); 8844 } 8845 8846 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8847 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8848 if (VTList.NumVTs == 1) 8849 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8850 8851 #ifndef NDEBUG 8852 for (auto &Op : Ops) 8853 assert(Op.getOpcode() != ISD::DELETED_NODE && 8854 "Operand is DELETED_NODE!"); 8855 #endif 8856 8857 switch (Opcode) { 8858 case ISD::STRICT_FP_EXTEND: 8859 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8860 "Invalid STRICT_FP_EXTEND!"); 8861 assert(VTList.VTs[0].isFloatingPoint() && 8862 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8863 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8864 "STRICT_FP_EXTEND result type should be vector iff the operand " 8865 "type is vector!"); 8866 assert((!VTList.VTs[0].isVector() || 8867 VTList.VTs[0].getVectorNumElements() == 8868 Ops[1].getValueType().getVectorNumElements()) && 8869 "Vector element count mismatch!"); 8870 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8871 "Invalid fpext node, dst <= src!"); 8872 break; 8873 case ISD::STRICT_FP_ROUND: 8874 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8875 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8876 "STRICT_FP_ROUND result type should be vector iff the operand " 8877 "type is vector!"); 8878 assert((!VTList.VTs[0].isVector() || 8879 VTList.VTs[0].getVectorNumElements() == 8880 Ops[1].getValueType().getVectorNumElements()) && 8881 "Vector element count mismatch!"); 8882 assert(VTList.VTs[0].isFloatingPoint() && 8883 Ops[1].getValueType().isFloatingPoint() && 8884 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8885 isa<ConstantSDNode>(Ops[2]) && 8886 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8887 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8888 "Invalid STRICT_FP_ROUND!"); 8889 break; 8890 #if 0 8891 // FIXME: figure out how to safely handle things like 8892 // int foo(int x) { return 1 << (x & 255); } 8893 // int bar() { return foo(256); } 8894 case ISD::SRA_PARTS: 8895 case ISD::SRL_PARTS: 8896 case ISD::SHL_PARTS: 8897 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8898 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8899 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8900 else if (N3.getOpcode() == ISD::AND) 8901 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8902 // If the and is only masking out bits that cannot effect the shift, 8903 // eliminate the and. 8904 unsigned NumBits = VT.getScalarSizeInBits()*2; 8905 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8906 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8907 } 8908 break; 8909 #endif 8910 } 8911 8912 // Memoize the node unless it returns a flag. 8913 SDNode *N; 8914 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8915 FoldingSetNodeID ID; 8916 AddNodeIDNode(ID, Opcode, VTList, Ops); 8917 void *IP = nullptr; 8918 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8919 return SDValue(E, 0); 8920 8921 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8922 createOperands(N, Ops); 8923 CSEMap.InsertNode(N, IP); 8924 } else { 8925 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8926 createOperands(N, Ops); 8927 } 8928 8929 N->setFlags(Flags); 8930 InsertNode(N); 8931 SDValue V(N, 0); 8932 NewSDValueDbgMsg(V, "Creating new node: ", this); 8933 return V; 8934 } 8935 8936 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8937 SDVTList VTList) { 8938 return getNode(Opcode, DL, VTList, None); 8939 } 8940 8941 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8942 SDValue N1) { 8943 SDValue Ops[] = { N1 }; 8944 return getNode(Opcode, DL, VTList, Ops); 8945 } 8946 8947 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8948 SDValue N1, SDValue N2) { 8949 SDValue Ops[] = { N1, N2 }; 8950 return getNode(Opcode, DL, VTList, Ops); 8951 } 8952 8953 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8954 SDValue N1, SDValue N2, SDValue N3) { 8955 SDValue Ops[] = { N1, N2, N3 }; 8956 return getNode(Opcode, DL, VTList, Ops); 8957 } 8958 8959 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8960 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8961 SDValue Ops[] = { N1, N2, N3, N4 }; 8962 return getNode(Opcode, DL, VTList, Ops); 8963 } 8964 8965 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8966 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8967 SDValue N5) { 8968 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8969 return getNode(Opcode, DL, VTList, Ops); 8970 } 8971 8972 SDVTList SelectionDAG::getVTList(EVT VT) { 8973 return makeVTList(SDNode::getValueTypeList(VT), 1); 8974 } 8975 8976 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8977 FoldingSetNodeID ID; 8978 ID.AddInteger(2U); 8979 ID.AddInteger(VT1.getRawBits()); 8980 ID.AddInteger(VT2.getRawBits()); 8981 8982 void *IP = nullptr; 8983 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8984 if (!Result) { 8985 EVT *Array = Allocator.Allocate<EVT>(2); 8986 Array[0] = VT1; 8987 Array[1] = VT2; 8988 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8989 VTListMap.InsertNode(Result, IP); 8990 } 8991 return Result->getSDVTList(); 8992 } 8993 8994 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 8995 FoldingSetNodeID ID; 8996 ID.AddInteger(3U); 8997 ID.AddInteger(VT1.getRawBits()); 8998 ID.AddInteger(VT2.getRawBits()); 8999 ID.AddInteger(VT3.getRawBits()); 9000 9001 void *IP = nullptr; 9002 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9003 if (!Result) { 9004 EVT *Array = Allocator.Allocate<EVT>(3); 9005 Array[0] = VT1; 9006 Array[1] = VT2; 9007 Array[2] = VT3; 9008 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9009 VTListMap.InsertNode(Result, IP); 9010 } 9011 return Result->getSDVTList(); 9012 } 9013 9014 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9015 FoldingSetNodeID ID; 9016 ID.AddInteger(4U); 9017 ID.AddInteger(VT1.getRawBits()); 9018 ID.AddInteger(VT2.getRawBits()); 9019 ID.AddInteger(VT3.getRawBits()); 9020 ID.AddInteger(VT4.getRawBits()); 9021 9022 void *IP = nullptr; 9023 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9024 if (!Result) { 9025 EVT *Array = Allocator.Allocate<EVT>(4); 9026 Array[0] = VT1; 9027 Array[1] = VT2; 9028 Array[2] = VT3; 9029 Array[3] = VT4; 9030 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9031 VTListMap.InsertNode(Result, IP); 9032 } 9033 return Result->getSDVTList(); 9034 } 9035 9036 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9037 unsigned NumVTs = VTs.size(); 9038 FoldingSetNodeID ID; 9039 ID.AddInteger(NumVTs); 9040 for (unsigned index = 0; index < NumVTs; index++) { 9041 ID.AddInteger(VTs[index].getRawBits()); 9042 } 9043 9044 void *IP = nullptr; 9045 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9046 if (!Result) { 9047 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9048 llvm::copy(VTs, Array); 9049 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9050 VTListMap.InsertNode(Result, IP); 9051 } 9052 return Result->getSDVTList(); 9053 } 9054 9055 9056 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9057 /// specified operands. If the resultant node already exists in the DAG, 9058 /// this does not modify the specified node, instead it returns the node that 9059 /// already exists. If the resultant node does not exist in the DAG, the 9060 /// input node is returned. As a degenerate case, if you specify the same 9061 /// input operands as the node already has, the input node is returned. 9062 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9063 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9064 9065 // Check to see if there is no change. 9066 if (Op == N->getOperand(0)) return N; 9067 9068 // See if the modified node already exists. 9069 void *InsertPos = nullptr; 9070 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9071 return Existing; 9072 9073 // Nope it doesn't. Remove the node from its current place in the maps. 9074 if (InsertPos) 9075 if (!RemoveNodeFromCSEMaps(N)) 9076 InsertPos = nullptr; 9077 9078 // Now we update the operands. 9079 N->OperandList[0].set(Op); 9080 9081 updateDivergence(N); 9082 // If this gets put into a CSE map, add it. 9083 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9084 return N; 9085 } 9086 9087 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9088 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9089 9090 // Check to see if there is no change. 9091 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9092 return N; // No operands changed, just return the input node. 9093 9094 // See if the modified node already exists. 9095 void *InsertPos = nullptr; 9096 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9097 return Existing; 9098 9099 // Nope it doesn't. Remove the node from its current place in the maps. 9100 if (InsertPos) 9101 if (!RemoveNodeFromCSEMaps(N)) 9102 InsertPos = nullptr; 9103 9104 // Now we update the operands. 9105 if (N->OperandList[0] != Op1) 9106 N->OperandList[0].set(Op1); 9107 if (N->OperandList[1] != Op2) 9108 N->OperandList[1].set(Op2); 9109 9110 updateDivergence(N); 9111 // If this gets put into a CSE map, add it. 9112 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9113 return N; 9114 } 9115 9116 SDNode *SelectionDAG:: 9117 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9118 SDValue Ops[] = { Op1, Op2, Op3 }; 9119 return UpdateNodeOperands(N, Ops); 9120 } 9121 9122 SDNode *SelectionDAG:: 9123 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9124 SDValue Op3, SDValue Op4) { 9125 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9126 return UpdateNodeOperands(N, Ops); 9127 } 9128 9129 SDNode *SelectionDAG:: 9130 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9131 SDValue Op3, SDValue Op4, SDValue Op5) { 9132 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9133 return UpdateNodeOperands(N, Ops); 9134 } 9135 9136 SDNode *SelectionDAG:: 9137 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9138 unsigned NumOps = Ops.size(); 9139 assert(N->getNumOperands() == NumOps && 9140 "Update with wrong number of operands"); 9141 9142 // If no operands changed just return the input node. 9143 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9144 return N; 9145 9146 // See if the modified node already exists. 9147 void *InsertPos = nullptr; 9148 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9149 return Existing; 9150 9151 // Nope it doesn't. Remove the node from its current place in the maps. 9152 if (InsertPos) 9153 if (!RemoveNodeFromCSEMaps(N)) 9154 InsertPos = nullptr; 9155 9156 // Now we update the operands. 9157 for (unsigned i = 0; i != NumOps; ++i) 9158 if (N->OperandList[i] != Ops[i]) 9159 N->OperandList[i].set(Ops[i]); 9160 9161 updateDivergence(N); 9162 // If this gets put into a CSE map, add it. 9163 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9164 return N; 9165 } 9166 9167 /// DropOperands - Release the operands and set this node to have 9168 /// zero operands. 9169 void SDNode::DropOperands() { 9170 // Unlike the code in MorphNodeTo that does this, we don't need to 9171 // watch for dead nodes here. 9172 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9173 SDUse &Use = *I++; 9174 Use.set(SDValue()); 9175 } 9176 } 9177 9178 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9179 ArrayRef<MachineMemOperand *> NewMemRefs) { 9180 if (NewMemRefs.empty()) { 9181 N->clearMemRefs(); 9182 return; 9183 } 9184 9185 // Check if we can avoid allocating by storing a single reference directly. 9186 if (NewMemRefs.size() == 1) { 9187 N->MemRefs = NewMemRefs[0]; 9188 N->NumMemRefs = 1; 9189 return; 9190 } 9191 9192 MachineMemOperand **MemRefsBuffer = 9193 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 9194 llvm::copy(NewMemRefs, MemRefsBuffer); 9195 N->MemRefs = MemRefsBuffer; 9196 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 9197 } 9198 9199 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 9200 /// machine opcode. 9201 /// 9202 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9203 EVT VT) { 9204 SDVTList VTs = getVTList(VT); 9205 return SelectNodeTo(N, MachineOpc, VTs, None); 9206 } 9207 9208 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9209 EVT VT, SDValue Op1) { 9210 SDVTList VTs = getVTList(VT); 9211 SDValue Ops[] = { Op1 }; 9212 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9213 } 9214 9215 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9216 EVT VT, SDValue Op1, 9217 SDValue Op2) { 9218 SDVTList VTs = getVTList(VT); 9219 SDValue Ops[] = { Op1, Op2 }; 9220 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9221 } 9222 9223 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9224 EVT VT, SDValue Op1, 9225 SDValue Op2, SDValue Op3) { 9226 SDVTList VTs = getVTList(VT); 9227 SDValue Ops[] = { Op1, Op2, Op3 }; 9228 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9229 } 9230 9231 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9232 EVT VT, ArrayRef<SDValue> Ops) { 9233 SDVTList VTs = getVTList(VT); 9234 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9235 } 9236 9237 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9238 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 9239 SDVTList VTs = getVTList(VT1, VT2); 9240 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9241 } 9242 9243 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9244 EVT VT1, EVT VT2) { 9245 SDVTList VTs = getVTList(VT1, VT2); 9246 return SelectNodeTo(N, MachineOpc, VTs, None); 9247 } 9248 9249 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9250 EVT VT1, EVT VT2, EVT VT3, 9251 ArrayRef<SDValue> Ops) { 9252 SDVTList VTs = getVTList(VT1, VT2, VT3); 9253 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9254 } 9255 9256 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9257 EVT VT1, EVT VT2, 9258 SDValue Op1, SDValue Op2) { 9259 SDVTList VTs = getVTList(VT1, VT2); 9260 SDValue Ops[] = { Op1, Op2 }; 9261 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9262 } 9263 9264 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9265 SDVTList VTs,ArrayRef<SDValue> Ops) { 9266 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 9267 // Reset the NodeID to -1. 9268 New->setNodeId(-1); 9269 if (New != N) { 9270 ReplaceAllUsesWith(N, New); 9271 RemoveDeadNode(N); 9272 } 9273 return New; 9274 } 9275 9276 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 9277 /// the line number information on the merged node since it is not possible to 9278 /// preserve the information that operation is associated with multiple lines. 9279 /// This will make the debugger working better at -O0, were there is a higher 9280 /// probability having other instructions associated with that line. 9281 /// 9282 /// For IROrder, we keep the smaller of the two 9283 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 9284 DebugLoc NLoc = N->getDebugLoc(); 9285 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 9286 N->setDebugLoc(DebugLoc()); 9287 } 9288 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 9289 N->setIROrder(Order); 9290 return N; 9291 } 9292 9293 /// MorphNodeTo - This *mutates* the specified node to have the specified 9294 /// return type, opcode, and operands. 9295 /// 9296 /// Note that MorphNodeTo returns the resultant node. If there is already a 9297 /// node of the specified opcode and operands, it returns that node instead of 9298 /// the current one. Note that the SDLoc need not be the same. 9299 /// 9300 /// Using MorphNodeTo is faster than creating a new node and swapping it in 9301 /// with ReplaceAllUsesWith both because it often avoids allocating a new 9302 /// node, and because it doesn't require CSE recalculation for any of 9303 /// the node's users. 9304 /// 9305 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 9306 /// As a consequence it isn't appropriate to use from within the DAG combiner or 9307 /// the legalizer which maintain worklists that would need to be updated when 9308 /// deleting things. 9309 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 9310 SDVTList VTs, ArrayRef<SDValue> Ops) { 9311 // If an identical node already exists, use it. 9312 void *IP = nullptr; 9313 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 9314 FoldingSetNodeID ID; 9315 AddNodeIDNode(ID, Opc, VTs, Ops); 9316 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 9317 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 9318 } 9319 9320 if (!RemoveNodeFromCSEMaps(N)) 9321 IP = nullptr; 9322 9323 // Start the morphing. 9324 N->NodeType = Opc; 9325 N->ValueList = VTs.VTs; 9326 N->NumValues = VTs.NumVTs; 9327 9328 // Clear the operands list, updating used nodes to remove this from their 9329 // use list. Keep track of any operands that become dead as a result. 9330 SmallPtrSet<SDNode*, 16> DeadNodeSet; 9331 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 9332 SDUse &Use = *I++; 9333 SDNode *Used = Use.getNode(); 9334 Use.set(SDValue()); 9335 if (Used->use_empty()) 9336 DeadNodeSet.insert(Used); 9337 } 9338 9339 // For MachineNode, initialize the memory references information. 9340 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 9341 MN->clearMemRefs(); 9342 9343 // Swap for an appropriately sized array from the recycler. 9344 removeOperands(N); 9345 createOperands(N, Ops); 9346 9347 // Delete any nodes that are still dead after adding the uses for the 9348 // new operands. 9349 if (!DeadNodeSet.empty()) { 9350 SmallVector<SDNode *, 16> DeadNodes; 9351 for (SDNode *N : DeadNodeSet) 9352 if (N->use_empty()) 9353 DeadNodes.push_back(N); 9354 RemoveDeadNodes(DeadNodes); 9355 } 9356 9357 if (IP) 9358 CSEMap.InsertNode(N, IP); // Memoize the new node. 9359 return N; 9360 } 9361 9362 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9363 unsigned OrigOpc = Node->getOpcode(); 9364 unsigned NewOpc; 9365 switch (OrigOpc) { 9366 default: 9367 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9368 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9369 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9370 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9371 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9372 #include "llvm/IR/ConstrainedOps.def" 9373 } 9374 9375 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9376 9377 // We're taking this node out of the chain, so we need to re-link things. 9378 SDValue InputChain = Node->getOperand(0); 9379 SDValue OutputChain = SDValue(Node, 1); 9380 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9381 9382 SmallVector<SDValue, 3> Ops; 9383 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9384 Ops.push_back(Node->getOperand(i)); 9385 9386 SDVTList VTs = getVTList(Node->getValueType(0)); 9387 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9388 9389 // MorphNodeTo can operate in two ways: if an existing node with the 9390 // specified operands exists, it can just return it. Otherwise, it 9391 // updates the node in place to have the requested operands. 9392 if (Res == Node) { 9393 // If we updated the node in place, reset the node ID. To the isel, 9394 // this should be just like a newly allocated machine node. 9395 Res->setNodeId(-1); 9396 } else { 9397 ReplaceAllUsesWith(Node, Res); 9398 RemoveDeadNode(Node); 9399 } 9400 9401 return Res; 9402 } 9403 9404 /// getMachineNode - These are used for target selectors to create a new node 9405 /// with specified return type(s), MachineInstr opcode, and operands. 9406 /// 9407 /// Note that getMachineNode returns the resultant node. If there is already a 9408 /// node of the specified opcode and operands, it returns that node instead of 9409 /// the current one. 9410 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9411 EVT VT) { 9412 SDVTList VTs = getVTList(VT); 9413 return getMachineNode(Opcode, dl, VTs, None); 9414 } 9415 9416 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9417 EVT VT, SDValue Op1) { 9418 SDVTList VTs = getVTList(VT); 9419 SDValue Ops[] = { Op1 }; 9420 return getMachineNode(Opcode, dl, VTs, Ops); 9421 } 9422 9423 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9424 EVT VT, SDValue Op1, SDValue Op2) { 9425 SDVTList VTs = getVTList(VT); 9426 SDValue Ops[] = { Op1, Op2 }; 9427 return getMachineNode(Opcode, dl, VTs, Ops); 9428 } 9429 9430 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9431 EVT VT, SDValue Op1, SDValue Op2, 9432 SDValue Op3) { 9433 SDVTList VTs = getVTList(VT); 9434 SDValue Ops[] = { Op1, Op2, Op3 }; 9435 return getMachineNode(Opcode, dl, VTs, Ops); 9436 } 9437 9438 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9439 EVT VT, ArrayRef<SDValue> Ops) { 9440 SDVTList VTs = getVTList(VT); 9441 return getMachineNode(Opcode, dl, VTs, Ops); 9442 } 9443 9444 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9445 EVT VT1, EVT VT2, SDValue Op1, 9446 SDValue Op2) { 9447 SDVTList VTs = getVTList(VT1, VT2); 9448 SDValue Ops[] = { Op1, Op2 }; 9449 return getMachineNode(Opcode, dl, VTs, Ops); 9450 } 9451 9452 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9453 EVT VT1, EVT VT2, SDValue Op1, 9454 SDValue Op2, SDValue Op3) { 9455 SDVTList VTs = getVTList(VT1, VT2); 9456 SDValue Ops[] = { Op1, Op2, Op3 }; 9457 return getMachineNode(Opcode, dl, VTs, Ops); 9458 } 9459 9460 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9461 EVT VT1, EVT VT2, 9462 ArrayRef<SDValue> Ops) { 9463 SDVTList VTs = getVTList(VT1, VT2); 9464 return getMachineNode(Opcode, dl, VTs, Ops); 9465 } 9466 9467 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9468 EVT VT1, EVT VT2, EVT VT3, 9469 SDValue Op1, SDValue Op2) { 9470 SDVTList VTs = getVTList(VT1, VT2, VT3); 9471 SDValue Ops[] = { Op1, Op2 }; 9472 return getMachineNode(Opcode, dl, VTs, Ops); 9473 } 9474 9475 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9476 EVT VT1, EVT VT2, EVT VT3, 9477 SDValue Op1, SDValue Op2, 9478 SDValue Op3) { 9479 SDVTList VTs = getVTList(VT1, VT2, VT3); 9480 SDValue Ops[] = { Op1, Op2, Op3 }; 9481 return getMachineNode(Opcode, dl, VTs, Ops); 9482 } 9483 9484 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9485 EVT VT1, EVT VT2, EVT VT3, 9486 ArrayRef<SDValue> Ops) { 9487 SDVTList VTs = getVTList(VT1, VT2, VT3); 9488 return getMachineNode(Opcode, dl, VTs, Ops); 9489 } 9490 9491 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9492 ArrayRef<EVT> ResultTys, 9493 ArrayRef<SDValue> Ops) { 9494 SDVTList VTs = getVTList(ResultTys); 9495 return getMachineNode(Opcode, dl, VTs, Ops); 9496 } 9497 9498 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9499 SDVTList VTs, 9500 ArrayRef<SDValue> Ops) { 9501 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9502 MachineSDNode *N; 9503 void *IP = nullptr; 9504 9505 if (DoCSE) { 9506 FoldingSetNodeID ID; 9507 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9508 IP = nullptr; 9509 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9510 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9511 } 9512 } 9513 9514 // Allocate a new MachineSDNode. 9515 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9516 createOperands(N, Ops); 9517 9518 if (DoCSE) 9519 CSEMap.InsertNode(N, IP); 9520 9521 InsertNode(N); 9522 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9523 return N; 9524 } 9525 9526 /// getTargetExtractSubreg - A convenience function for creating 9527 /// TargetOpcode::EXTRACT_SUBREG nodes. 9528 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9529 SDValue Operand) { 9530 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9531 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9532 VT, Operand, SRIdxVal); 9533 return SDValue(Subreg, 0); 9534 } 9535 9536 /// getTargetInsertSubreg - A convenience function for creating 9537 /// TargetOpcode::INSERT_SUBREG nodes. 9538 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9539 SDValue Operand, SDValue Subreg) { 9540 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9541 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9542 VT, Operand, Subreg, SRIdxVal); 9543 return SDValue(Result, 0); 9544 } 9545 9546 /// getNodeIfExists - Get the specified node if it's already available, or 9547 /// else return NULL. 9548 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9549 ArrayRef<SDValue> Ops) { 9550 SDNodeFlags Flags; 9551 if (Inserter) 9552 Flags = Inserter->getFlags(); 9553 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9554 } 9555 9556 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9557 ArrayRef<SDValue> Ops, 9558 const SDNodeFlags Flags) { 9559 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9560 FoldingSetNodeID ID; 9561 AddNodeIDNode(ID, Opcode, VTList, Ops); 9562 void *IP = nullptr; 9563 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9564 E->intersectFlagsWith(Flags); 9565 return E; 9566 } 9567 } 9568 return nullptr; 9569 } 9570 9571 /// doesNodeExist - Check if a node exists without modifying its flags. 9572 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9573 ArrayRef<SDValue> Ops) { 9574 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9575 FoldingSetNodeID ID; 9576 AddNodeIDNode(ID, Opcode, VTList, Ops); 9577 void *IP = nullptr; 9578 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9579 return true; 9580 } 9581 return false; 9582 } 9583 9584 /// getDbgValue - Creates a SDDbgValue node. 9585 /// 9586 /// SDNode 9587 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9588 SDNode *N, unsigned R, bool IsIndirect, 9589 const DebugLoc &DL, unsigned O) { 9590 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9591 "Expected inlined-at fields to agree"); 9592 return new (DbgInfo->getAlloc()) 9593 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9594 {}, IsIndirect, DL, O, 9595 /*IsVariadic=*/false); 9596 } 9597 9598 /// Constant 9599 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9600 DIExpression *Expr, 9601 const Value *C, 9602 const DebugLoc &DL, unsigned O) { 9603 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9604 "Expected inlined-at fields to agree"); 9605 return new (DbgInfo->getAlloc()) 9606 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9607 /*IsIndirect=*/false, DL, O, 9608 /*IsVariadic=*/false); 9609 } 9610 9611 /// FrameIndex 9612 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9613 DIExpression *Expr, unsigned FI, 9614 bool IsIndirect, 9615 const DebugLoc &DL, 9616 unsigned O) { 9617 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9618 "Expected inlined-at fields to agree"); 9619 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9620 } 9621 9622 /// FrameIndex with dependencies 9623 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9624 DIExpression *Expr, unsigned FI, 9625 ArrayRef<SDNode *> Dependencies, 9626 bool IsIndirect, 9627 const DebugLoc &DL, 9628 unsigned O) { 9629 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9630 "Expected inlined-at fields to agree"); 9631 return new (DbgInfo->getAlloc()) 9632 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9633 Dependencies, IsIndirect, DL, O, 9634 /*IsVariadic=*/false); 9635 } 9636 9637 /// VReg 9638 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9639 unsigned VReg, bool IsIndirect, 9640 const DebugLoc &DL, unsigned O) { 9641 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9642 "Expected inlined-at fields to agree"); 9643 return new (DbgInfo->getAlloc()) 9644 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9645 {}, IsIndirect, DL, O, 9646 /*IsVariadic=*/false); 9647 } 9648 9649 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9650 ArrayRef<SDDbgOperand> Locs, 9651 ArrayRef<SDNode *> Dependencies, 9652 bool IsIndirect, const DebugLoc &DL, 9653 unsigned O, bool IsVariadic) { 9654 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9655 "Expected inlined-at fields to agree"); 9656 return new (DbgInfo->getAlloc()) 9657 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9658 DL, O, IsVariadic); 9659 } 9660 9661 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9662 unsigned OffsetInBits, unsigned SizeInBits, 9663 bool InvalidateDbg) { 9664 SDNode *FromNode = From.getNode(); 9665 SDNode *ToNode = To.getNode(); 9666 assert(FromNode && ToNode && "Can't modify dbg values"); 9667 9668 // PR35338 9669 // TODO: assert(From != To && "Redundant dbg value transfer"); 9670 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9671 if (From == To || FromNode == ToNode) 9672 return; 9673 9674 if (!FromNode->getHasDebugValue()) 9675 return; 9676 9677 SDDbgOperand FromLocOp = 9678 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9679 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9680 9681 SmallVector<SDDbgValue *, 2> ClonedDVs; 9682 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9683 if (Dbg->isInvalidated()) 9684 continue; 9685 9686 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9687 9688 // Create a new location ops vector that is equal to the old vector, but 9689 // with each instance of FromLocOp replaced with ToLocOp. 9690 bool Changed = false; 9691 auto NewLocOps = Dbg->copyLocationOps(); 9692 std::replace_if( 9693 NewLocOps.begin(), NewLocOps.end(), 9694 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9695 bool Match = Op == FromLocOp; 9696 Changed |= Match; 9697 return Match; 9698 }, 9699 ToLocOp); 9700 // Ignore this SDDbgValue if we didn't find a matching location. 9701 if (!Changed) 9702 continue; 9703 9704 DIVariable *Var = Dbg->getVariable(); 9705 auto *Expr = Dbg->getExpression(); 9706 // If a fragment is requested, update the expression. 9707 if (SizeInBits) { 9708 // When splitting a larger (e.g., sign-extended) value whose 9709 // lower bits are described with an SDDbgValue, do not attempt 9710 // to transfer the SDDbgValue to the upper bits. 9711 if (auto FI = Expr->getFragmentInfo()) 9712 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9713 continue; 9714 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9715 SizeInBits); 9716 if (!Fragment) 9717 continue; 9718 Expr = *Fragment; 9719 } 9720 9721 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9722 // Clone the SDDbgValue and move it to To. 9723 SDDbgValue *Clone = getDbgValueList( 9724 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9725 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9726 Dbg->isVariadic()); 9727 ClonedDVs.push_back(Clone); 9728 9729 if (InvalidateDbg) { 9730 // Invalidate value and indicate the SDDbgValue should not be emitted. 9731 Dbg->setIsInvalidated(); 9732 Dbg->setIsEmitted(); 9733 } 9734 } 9735 9736 for (SDDbgValue *Dbg : ClonedDVs) { 9737 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9738 "Transferred DbgValues should depend on the new SDNode"); 9739 AddDbgValue(Dbg, false); 9740 } 9741 } 9742 9743 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9744 if (!N.getHasDebugValue()) 9745 return; 9746 9747 SmallVector<SDDbgValue *, 2> ClonedDVs; 9748 for (auto DV : GetDbgValues(&N)) { 9749 if (DV->isInvalidated()) 9750 continue; 9751 switch (N.getOpcode()) { 9752 default: 9753 break; 9754 case ISD::ADD: 9755 SDValue N0 = N.getOperand(0); 9756 SDValue N1 = N.getOperand(1); 9757 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9758 isConstantIntBuildVectorOrConstantInt(N1)) { 9759 uint64_t Offset = N.getConstantOperandVal(1); 9760 9761 // Rewrite an ADD constant node into a DIExpression. Since we are 9762 // performing arithmetic to compute the variable's *value* in the 9763 // DIExpression, we need to mark the expression with a 9764 // DW_OP_stack_value. 9765 auto *DIExpr = DV->getExpression(); 9766 auto NewLocOps = DV->copyLocationOps(); 9767 bool Changed = false; 9768 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9769 // We're not given a ResNo to compare against because the whole 9770 // node is going away. We know that any ISD::ADD only has one 9771 // result, so we can assume any node match is using the result. 9772 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9773 NewLocOps[i].getSDNode() != &N) 9774 continue; 9775 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9776 SmallVector<uint64_t, 3> ExprOps; 9777 DIExpression::appendOffset(ExprOps, Offset); 9778 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9779 Changed = true; 9780 } 9781 (void)Changed; 9782 assert(Changed && "Salvage target doesn't use N"); 9783 9784 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9785 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9786 NewLocOps, AdditionalDependencies, 9787 DV->isIndirect(), DV->getDebugLoc(), 9788 DV->getOrder(), DV->isVariadic()); 9789 ClonedDVs.push_back(Clone); 9790 DV->setIsInvalidated(); 9791 DV->setIsEmitted(); 9792 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9793 N0.getNode()->dumprFull(this); 9794 dbgs() << " into " << *DIExpr << '\n'); 9795 } 9796 } 9797 } 9798 9799 for (SDDbgValue *Dbg : ClonedDVs) { 9800 assert(!Dbg->getSDNodes().empty() && 9801 "Salvaged DbgValue should depend on a new SDNode"); 9802 AddDbgValue(Dbg, false); 9803 } 9804 } 9805 9806 /// Creates a SDDbgLabel node. 9807 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9808 const DebugLoc &DL, unsigned O) { 9809 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9810 "Expected inlined-at fields to agree"); 9811 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9812 } 9813 9814 namespace { 9815 9816 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9817 /// pointed to by a use iterator is deleted, increment the use iterator 9818 /// so that it doesn't dangle. 9819 /// 9820 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9821 SDNode::use_iterator &UI; 9822 SDNode::use_iterator &UE; 9823 9824 void NodeDeleted(SDNode *N, SDNode *E) override { 9825 // Increment the iterator as needed. 9826 while (UI != UE && N == *UI) 9827 ++UI; 9828 } 9829 9830 public: 9831 RAUWUpdateListener(SelectionDAG &d, 9832 SDNode::use_iterator &ui, 9833 SDNode::use_iterator &ue) 9834 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9835 }; 9836 9837 } // end anonymous namespace 9838 9839 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9840 /// This can cause recursive merging of nodes in the DAG. 9841 /// 9842 /// This version assumes From has a single result value. 9843 /// 9844 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9845 SDNode *From = FromN.getNode(); 9846 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9847 "Cannot replace with this method!"); 9848 assert(From != To.getNode() && "Cannot replace uses of with self"); 9849 9850 // Preserve Debug Values 9851 transferDbgValues(FromN, To); 9852 9853 // Iterate over all the existing uses of From. New uses will be added 9854 // to the beginning of the use list, which we avoid visiting. 9855 // This specifically avoids visiting uses of From that arise while the 9856 // replacement is happening, because any such uses would be the result 9857 // of CSE: If an existing node looks like From after one of its operands 9858 // is replaced by To, we don't want to replace of all its users with To 9859 // too. See PR3018 for more info. 9860 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9861 RAUWUpdateListener Listener(*this, UI, UE); 9862 while (UI != UE) { 9863 SDNode *User = *UI; 9864 9865 // This node is about to morph, remove its old self from the CSE maps. 9866 RemoveNodeFromCSEMaps(User); 9867 9868 // A user can appear in a use list multiple times, and when this 9869 // happens the uses are usually next to each other in the list. 9870 // To help reduce the number of CSE recomputations, process all 9871 // the uses of this user that we can find this way. 9872 do { 9873 SDUse &Use = UI.getUse(); 9874 ++UI; 9875 Use.set(To); 9876 if (To->isDivergent() != From->isDivergent()) 9877 updateDivergence(User); 9878 } while (UI != UE && *UI == User); 9879 // Now that we have modified User, add it back to the CSE maps. If it 9880 // already exists there, recursively merge the results together. 9881 AddModifiedNodeToCSEMaps(User); 9882 } 9883 9884 // If we just RAUW'd the root, take note. 9885 if (FromN == getRoot()) 9886 setRoot(To); 9887 } 9888 9889 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9890 /// This can cause recursive merging of nodes in the DAG. 9891 /// 9892 /// This version assumes that for each value of From, there is a 9893 /// corresponding value in To in the same position with the same type. 9894 /// 9895 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9896 #ifndef NDEBUG 9897 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9898 assert((!From->hasAnyUseOfValue(i) || 9899 From->getValueType(i) == To->getValueType(i)) && 9900 "Cannot use this version of ReplaceAllUsesWith!"); 9901 #endif 9902 9903 // Handle the trivial case. 9904 if (From == To) 9905 return; 9906 9907 // Preserve Debug Info. Only do this if there's a use. 9908 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9909 if (From->hasAnyUseOfValue(i)) { 9910 assert((i < To->getNumValues()) && "Invalid To location"); 9911 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9912 } 9913 9914 // Iterate over just the existing users of From. See the comments in 9915 // the ReplaceAllUsesWith above. 9916 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9917 RAUWUpdateListener Listener(*this, UI, UE); 9918 while (UI != UE) { 9919 SDNode *User = *UI; 9920 9921 // This node is about to morph, remove its old self from the CSE maps. 9922 RemoveNodeFromCSEMaps(User); 9923 9924 // A user can appear in a use list multiple times, and when this 9925 // happens the uses are usually next to each other in the list. 9926 // To help reduce the number of CSE recomputations, process all 9927 // the uses of this user that we can find this way. 9928 do { 9929 SDUse &Use = UI.getUse(); 9930 ++UI; 9931 Use.setNode(To); 9932 if (To->isDivergent() != From->isDivergent()) 9933 updateDivergence(User); 9934 } while (UI != UE && *UI == User); 9935 9936 // Now that we have modified User, add it back to the CSE maps. If it 9937 // already exists there, recursively merge the results together. 9938 AddModifiedNodeToCSEMaps(User); 9939 } 9940 9941 // If we just RAUW'd the root, take note. 9942 if (From == getRoot().getNode()) 9943 setRoot(SDValue(To, getRoot().getResNo())); 9944 } 9945 9946 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9947 /// This can cause recursive merging of nodes in the DAG. 9948 /// 9949 /// This version can replace From with any result values. To must match the 9950 /// number and types of values returned by From. 9951 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9952 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9953 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9954 9955 // Preserve Debug Info. 9956 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9957 transferDbgValues(SDValue(From, i), To[i]); 9958 9959 // Iterate over just the existing users of From. See the comments in 9960 // the ReplaceAllUsesWith above. 9961 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9962 RAUWUpdateListener Listener(*this, UI, UE); 9963 while (UI != UE) { 9964 SDNode *User = *UI; 9965 9966 // This node is about to morph, remove its old self from the CSE maps. 9967 RemoveNodeFromCSEMaps(User); 9968 9969 // A user can appear in a use list multiple times, and when this happens the 9970 // uses are usually next to each other in the list. To help reduce the 9971 // number of CSE and divergence recomputations, process all the uses of this 9972 // user that we can find this way. 9973 bool To_IsDivergent = false; 9974 do { 9975 SDUse &Use = UI.getUse(); 9976 const SDValue &ToOp = To[Use.getResNo()]; 9977 ++UI; 9978 Use.set(ToOp); 9979 To_IsDivergent |= ToOp->isDivergent(); 9980 } while (UI != UE && *UI == User); 9981 9982 if (To_IsDivergent != From->isDivergent()) 9983 updateDivergence(User); 9984 9985 // Now that we have modified User, add it back to the CSE maps. If it 9986 // already exists there, recursively merge the results together. 9987 AddModifiedNodeToCSEMaps(User); 9988 } 9989 9990 // If we just RAUW'd the root, take note. 9991 if (From == getRoot().getNode()) 9992 setRoot(SDValue(To[getRoot().getResNo()])); 9993 } 9994 9995 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 9996 /// uses of other values produced by From.getNode() alone. The Deleted 9997 /// vector is handled the same way as for ReplaceAllUsesWith. 9998 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 9999 // Handle the really simple, really trivial case efficiently. 10000 if (From == To) return; 10001 10002 // Handle the simple, trivial, case efficiently. 10003 if (From.getNode()->getNumValues() == 1) { 10004 ReplaceAllUsesWith(From, To); 10005 return; 10006 } 10007 10008 // Preserve Debug Info. 10009 transferDbgValues(From, To); 10010 10011 // Iterate over just the existing users of From. See the comments in 10012 // the ReplaceAllUsesWith above. 10013 SDNode::use_iterator UI = From.getNode()->use_begin(), 10014 UE = From.getNode()->use_end(); 10015 RAUWUpdateListener Listener(*this, UI, UE); 10016 while (UI != UE) { 10017 SDNode *User = *UI; 10018 bool UserRemovedFromCSEMaps = false; 10019 10020 // A user can appear in a use list multiple times, and when this 10021 // happens the uses are usually next to each other in the list. 10022 // To help reduce the number of CSE recomputations, process all 10023 // the uses of this user that we can find this way. 10024 do { 10025 SDUse &Use = UI.getUse(); 10026 10027 // Skip uses of different values from the same node. 10028 if (Use.getResNo() != From.getResNo()) { 10029 ++UI; 10030 continue; 10031 } 10032 10033 // If this node hasn't been modified yet, it's still in the CSE maps, 10034 // so remove its old self from the CSE maps. 10035 if (!UserRemovedFromCSEMaps) { 10036 RemoveNodeFromCSEMaps(User); 10037 UserRemovedFromCSEMaps = true; 10038 } 10039 10040 ++UI; 10041 Use.set(To); 10042 if (To->isDivergent() != From->isDivergent()) 10043 updateDivergence(User); 10044 } while (UI != UE && *UI == User); 10045 // We are iterating over all uses of the From node, so if a use 10046 // doesn't use the specific value, no changes are made. 10047 if (!UserRemovedFromCSEMaps) 10048 continue; 10049 10050 // Now that we have modified User, add it back to the CSE maps. If it 10051 // already exists there, recursively merge the results together. 10052 AddModifiedNodeToCSEMaps(User); 10053 } 10054 10055 // If we just RAUW'd the root, take note. 10056 if (From == getRoot()) 10057 setRoot(To); 10058 } 10059 10060 namespace { 10061 10062 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10063 /// to record information about a use. 10064 struct UseMemo { 10065 SDNode *User; 10066 unsigned Index; 10067 SDUse *Use; 10068 }; 10069 10070 /// operator< - Sort Memos by User. 10071 bool operator<(const UseMemo &L, const UseMemo &R) { 10072 return (intptr_t)L.User < (intptr_t)R.User; 10073 } 10074 10075 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10076 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10077 /// the node already has been taken care of recursively. 10078 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10079 SmallVector<UseMemo, 4> &Uses; 10080 10081 void NodeDeleted(SDNode *N, SDNode *E) override { 10082 for (UseMemo &Memo : Uses) 10083 if (Memo.User == N) 10084 Memo.User = nullptr; 10085 } 10086 10087 public: 10088 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10089 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10090 }; 10091 10092 } // end anonymous namespace 10093 10094 bool SelectionDAG::calculateDivergence(SDNode *N) { 10095 if (TLI->isSDNodeAlwaysUniform(N)) { 10096 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 10097 "Conflicting divergence information!"); 10098 return false; 10099 } 10100 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 10101 return true; 10102 for (auto &Op : N->ops()) { 10103 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10104 return true; 10105 } 10106 return false; 10107 } 10108 10109 void SelectionDAG::updateDivergence(SDNode *N) { 10110 SmallVector<SDNode *, 16> Worklist(1, N); 10111 do { 10112 N = Worklist.pop_back_val(); 10113 bool IsDivergent = calculateDivergence(N); 10114 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10115 N->SDNodeBits.IsDivergent = IsDivergent; 10116 llvm::append_range(Worklist, N->uses()); 10117 } 10118 } while (!Worklist.empty()); 10119 } 10120 10121 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10122 DenseMap<SDNode *, unsigned> Degree; 10123 Order.reserve(AllNodes.size()); 10124 for (auto &N : allnodes()) { 10125 unsigned NOps = N.getNumOperands(); 10126 Degree[&N] = NOps; 10127 if (0 == NOps) 10128 Order.push_back(&N); 10129 } 10130 for (size_t I = 0; I != Order.size(); ++I) { 10131 SDNode *N = Order[I]; 10132 for (auto U : N->uses()) { 10133 unsigned &UnsortedOps = Degree[U]; 10134 if (0 == --UnsortedOps) 10135 Order.push_back(U); 10136 } 10137 } 10138 } 10139 10140 #ifndef NDEBUG 10141 void SelectionDAG::VerifyDAGDivergence() { 10142 std::vector<SDNode *> TopoOrder; 10143 CreateTopologicalOrder(TopoOrder); 10144 for (auto *N : TopoOrder) { 10145 assert(calculateDivergence(N) == N->isDivergent() && 10146 "Divergence bit inconsistency detected"); 10147 } 10148 } 10149 #endif 10150 10151 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10152 /// uses of other values produced by From.getNode() alone. The same value 10153 /// may appear in both the From and To list. The Deleted vector is 10154 /// handled the same way as for ReplaceAllUsesWith. 10155 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10156 const SDValue *To, 10157 unsigned Num){ 10158 // Handle the simple, trivial case efficiently. 10159 if (Num == 1) 10160 return ReplaceAllUsesOfValueWith(*From, *To); 10161 10162 transferDbgValues(*From, *To); 10163 10164 // Read up all the uses and make records of them. This helps 10165 // processing new uses that are introduced during the 10166 // replacement process. 10167 SmallVector<UseMemo, 4> Uses; 10168 for (unsigned i = 0; i != Num; ++i) { 10169 unsigned FromResNo = From[i].getResNo(); 10170 SDNode *FromNode = From[i].getNode(); 10171 for (SDNode::use_iterator UI = FromNode->use_begin(), 10172 E = FromNode->use_end(); UI != E; ++UI) { 10173 SDUse &Use = UI.getUse(); 10174 if (Use.getResNo() == FromResNo) { 10175 UseMemo Memo = { *UI, i, &Use }; 10176 Uses.push_back(Memo); 10177 } 10178 } 10179 } 10180 10181 // Sort the uses, so that all the uses from a given User are together. 10182 llvm::sort(Uses); 10183 RAUOVWUpdateListener Listener(*this, Uses); 10184 10185 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 10186 UseIndex != UseIndexEnd; ) { 10187 // We know that this user uses some value of From. If it is the right 10188 // value, update it. 10189 SDNode *User = Uses[UseIndex].User; 10190 // If the node has been deleted by recursive CSE updates when updating 10191 // another node, then just skip this entry. 10192 if (User == nullptr) { 10193 ++UseIndex; 10194 continue; 10195 } 10196 10197 // This node is about to morph, remove its old self from the CSE maps. 10198 RemoveNodeFromCSEMaps(User); 10199 10200 // The Uses array is sorted, so all the uses for a given User 10201 // are next to each other in the list. 10202 // To help reduce the number of CSE recomputations, process all 10203 // the uses of this user that we can find this way. 10204 do { 10205 unsigned i = Uses[UseIndex].Index; 10206 SDUse &Use = *Uses[UseIndex].Use; 10207 ++UseIndex; 10208 10209 Use.set(To[i]); 10210 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 10211 10212 // Now that we have modified User, add it back to the CSE maps. If it 10213 // already exists there, recursively merge the results together. 10214 AddModifiedNodeToCSEMaps(User); 10215 } 10216 } 10217 10218 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 10219 /// based on their topological order. It returns the maximum id and a vector 10220 /// of the SDNodes* in assigned order by reference. 10221 unsigned SelectionDAG::AssignTopologicalOrder() { 10222 unsigned DAGSize = 0; 10223 10224 // SortedPos tracks the progress of the algorithm. Nodes before it are 10225 // sorted, nodes after it are unsorted. When the algorithm completes 10226 // it is at the end of the list. 10227 allnodes_iterator SortedPos = allnodes_begin(); 10228 10229 // Visit all the nodes. Move nodes with no operands to the front of 10230 // the list immediately. Annotate nodes that do have operands with their 10231 // operand count. Before we do this, the Node Id fields of the nodes 10232 // may contain arbitrary values. After, the Node Id fields for nodes 10233 // before SortedPos will contain the topological sort index, and the 10234 // Node Id fields for nodes At SortedPos and after will contain the 10235 // count of outstanding operands. 10236 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 10237 checkForCycles(&N, this); 10238 unsigned Degree = N.getNumOperands(); 10239 if (Degree == 0) { 10240 // A node with no uses, add it to the result array immediately. 10241 N.setNodeId(DAGSize++); 10242 allnodes_iterator Q(&N); 10243 if (Q != SortedPos) 10244 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 10245 assert(SortedPos != AllNodes.end() && "Overran node list"); 10246 ++SortedPos; 10247 } else { 10248 // Temporarily use the Node Id as scratch space for the degree count. 10249 N.setNodeId(Degree); 10250 } 10251 } 10252 10253 // Visit all the nodes. As we iterate, move nodes into sorted order, 10254 // such that by the time the end is reached all nodes will be sorted. 10255 for (SDNode &Node : allnodes()) { 10256 SDNode *N = &Node; 10257 checkForCycles(N, this); 10258 // N is in sorted position, so all its uses have one less operand 10259 // that needs to be sorted. 10260 for (SDNode *P : N->uses()) { 10261 unsigned Degree = P->getNodeId(); 10262 assert(Degree != 0 && "Invalid node degree"); 10263 --Degree; 10264 if (Degree == 0) { 10265 // All of P's operands are sorted, so P may sorted now. 10266 P->setNodeId(DAGSize++); 10267 if (P->getIterator() != SortedPos) 10268 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 10269 assert(SortedPos != AllNodes.end() && "Overran node list"); 10270 ++SortedPos; 10271 } else { 10272 // Update P's outstanding operand count. 10273 P->setNodeId(Degree); 10274 } 10275 } 10276 if (Node.getIterator() == SortedPos) { 10277 #ifndef NDEBUG 10278 allnodes_iterator I(N); 10279 SDNode *S = &*++I; 10280 dbgs() << "Overran sorted position:\n"; 10281 S->dumprFull(this); dbgs() << "\n"; 10282 dbgs() << "Checking if this is due to cycles\n"; 10283 checkForCycles(this, true); 10284 #endif 10285 llvm_unreachable(nullptr); 10286 } 10287 } 10288 10289 assert(SortedPos == AllNodes.end() && 10290 "Topological sort incomplete!"); 10291 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 10292 "First node in topological sort is not the entry token!"); 10293 assert(AllNodes.front().getNodeId() == 0 && 10294 "First node in topological sort has non-zero id!"); 10295 assert(AllNodes.front().getNumOperands() == 0 && 10296 "First node in topological sort has operands!"); 10297 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 10298 "Last node in topologic sort has unexpected id!"); 10299 assert(AllNodes.back().use_empty() && 10300 "Last node in topologic sort has users!"); 10301 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 10302 return DAGSize; 10303 } 10304 10305 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 10306 /// value is produced by SD. 10307 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 10308 for (SDNode *SD : DB->getSDNodes()) { 10309 if (!SD) 10310 continue; 10311 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 10312 SD->setHasDebugValue(true); 10313 } 10314 DbgInfo->add(DB, isParameter); 10315 } 10316 10317 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 10318 10319 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 10320 SDValue NewMemOpChain) { 10321 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 10322 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 10323 // The new memory operation must have the same position as the old load in 10324 // terms of memory dependency. Create a TokenFactor for the old load and new 10325 // memory operation and update uses of the old load's output chain to use that 10326 // TokenFactor. 10327 if (OldChain == NewMemOpChain || OldChain.use_empty()) 10328 return NewMemOpChain; 10329 10330 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 10331 OldChain, NewMemOpChain); 10332 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 10333 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 10334 return TokenFactor; 10335 } 10336 10337 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 10338 SDValue NewMemOp) { 10339 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 10340 SDValue OldChain = SDValue(OldLoad, 1); 10341 SDValue NewMemOpChain = NewMemOp.getValue(1); 10342 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 10343 } 10344 10345 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 10346 Function **OutFunction) { 10347 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 10348 10349 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 10350 auto *Module = MF->getFunction().getParent(); 10351 auto *Function = Module->getFunction(Symbol); 10352 10353 if (OutFunction != nullptr) 10354 *OutFunction = Function; 10355 10356 if (Function != nullptr) { 10357 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 10358 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 10359 } 10360 10361 std::string ErrorStr; 10362 raw_string_ostream ErrorFormatter(ErrorStr); 10363 ErrorFormatter << "Undefined external symbol "; 10364 ErrorFormatter << '"' << Symbol << '"'; 10365 report_fatal_error(Twine(ErrorFormatter.str())); 10366 } 10367 10368 //===----------------------------------------------------------------------===// 10369 // SDNode Class 10370 //===----------------------------------------------------------------------===// 10371 10372 bool llvm::isNullConstant(SDValue V) { 10373 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10374 return Const != nullptr && Const->isZero(); 10375 } 10376 10377 bool llvm::isNullFPConstant(SDValue V) { 10378 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10379 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10380 } 10381 10382 bool llvm::isAllOnesConstant(SDValue V) { 10383 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10384 return Const != nullptr && Const->isAllOnes(); 10385 } 10386 10387 bool llvm::isOneConstant(SDValue V) { 10388 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10389 return Const != nullptr && Const->isOne(); 10390 } 10391 10392 SDValue llvm::peekThroughBitcasts(SDValue V) { 10393 while (V.getOpcode() == ISD::BITCAST) 10394 V = V.getOperand(0); 10395 return V; 10396 } 10397 10398 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10399 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10400 V = V.getOperand(0); 10401 return V; 10402 } 10403 10404 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10405 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10406 V = V.getOperand(0); 10407 return V; 10408 } 10409 10410 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10411 if (V.getOpcode() != ISD::XOR) 10412 return false; 10413 V = peekThroughBitcasts(V.getOperand(1)); 10414 unsigned NumBits = V.getScalarValueSizeInBits(); 10415 ConstantSDNode *C = 10416 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10417 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10418 } 10419 10420 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10421 bool AllowTruncation) { 10422 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10423 return CN; 10424 10425 // SplatVectors can truncate their operands. Ignore that case here unless 10426 // AllowTruncation is set. 10427 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10428 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10429 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10430 EVT CVT = CN->getValueType(0); 10431 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10432 if (AllowTruncation || CVT == VecEltVT) 10433 return CN; 10434 } 10435 } 10436 10437 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10438 BitVector UndefElements; 10439 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10440 10441 // BuildVectors can truncate their operands. Ignore that case here unless 10442 // AllowTruncation is set. 10443 if (CN && (UndefElements.none() || AllowUndefs)) { 10444 EVT CVT = CN->getValueType(0); 10445 EVT NSVT = N.getValueType().getScalarType(); 10446 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10447 if (AllowTruncation || (CVT == NSVT)) 10448 return CN; 10449 } 10450 } 10451 10452 return nullptr; 10453 } 10454 10455 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10456 bool AllowUndefs, 10457 bool AllowTruncation) { 10458 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10459 return CN; 10460 10461 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10462 BitVector UndefElements; 10463 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10464 10465 // BuildVectors can truncate their operands. Ignore that case here unless 10466 // AllowTruncation is set. 10467 if (CN && (UndefElements.none() || AllowUndefs)) { 10468 EVT CVT = CN->getValueType(0); 10469 EVT NSVT = N.getValueType().getScalarType(); 10470 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10471 if (AllowTruncation || (CVT == NSVT)) 10472 return CN; 10473 } 10474 } 10475 10476 return nullptr; 10477 } 10478 10479 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10480 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10481 return CN; 10482 10483 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10484 BitVector UndefElements; 10485 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10486 if (CN && (UndefElements.none() || AllowUndefs)) 10487 return CN; 10488 } 10489 10490 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10491 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10492 return CN; 10493 10494 return nullptr; 10495 } 10496 10497 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10498 const APInt &DemandedElts, 10499 bool AllowUndefs) { 10500 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10501 return CN; 10502 10503 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10504 BitVector UndefElements; 10505 ConstantFPSDNode *CN = 10506 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10507 if (CN && (UndefElements.none() || AllowUndefs)) 10508 return CN; 10509 } 10510 10511 return nullptr; 10512 } 10513 10514 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10515 // TODO: may want to use peekThroughBitcast() here. 10516 ConstantSDNode *C = 10517 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10518 return C && C->isZero(); 10519 } 10520 10521 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10522 // TODO: may want to use peekThroughBitcast() here. 10523 unsigned BitWidth = N.getScalarValueSizeInBits(); 10524 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10525 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10526 } 10527 10528 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10529 N = peekThroughBitcasts(N); 10530 unsigned BitWidth = N.getScalarValueSizeInBits(); 10531 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10532 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10533 } 10534 10535 HandleSDNode::~HandleSDNode() { 10536 DropOperands(); 10537 } 10538 10539 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10540 const DebugLoc &DL, 10541 const GlobalValue *GA, EVT VT, 10542 int64_t o, unsigned TF) 10543 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10544 TheGlobal = GA; 10545 } 10546 10547 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10548 EVT VT, unsigned SrcAS, 10549 unsigned DestAS) 10550 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10551 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10552 10553 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10554 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10555 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10556 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10557 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10558 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10559 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10560 10561 // We check here that the size of the memory operand fits within the size of 10562 // the MMO. This is because the MMO might indicate only a possible address 10563 // range instead of specifying the affected memory addresses precisely. 10564 // TODO: Make MachineMemOperands aware of scalable vectors. 10565 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10566 "Size mismatch!"); 10567 } 10568 10569 /// Profile - Gather unique data for the node. 10570 /// 10571 void SDNode::Profile(FoldingSetNodeID &ID) const { 10572 AddNodeIDNode(ID, this); 10573 } 10574 10575 namespace { 10576 10577 struct EVTArray { 10578 std::vector<EVT> VTs; 10579 10580 EVTArray() { 10581 VTs.reserve(MVT::VALUETYPE_SIZE); 10582 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10583 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10584 } 10585 }; 10586 10587 } // end anonymous namespace 10588 10589 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10590 static ManagedStatic<EVTArray> SimpleVTArray; 10591 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10592 10593 /// getValueTypeList - Return a pointer to the specified value type. 10594 /// 10595 const EVT *SDNode::getValueTypeList(EVT VT) { 10596 if (VT.isExtended()) { 10597 sys::SmartScopedLock<true> Lock(*VTMutex); 10598 return &(*EVTs->insert(VT).first); 10599 } 10600 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10601 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10602 } 10603 10604 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10605 /// indicated value. This method ignores uses of other values defined by this 10606 /// operation. 10607 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10608 assert(Value < getNumValues() && "Bad value!"); 10609 10610 // TODO: Only iterate over uses of a given value of the node 10611 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10612 if (UI.getUse().getResNo() == Value) { 10613 if (NUses == 0) 10614 return false; 10615 --NUses; 10616 } 10617 } 10618 10619 // Found exactly the right number of uses? 10620 return NUses == 0; 10621 } 10622 10623 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10624 /// value. This method ignores uses of other values defined by this operation. 10625 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10626 assert(Value < getNumValues() && "Bad value!"); 10627 10628 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10629 if (UI.getUse().getResNo() == Value) 10630 return true; 10631 10632 return false; 10633 } 10634 10635 /// isOnlyUserOf - Return true if this node is the only use of N. 10636 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10637 bool Seen = false; 10638 for (const SDNode *User : N->uses()) { 10639 if (User == this) 10640 Seen = true; 10641 else 10642 return false; 10643 } 10644 10645 return Seen; 10646 } 10647 10648 /// Return true if the only users of N are contained in Nodes. 10649 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10650 bool Seen = false; 10651 for (const SDNode *User : N->uses()) { 10652 if (llvm::is_contained(Nodes, User)) 10653 Seen = true; 10654 else 10655 return false; 10656 } 10657 10658 return Seen; 10659 } 10660 10661 /// isOperand - Return true if this node is an operand of N. 10662 bool SDValue::isOperandOf(const SDNode *N) const { 10663 return is_contained(N->op_values(), *this); 10664 } 10665 10666 bool SDNode::isOperandOf(const SDNode *N) const { 10667 return any_of(N->op_values(), 10668 [this](SDValue Op) { return this == Op.getNode(); }); 10669 } 10670 10671 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10672 /// be a chain) reaches the specified operand without crossing any 10673 /// side-effecting instructions on any chain path. In practice, this looks 10674 /// through token factors and non-volatile loads. In order to remain efficient, 10675 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10676 /// 10677 /// Note that we only need to examine chains when we're searching for 10678 /// side-effects; SelectionDAG requires that all side-effects are represented 10679 /// by chains, even if another operand would force a specific ordering. This 10680 /// constraint is necessary to allow transformations like splitting loads. 10681 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10682 unsigned Depth) const { 10683 if (*this == Dest) return true; 10684 10685 // Don't search too deeply, we just want to be able to see through 10686 // TokenFactor's etc. 10687 if (Depth == 0) return false; 10688 10689 // If this is a token factor, all inputs to the TF happen in parallel. 10690 if (getOpcode() == ISD::TokenFactor) { 10691 // First, try a shallow search. 10692 if (is_contained((*this)->ops(), Dest)) { 10693 // We found the chain we want as an operand of this TokenFactor. 10694 // Essentially, we reach the chain without side-effects if we could 10695 // serialize the TokenFactor into a simple chain of operations with 10696 // Dest as the last operation. This is automatically true if the 10697 // chain has one use: there are no other ordering constraints. 10698 // If the chain has more than one use, we give up: some other 10699 // use of Dest might force a side-effect between Dest and the current 10700 // node. 10701 if (Dest.hasOneUse()) 10702 return true; 10703 } 10704 // Next, try a deep search: check whether every operand of the TokenFactor 10705 // reaches Dest. 10706 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10707 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10708 }); 10709 } 10710 10711 // Loads don't have side effects, look through them. 10712 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10713 if (Ld->isUnordered()) 10714 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10715 } 10716 return false; 10717 } 10718 10719 bool SDNode::hasPredecessor(const SDNode *N) const { 10720 SmallPtrSet<const SDNode *, 32> Visited; 10721 SmallVector<const SDNode *, 16> Worklist; 10722 Worklist.push_back(this); 10723 return hasPredecessorHelper(N, Visited, Worklist); 10724 } 10725 10726 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10727 this->Flags.intersectWith(Flags); 10728 } 10729 10730 SDValue 10731 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10732 ArrayRef<ISD::NodeType> CandidateBinOps, 10733 bool AllowPartials) { 10734 // The pattern must end in an extract from index 0. 10735 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10736 !isNullConstant(Extract->getOperand(1))) 10737 return SDValue(); 10738 10739 // Match against one of the candidate binary ops. 10740 SDValue Op = Extract->getOperand(0); 10741 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10742 return Op.getOpcode() == unsigned(BinOp); 10743 })) 10744 return SDValue(); 10745 10746 // Floating-point reductions may require relaxed constraints on the final step 10747 // of the reduction because they may reorder intermediate operations. 10748 unsigned CandidateBinOp = Op.getOpcode(); 10749 if (Op.getValueType().isFloatingPoint()) { 10750 SDNodeFlags Flags = Op->getFlags(); 10751 switch (CandidateBinOp) { 10752 case ISD::FADD: 10753 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10754 return SDValue(); 10755 break; 10756 default: 10757 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10758 } 10759 } 10760 10761 // Matching failed - attempt to see if we did enough stages that a partial 10762 // reduction from a subvector is possible. 10763 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10764 if (!AllowPartials || !Op) 10765 return SDValue(); 10766 EVT OpVT = Op.getValueType(); 10767 EVT OpSVT = OpVT.getScalarType(); 10768 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10769 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10770 return SDValue(); 10771 BinOp = (ISD::NodeType)CandidateBinOp; 10772 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10773 getVectorIdxConstant(0, SDLoc(Op))); 10774 }; 10775 10776 // At each stage, we're looking for something that looks like: 10777 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10778 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10779 // i32 undef, i32 undef, i32 undef, i32 undef> 10780 // %a = binop <8 x i32> %op, %s 10781 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10782 // we expect something like: 10783 // <4,5,6,7,u,u,u,u> 10784 // <2,3,u,u,u,u,u,u> 10785 // <1,u,u,u,u,u,u,u> 10786 // While a partial reduction match would be: 10787 // <2,3,u,u,u,u,u,u> 10788 // <1,u,u,u,u,u,u,u> 10789 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10790 SDValue PrevOp; 10791 for (unsigned i = 0; i < Stages; ++i) { 10792 unsigned MaskEnd = (1 << i); 10793 10794 if (Op.getOpcode() != CandidateBinOp) 10795 return PartialReduction(PrevOp, MaskEnd); 10796 10797 SDValue Op0 = Op.getOperand(0); 10798 SDValue Op1 = Op.getOperand(1); 10799 10800 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10801 if (Shuffle) { 10802 Op = Op1; 10803 } else { 10804 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10805 Op = Op0; 10806 } 10807 10808 // The first operand of the shuffle should be the same as the other operand 10809 // of the binop. 10810 if (!Shuffle || Shuffle->getOperand(0) != Op) 10811 return PartialReduction(PrevOp, MaskEnd); 10812 10813 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10814 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10815 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10816 return PartialReduction(PrevOp, MaskEnd); 10817 10818 PrevOp = Op; 10819 } 10820 10821 // Handle subvector reductions, which tend to appear after the shuffle 10822 // reduction stages. 10823 while (Op.getOpcode() == CandidateBinOp) { 10824 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10825 SDValue Op0 = Op.getOperand(0); 10826 SDValue Op1 = Op.getOperand(1); 10827 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10828 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10829 Op0.getOperand(0) != Op1.getOperand(0)) 10830 break; 10831 SDValue Src = Op0.getOperand(0); 10832 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10833 if (NumSrcElts != (2 * NumElts)) 10834 break; 10835 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10836 Op1.getConstantOperandAPInt(1) == NumElts) && 10837 !(Op1.getConstantOperandAPInt(1) == 0 && 10838 Op0.getConstantOperandAPInt(1) == NumElts)) 10839 break; 10840 Op = Src; 10841 } 10842 10843 BinOp = (ISD::NodeType)CandidateBinOp; 10844 return Op; 10845 } 10846 10847 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10848 assert(N->getNumValues() == 1 && 10849 "Can't unroll a vector with multiple results!"); 10850 10851 EVT VT = N->getValueType(0); 10852 unsigned NE = VT.getVectorNumElements(); 10853 EVT EltVT = VT.getVectorElementType(); 10854 SDLoc dl(N); 10855 10856 SmallVector<SDValue, 8> Scalars; 10857 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10858 10859 // If ResNE is 0, fully unroll the vector op. 10860 if (ResNE == 0) 10861 ResNE = NE; 10862 else if (NE > ResNE) 10863 NE = ResNE; 10864 10865 unsigned i; 10866 for (i= 0; i != NE; ++i) { 10867 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10868 SDValue Operand = N->getOperand(j); 10869 EVT OperandVT = Operand.getValueType(); 10870 if (OperandVT.isVector()) { 10871 // A vector operand; extract a single element. 10872 EVT OperandEltVT = OperandVT.getVectorElementType(); 10873 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10874 Operand, getVectorIdxConstant(i, dl)); 10875 } else { 10876 // A scalar operand; just use it as is. 10877 Operands[j] = Operand; 10878 } 10879 } 10880 10881 switch (N->getOpcode()) { 10882 default: { 10883 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10884 N->getFlags())); 10885 break; 10886 } 10887 case ISD::VSELECT: 10888 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10889 break; 10890 case ISD::SHL: 10891 case ISD::SRA: 10892 case ISD::SRL: 10893 case ISD::ROTL: 10894 case ISD::ROTR: 10895 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10896 getShiftAmountOperand(Operands[0].getValueType(), 10897 Operands[1]))); 10898 break; 10899 case ISD::SIGN_EXTEND_INREG: { 10900 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10901 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10902 Operands[0], 10903 getValueType(ExtVT))); 10904 } 10905 } 10906 } 10907 10908 for (; i < ResNE; ++i) 10909 Scalars.push_back(getUNDEF(EltVT)); 10910 10911 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10912 return getBuildVector(VecVT, dl, Scalars); 10913 } 10914 10915 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10916 SDNode *N, unsigned ResNE) { 10917 unsigned Opcode = N->getOpcode(); 10918 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10919 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10920 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10921 "Expected an overflow opcode"); 10922 10923 EVT ResVT = N->getValueType(0); 10924 EVT OvVT = N->getValueType(1); 10925 EVT ResEltVT = ResVT.getVectorElementType(); 10926 EVT OvEltVT = OvVT.getVectorElementType(); 10927 SDLoc dl(N); 10928 10929 // If ResNE is 0, fully unroll the vector op. 10930 unsigned NE = ResVT.getVectorNumElements(); 10931 if (ResNE == 0) 10932 ResNE = NE; 10933 else if (NE > ResNE) 10934 NE = ResNE; 10935 10936 SmallVector<SDValue, 8> LHSScalars; 10937 SmallVector<SDValue, 8> RHSScalars; 10938 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10939 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10940 10941 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10942 SDVTList VTs = getVTList(ResEltVT, SVT); 10943 SmallVector<SDValue, 8> ResScalars; 10944 SmallVector<SDValue, 8> OvScalars; 10945 for (unsigned i = 0; i < NE; ++i) { 10946 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10947 SDValue Ov = 10948 getSelect(dl, OvEltVT, Res.getValue(1), 10949 getBoolConstant(true, dl, OvEltVT, ResVT), 10950 getConstant(0, dl, OvEltVT)); 10951 10952 ResScalars.push_back(Res); 10953 OvScalars.push_back(Ov); 10954 } 10955 10956 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10957 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10958 10959 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10960 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10961 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10962 getBuildVector(NewOvVT, dl, OvScalars)); 10963 } 10964 10965 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10966 LoadSDNode *Base, 10967 unsigned Bytes, 10968 int Dist) const { 10969 if (LD->isVolatile() || Base->isVolatile()) 10970 return false; 10971 // TODO: probably too restrictive for atomics, revisit 10972 if (!LD->isSimple()) 10973 return false; 10974 if (LD->isIndexed() || Base->isIndexed()) 10975 return false; 10976 if (LD->getChain() != Base->getChain()) 10977 return false; 10978 EVT VT = LD->getValueType(0); 10979 if (VT.getSizeInBits() / 8 != Bytes) 10980 return false; 10981 10982 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10983 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10984 10985 int64_t Offset = 0; 10986 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 10987 return (Dist * Bytes == Offset); 10988 return false; 10989 } 10990 10991 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 10992 /// if it cannot be inferred. 10993 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 10994 // If this is a GlobalAddress + cst, return the alignment. 10995 const GlobalValue *GV = nullptr; 10996 int64_t GVOffset = 0; 10997 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 10998 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 10999 KnownBits Known(PtrWidth); 11000 llvm::computeKnownBits(GV, Known, getDataLayout()); 11001 unsigned AlignBits = Known.countMinTrailingZeros(); 11002 if (AlignBits) 11003 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11004 } 11005 11006 // If this is a direct reference to a stack slot, use information about the 11007 // stack slot's alignment. 11008 int FrameIdx = INT_MIN; 11009 int64_t FrameOffset = 0; 11010 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11011 FrameIdx = FI->getIndex(); 11012 } else if (isBaseWithConstantOffset(Ptr) && 11013 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11014 // Handle FI+Cst 11015 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11016 FrameOffset = Ptr.getConstantOperandVal(1); 11017 } 11018 11019 if (FrameIdx != INT_MIN) { 11020 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11021 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11022 } 11023 11024 return None; 11025 } 11026 11027 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11028 /// which is split (or expanded) into two not necessarily identical pieces. 11029 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11030 // Currently all types are split in half. 11031 EVT LoVT, HiVT; 11032 if (!VT.isVector()) 11033 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11034 else 11035 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11036 11037 return std::make_pair(LoVT, HiVT); 11038 } 11039 11040 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11041 /// type, dependent on an enveloping VT that has been split into two identical 11042 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11043 std::pair<EVT, EVT> 11044 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11045 bool *HiIsEmpty) const { 11046 EVT EltTp = VT.getVectorElementType(); 11047 // Examples: 11048 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11049 // custom VL=9 with enveloping VL=8/8 yields 8/1 11050 // custom VL=10 with enveloping VL=8/8 yields 8/2 11051 // etc. 11052 ElementCount VTNumElts = VT.getVectorElementCount(); 11053 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11054 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11055 "Mixing fixed width and scalable vectors when enveloping a type"); 11056 EVT LoVT, HiVT; 11057 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11058 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11059 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11060 *HiIsEmpty = false; 11061 } else { 11062 // Flag that hi type has zero storage size, but return split envelop type 11063 // (this would be easier if vector types with zero elements were allowed). 11064 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11065 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11066 *HiIsEmpty = true; 11067 } 11068 return std::make_pair(LoVT, HiVT); 11069 } 11070 11071 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11072 /// low/high part. 11073 std::pair<SDValue, SDValue> 11074 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11075 const EVT &HiVT) { 11076 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 11077 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 11078 "Splitting vector with an invalid mixture of fixed and scalable " 11079 "vector types"); 11080 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 11081 N.getValueType().getVectorMinNumElements() && 11082 "More vector elements requested than available!"); 11083 SDValue Lo, Hi; 11084 Lo = 11085 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 11086 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 11087 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 11088 // IDX with the runtime scaling factor of the result vector type. For 11089 // fixed-width result vectors, that runtime scaling factor is 1. 11090 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 11091 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 11092 return std::make_pair(Lo, Hi); 11093 } 11094 11095 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 11096 const SDLoc &DL) { 11097 // Split the vector length parameter. 11098 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 11099 EVT VT = N.getValueType(); 11100 assert(VecVT.getVectorElementCount().isKnownEven() && 11101 "Expecting the mask to be an evenly-sized vector"); 11102 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 11103 SDValue HalfNumElts = 11104 VecVT.isFixedLengthVector() 11105 ? getConstant(HalfMinNumElts, DL, VT) 11106 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 11107 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 11108 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 11109 return std::make_pair(Lo, Hi); 11110 } 11111 11112 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 11113 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 11114 EVT VT = N.getValueType(); 11115 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 11116 NextPowerOf2(VT.getVectorNumElements())); 11117 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 11118 getVectorIdxConstant(0, DL)); 11119 } 11120 11121 void SelectionDAG::ExtractVectorElements(SDValue Op, 11122 SmallVectorImpl<SDValue> &Args, 11123 unsigned Start, unsigned Count, 11124 EVT EltVT) { 11125 EVT VT = Op.getValueType(); 11126 if (Count == 0) 11127 Count = VT.getVectorNumElements(); 11128 if (EltVT == EVT()) 11129 EltVT = VT.getVectorElementType(); 11130 SDLoc SL(Op); 11131 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 11132 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 11133 getVectorIdxConstant(i, SL))); 11134 } 11135 } 11136 11137 // getAddressSpace - Return the address space this GlobalAddress belongs to. 11138 unsigned GlobalAddressSDNode::getAddressSpace() const { 11139 return getGlobal()->getType()->getAddressSpace(); 11140 } 11141 11142 Type *ConstantPoolSDNode::getType() const { 11143 if (isMachineConstantPoolEntry()) 11144 return Val.MachineCPVal->getType(); 11145 return Val.ConstVal->getType(); 11146 } 11147 11148 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 11149 unsigned &SplatBitSize, 11150 bool &HasAnyUndefs, 11151 unsigned MinSplatBits, 11152 bool IsBigEndian) const { 11153 EVT VT = getValueType(0); 11154 assert(VT.isVector() && "Expected a vector type"); 11155 unsigned VecWidth = VT.getSizeInBits(); 11156 if (MinSplatBits > VecWidth) 11157 return false; 11158 11159 // FIXME: The widths are based on this node's type, but build vectors can 11160 // truncate their operands. 11161 SplatValue = APInt(VecWidth, 0); 11162 SplatUndef = APInt(VecWidth, 0); 11163 11164 // Get the bits. Bits with undefined values (when the corresponding element 11165 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 11166 // in SplatValue. If any of the values are not constant, give up and return 11167 // false. 11168 unsigned int NumOps = getNumOperands(); 11169 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 11170 unsigned EltWidth = VT.getScalarSizeInBits(); 11171 11172 for (unsigned j = 0; j < NumOps; ++j) { 11173 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 11174 SDValue OpVal = getOperand(i); 11175 unsigned BitPos = j * EltWidth; 11176 11177 if (OpVal.isUndef()) 11178 SplatUndef.setBits(BitPos, BitPos + EltWidth); 11179 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 11180 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 11181 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 11182 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 11183 else 11184 return false; 11185 } 11186 11187 // The build_vector is all constants or undefs. Find the smallest element 11188 // size that splats the vector. 11189 HasAnyUndefs = (SplatUndef != 0); 11190 11191 // FIXME: This does not work for vectors with elements less than 8 bits. 11192 while (VecWidth > 8) { 11193 unsigned HalfSize = VecWidth / 2; 11194 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 11195 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 11196 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 11197 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 11198 11199 // If the two halves do not match (ignoring undef bits), stop here. 11200 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 11201 MinSplatBits > HalfSize) 11202 break; 11203 11204 SplatValue = HighValue | LowValue; 11205 SplatUndef = HighUndef & LowUndef; 11206 11207 VecWidth = HalfSize; 11208 } 11209 11210 SplatBitSize = VecWidth; 11211 return true; 11212 } 11213 11214 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 11215 BitVector *UndefElements) const { 11216 unsigned NumOps = getNumOperands(); 11217 if (UndefElements) { 11218 UndefElements->clear(); 11219 UndefElements->resize(NumOps); 11220 } 11221 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11222 if (!DemandedElts) 11223 return SDValue(); 11224 SDValue Splatted; 11225 for (unsigned i = 0; i != NumOps; ++i) { 11226 if (!DemandedElts[i]) 11227 continue; 11228 SDValue Op = getOperand(i); 11229 if (Op.isUndef()) { 11230 if (UndefElements) 11231 (*UndefElements)[i] = true; 11232 } else if (!Splatted) { 11233 Splatted = Op; 11234 } else if (Splatted != Op) { 11235 return SDValue(); 11236 } 11237 } 11238 11239 if (!Splatted) { 11240 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 11241 assert(getOperand(FirstDemandedIdx).isUndef() && 11242 "Can only have a splat without a constant for all undefs."); 11243 return getOperand(FirstDemandedIdx); 11244 } 11245 11246 return Splatted; 11247 } 11248 11249 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 11250 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11251 return getSplatValue(DemandedElts, UndefElements); 11252 } 11253 11254 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 11255 SmallVectorImpl<SDValue> &Sequence, 11256 BitVector *UndefElements) const { 11257 unsigned NumOps = getNumOperands(); 11258 Sequence.clear(); 11259 if (UndefElements) { 11260 UndefElements->clear(); 11261 UndefElements->resize(NumOps); 11262 } 11263 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11264 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 11265 return false; 11266 11267 // Set the undefs even if we don't find a sequence (like getSplatValue). 11268 if (UndefElements) 11269 for (unsigned I = 0; I != NumOps; ++I) 11270 if (DemandedElts[I] && getOperand(I).isUndef()) 11271 (*UndefElements)[I] = true; 11272 11273 // Iteratively widen the sequence length looking for repetitions. 11274 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 11275 Sequence.append(SeqLen, SDValue()); 11276 for (unsigned I = 0; I != NumOps; ++I) { 11277 if (!DemandedElts[I]) 11278 continue; 11279 SDValue &SeqOp = Sequence[I % SeqLen]; 11280 SDValue Op = getOperand(I); 11281 if (Op.isUndef()) { 11282 if (!SeqOp) 11283 SeqOp = Op; 11284 continue; 11285 } 11286 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 11287 Sequence.clear(); 11288 break; 11289 } 11290 SeqOp = Op; 11291 } 11292 if (!Sequence.empty()) 11293 return true; 11294 } 11295 11296 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 11297 return false; 11298 } 11299 11300 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 11301 BitVector *UndefElements) const { 11302 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11303 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 11304 } 11305 11306 ConstantSDNode * 11307 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 11308 BitVector *UndefElements) const { 11309 return dyn_cast_or_null<ConstantSDNode>( 11310 getSplatValue(DemandedElts, UndefElements)); 11311 } 11312 11313 ConstantSDNode * 11314 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 11315 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 11316 } 11317 11318 ConstantFPSDNode * 11319 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 11320 BitVector *UndefElements) const { 11321 return dyn_cast_or_null<ConstantFPSDNode>( 11322 getSplatValue(DemandedElts, UndefElements)); 11323 } 11324 11325 ConstantFPSDNode * 11326 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 11327 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 11328 } 11329 11330 int32_t 11331 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 11332 uint32_t BitWidth) const { 11333 if (ConstantFPSDNode *CN = 11334 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 11335 bool IsExact; 11336 APSInt IntVal(BitWidth); 11337 const APFloat &APF = CN->getValueAPF(); 11338 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 11339 APFloat::opOK || 11340 !IsExact) 11341 return -1; 11342 11343 return IntVal.exactLogBase2(); 11344 } 11345 return -1; 11346 } 11347 11348 bool BuildVectorSDNode::getConstantRawBits( 11349 bool IsLittleEndian, unsigned DstEltSizeInBits, 11350 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 11351 // Early-out if this contains anything but Undef/Constant/ConstantFP. 11352 if (!isConstant()) 11353 return false; 11354 11355 unsigned NumSrcOps = getNumOperands(); 11356 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 11357 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11358 "Invalid bitcast scale"); 11359 11360 // Extract raw src bits. 11361 SmallVector<APInt> SrcBitElements(NumSrcOps, 11362 APInt::getNullValue(SrcEltSizeInBits)); 11363 BitVector SrcUndeElements(NumSrcOps, false); 11364 11365 for (unsigned I = 0; I != NumSrcOps; ++I) { 11366 SDValue Op = getOperand(I); 11367 if (Op.isUndef()) { 11368 SrcUndeElements.set(I); 11369 continue; 11370 } 11371 auto *CInt = dyn_cast<ConstantSDNode>(Op); 11372 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 11373 assert((CInt || CFP) && "Unknown constant"); 11374 SrcBitElements[I] = 11375 CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits) 11376 : CFP->getValueAPF().bitcastToAPInt(); 11377 } 11378 11379 // Recast to dst width. 11380 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11381 SrcBitElements, UndefElements, SrcUndeElements); 11382 return true; 11383 } 11384 11385 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11386 unsigned DstEltSizeInBits, 11387 SmallVectorImpl<APInt> &DstBitElements, 11388 ArrayRef<APInt> SrcBitElements, 11389 BitVector &DstUndefElements, 11390 const BitVector &SrcUndefElements) { 11391 unsigned NumSrcOps = SrcBitElements.size(); 11392 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11393 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11394 "Invalid bitcast scale"); 11395 assert(NumSrcOps == SrcUndefElements.size() && 11396 "Vector size mismatch"); 11397 11398 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11399 DstUndefElements.clear(); 11400 DstUndefElements.resize(NumDstOps, false); 11401 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11402 11403 // Concatenate src elements constant bits together into dst element. 11404 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11405 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11406 for (unsigned I = 0; I != NumDstOps; ++I) { 11407 DstUndefElements.set(I); 11408 APInt &DstBits = DstBitElements[I]; 11409 for (unsigned J = 0; J != Scale; ++J) { 11410 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11411 if (SrcUndefElements[Idx]) 11412 continue; 11413 DstUndefElements.reset(I); 11414 const APInt &SrcBits = SrcBitElements[Idx]; 11415 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11416 "Illegal constant bitwidths"); 11417 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11418 } 11419 } 11420 return; 11421 } 11422 11423 // Split src element constant bits into dst elements. 11424 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11425 for (unsigned I = 0; I != NumSrcOps; ++I) { 11426 if (SrcUndefElements[I]) { 11427 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11428 continue; 11429 } 11430 const APInt &SrcBits = SrcBitElements[I]; 11431 for (unsigned J = 0; J != Scale; ++J) { 11432 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11433 APInt &DstBits = DstBitElements[Idx]; 11434 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11435 } 11436 } 11437 } 11438 11439 bool BuildVectorSDNode::isConstant() const { 11440 for (const SDValue &Op : op_values()) { 11441 unsigned Opc = Op.getOpcode(); 11442 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11443 return false; 11444 } 11445 return true; 11446 } 11447 11448 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11449 // Find the first non-undef value in the shuffle mask. 11450 unsigned i, e; 11451 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11452 /* search */; 11453 11454 // If all elements are undefined, this shuffle can be considered a splat 11455 // (although it should eventually get simplified away completely). 11456 if (i == e) 11457 return true; 11458 11459 // Make sure all remaining elements are either undef or the same as the first 11460 // non-undef value. 11461 for (int Idx = Mask[i]; i != e; ++i) 11462 if (Mask[i] >= 0 && Mask[i] != Idx) 11463 return false; 11464 return true; 11465 } 11466 11467 // Returns the SDNode if it is a constant integer BuildVector 11468 // or constant integer. 11469 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11470 if (isa<ConstantSDNode>(N)) 11471 return N.getNode(); 11472 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11473 return N.getNode(); 11474 // Treat a GlobalAddress supporting constant offset folding as a 11475 // constant integer. 11476 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11477 if (GA->getOpcode() == ISD::GlobalAddress && 11478 TLI->isOffsetFoldingLegal(GA)) 11479 return GA; 11480 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11481 isa<ConstantSDNode>(N.getOperand(0))) 11482 return N.getNode(); 11483 return nullptr; 11484 } 11485 11486 // Returns the SDNode if it is a constant float BuildVector 11487 // or constant float. 11488 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11489 if (isa<ConstantFPSDNode>(N)) 11490 return N.getNode(); 11491 11492 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11493 return N.getNode(); 11494 11495 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11496 isa<ConstantFPSDNode>(N.getOperand(0))) 11497 return N.getNode(); 11498 11499 return nullptr; 11500 } 11501 11502 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11503 assert(!Node->OperandList && "Node already has operands"); 11504 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11505 "too many operands to fit into SDNode"); 11506 SDUse *Ops = OperandRecycler.allocate( 11507 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11508 11509 bool IsDivergent = false; 11510 for (unsigned I = 0; I != Vals.size(); ++I) { 11511 Ops[I].setUser(Node); 11512 Ops[I].setInitial(Vals[I]); 11513 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11514 IsDivergent |= Ops[I].getNode()->isDivergent(); 11515 } 11516 Node->NumOperands = Vals.size(); 11517 Node->OperandList = Ops; 11518 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11519 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11520 Node->SDNodeBits.IsDivergent = IsDivergent; 11521 } 11522 checkForCycles(Node); 11523 } 11524 11525 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11526 SmallVectorImpl<SDValue> &Vals) { 11527 size_t Limit = SDNode::getMaxNumOperands(); 11528 while (Vals.size() > Limit) { 11529 unsigned SliceIdx = Vals.size() - Limit; 11530 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11531 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11532 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11533 Vals.emplace_back(NewTF); 11534 } 11535 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11536 } 11537 11538 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11539 EVT VT, SDNodeFlags Flags) { 11540 switch (Opcode) { 11541 default: 11542 return SDValue(); 11543 case ISD::ADD: 11544 case ISD::OR: 11545 case ISD::XOR: 11546 case ISD::UMAX: 11547 return getConstant(0, DL, VT); 11548 case ISD::MUL: 11549 return getConstant(1, DL, VT); 11550 case ISD::AND: 11551 case ISD::UMIN: 11552 return getAllOnesConstant(DL, VT); 11553 case ISD::SMAX: 11554 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11555 case ISD::SMIN: 11556 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11557 case ISD::FADD: 11558 return getConstantFP(-0.0, DL, VT); 11559 case ISD::FMUL: 11560 return getConstantFP(1.0, DL, VT); 11561 case ISD::FMINNUM: 11562 case ISD::FMAXNUM: { 11563 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11564 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11565 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11566 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11567 APFloat::getLargest(Semantics); 11568 if (Opcode == ISD::FMAXNUM) 11569 NeutralAF.changeSign(); 11570 11571 return getConstantFP(NeutralAF, DL, VT); 11572 } 11573 } 11574 } 11575 11576 #ifndef NDEBUG 11577 static void checkForCyclesHelper(const SDNode *N, 11578 SmallPtrSetImpl<const SDNode*> &Visited, 11579 SmallPtrSetImpl<const SDNode*> &Checked, 11580 const llvm::SelectionDAG *DAG) { 11581 // If this node has already been checked, don't check it again. 11582 if (Checked.count(N)) 11583 return; 11584 11585 // If a node has already been visited on this depth-first walk, reject it as 11586 // a cycle. 11587 if (!Visited.insert(N).second) { 11588 errs() << "Detected cycle in SelectionDAG\n"; 11589 dbgs() << "Offending node:\n"; 11590 N->dumprFull(DAG); dbgs() << "\n"; 11591 abort(); 11592 } 11593 11594 for (const SDValue &Op : N->op_values()) 11595 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11596 11597 Checked.insert(N); 11598 Visited.erase(N); 11599 } 11600 #endif 11601 11602 void llvm::checkForCycles(const llvm::SDNode *N, 11603 const llvm::SelectionDAG *DAG, 11604 bool force) { 11605 #ifndef NDEBUG 11606 bool check = force; 11607 #ifdef EXPENSIVE_CHECKS 11608 check = true; 11609 #endif // EXPENSIVE_CHECKS 11610 if (check) { 11611 assert(N && "Checking nonexistent SDNode"); 11612 SmallPtrSet<const SDNode*, 32> visited; 11613 SmallPtrSet<const SDNode*, 32> checked; 11614 checkForCyclesHelper(N, visited, checked, DAG); 11615 } 11616 #endif // !NDEBUG 11617 } 11618 11619 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11620 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11621 } 11622