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 } // end switch (N->getOpcode()) 848 849 // Target specific memory nodes could also have address spaces and flags 850 // to check. 851 if (N->isTargetMemoryOpcode()) { 852 const MemSDNode *MN = cast<MemSDNode>(N); 853 ID.AddInteger(MN->getPointerInfo().getAddrSpace()); 854 ID.AddInteger(MN->getMemOperand()->getFlags()); 855 } 856 } 857 858 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 859 /// data. 860 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 861 AddNodeIDOpcode(ID, N->getOpcode()); 862 // Add the return value info. 863 AddNodeIDValueTypes(ID, N->getVTList()); 864 // Add the operand info. 865 AddNodeIDOperands(ID, N->ops()); 866 867 // Handle SDNode leafs with special info. 868 AddNodeIDCustom(ID, N); 869 } 870 871 //===----------------------------------------------------------------------===// 872 // SelectionDAG Class 873 //===----------------------------------------------------------------------===// 874 875 /// doNotCSE - Return true if CSE should not be performed for this node. 876 static bool doNotCSE(SDNode *N) { 877 if (N->getValueType(0) == MVT::Glue) 878 return true; // Never CSE anything that produces a flag. 879 880 switch (N->getOpcode()) { 881 default: break; 882 case ISD::HANDLENODE: 883 case ISD::EH_LABEL: 884 return true; // Never CSE these nodes. 885 } 886 887 // Check that remaining values produced are not flags. 888 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 889 if (N->getValueType(i) == MVT::Glue) 890 return true; // Never CSE anything that produces a flag. 891 892 return false; 893 } 894 895 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 896 /// SelectionDAG. 897 void SelectionDAG::RemoveDeadNodes() { 898 // Create a dummy node (which is not added to allnodes), that adds a reference 899 // to the root node, preventing it from being deleted. 900 HandleSDNode Dummy(getRoot()); 901 902 SmallVector<SDNode*, 128> DeadNodes; 903 904 // Add all obviously-dead nodes to the DeadNodes worklist. 905 for (SDNode &Node : allnodes()) 906 if (Node.use_empty()) 907 DeadNodes.push_back(&Node); 908 909 RemoveDeadNodes(DeadNodes); 910 911 // If the root changed (e.g. it was a dead load, update the root). 912 setRoot(Dummy.getValue()); 913 } 914 915 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 916 /// given list, and any nodes that become unreachable as a result. 917 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 918 919 // Process the worklist, deleting the nodes and adding their uses to the 920 // worklist. 921 while (!DeadNodes.empty()) { 922 SDNode *N = DeadNodes.pop_back_val(); 923 // Skip to next node if we've already managed to delete the node. This could 924 // happen if replacing a node causes a node previously added to the node to 925 // be deleted. 926 if (N->getOpcode() == ISD::DELETED_NODE) 927 continue; 928 929 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 930 DUL->NodeDeleted(N, nullptr); 931 932 // Take the node out of the appropriate CSE map. 933 RemoveNodeFromCSEMaps(N); 934 935 // Next, brutally remove the operand list. This is safe to do, as there are 936 // no cycles in the graph. 937 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 938 SDUse &Use = *I++; 939 SDNode *Operand = Use.getNode(); 940 Use.set(SDValue()); 941 942 // Now that we removed this operand, see if there are no uses of it left. 943 if (Operand->use_empty()) 944 DeadNodes.push_back(Operand); 945 } 946 947 DeallocateNode(N); 948 } 949 } 950 951 void SelectionDAG::RemoveDeadNode(SDNode *N){ 952 SmallVector<SDNode*, 16> DeadNodes(1, N); 953 954 // Create a dummy node that adds a reference to the root node, preventing 955 // it from being deleted. (This matters if the root is an operand of the 956 // dead node.) 957 HandleSDNode Dummy(getRoot()); 958 959 RemoveDeadNodes(DeadNodes); 960 } 961 962 void SelectionDAG::DeleteNode(SDNode *N) { 963 // First take this out of the appropriate CSE map. 964 RemoveNodeFromCSEMaps(N); 965 966 // Finally, remove uses due to operands of this node, remove from the 967 // AllNodes list, and delete the node. 968 DeleteNodeNotInCSEMaps(N); 969 } 970 971 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 972 assert(N->getIterator() != AllNodes.begin() && 973 "Cannot delete the entry node!"); 974 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 975 976 // Drop all of the operands and decrement used node's use counts. 977 N->DropOperands(); 978 979 DeallocateNode(N); 980 } 981 982 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 983 assert(!(V->isVariadic() && isParameter)); 984 if (isParameter) 985 ByvalParmDbgValues.push_back(V); 986 else 987 DbgValues.push_back(V); 988 for (const SDNode *Node : V->getSDNodes()) 989 if (Node) 990 DbgValMap[Node].push_back(V); 991 } 992 993 void SDDbgInfo::erase(const SDNode *Node) { 994 DbgValMapType::iterator I = DbgValMap.find(Node); 995 if (I == DbgValMap.end()) 996 return; 997 for (auto &Val: I->second) 998 Val->setIsInvalidated(); 999 DbgValMap.erase(I); 1000 } 1001 1002 void SelectionDAG::DeallocateNode(SDNode *N) { 1003 // If we have operands, deallocate them. 1004 removeOperands(N); 1005 1006 NodeAllocator.Deallocate(AllNodes.remove(N)); 1007 1008 // Set the opcode to DELETED_NODE to help catch bugs when node 1009 // memory is reallocated. 1010 // FIXME: There are places in SDag that have grown a dependency on the opcode 1011 // value in the released node. 1012 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 1013 N->NodeType = ISD::DELETED_NODE; 1014 1015 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 1016 // them and forget about that node. 1017 DbgInfo->erase(N); 1018 } 1019 1020 #ifndef NDEBUG 1021 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 1022 static void VerifySDNode(SDNode *N) { 1023 switch (N->getOpcode()) { 1024 default: 1025 break; 1026 case ISD::BUILD_PAIR: { 1027 EVT VT = N->getValueType(0); 1028 assert(N->getNumValues() == 1 && "Too many results!"); 1029 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1030 "Wrong return type!"); 1031 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1032 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1033 "Mismatched operand types!"); 1034 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1035 "Wrong operand type!"); 1036 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1037 "Wrong return type size"); 1038 break; 1039 } 1040 case ISD::BUILD_VECTOR: { 1041 assert(N->getNumValues() == 1 && "Too many results!"); 1042 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1043 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1044 "Wrong number of operands!"); 1045 EVT EltVT = N->getValueType(0).getVectorElementType(); 1046 for (const SDUse &Op : N->ops()) { 1047 assert((Op.getValueType() == EltVT || 1048 (EltVT.isInteger() && Op.getValueType().isInteger() && 1049 EltVT.bitsLE(Op.getValueType()))) && 1050 "Wrong operand type!"); 1051 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1052 "Operands must all have the same type"); 1053 } 1054 break; 1055 } 1056 } 1057 } 1058 #endif // NDEBUG 1059 1060 /// Insert a newly allocated node into the DAG. 1061 /// 1062 /// Handles insertion into the all nodes list and CSE map, as well as 1063 /// verification and other common operations when a new node is allocated. 1064 void SelectionDAG::InsertNode(SDNode *N) { 1065 AllNodes.push_back(N); 1066 #ifndef NDEBUG 1067 N->PersistentId = NextPersistentId++; 1068 VerifySDNode(N); 1069 #endif 1070 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1071 DUL->NodeInserted(N); 1072 } 1073 1074 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1075 /// correspond to it. This is useful when we're about to delete or repurpose 1076 /// the node. We don't want future request for structurally identical nodes 1077 /// to return N anymore. 1078 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1079 bool Erased = false; 1080 switch (N->getOpcode()) { 1081 case ISD::HANDLENODE: return false; // noop. 1082 case ISD::CONDCODE: 1083 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1084 "Cond code doesn't exist!"); 1085 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1086 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1087 break; 1088 case ISD::ExternalSymbol: 1089 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1090 break; 1091 case ISD::TargetExternalSymbol: { 1092 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1093 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1094 ESN->getSymbol(), ESN->getTargetFlags())); 1095 break; 1096 } 1097 case ISD::MCSymbol: { 1098 auto *MCSN = cast<MCSymbolSDNode>(N); 1099 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1100 break; 1101 } 1102 case ISD::VALUETYPE: { 1103 EVT VT = cast<VTSDNode>(N)->getVT(); 1104 if (VT.isExtended()) { 1105 Erased = ExtendedValueTypeNodes.erase(VT); 1106 } else { 1107 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1108 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1109 } 1110 break; 1111 } 1112 default: 1113 // Remove it from the CSE Map. 1114 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1115 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1116 Erased = CSEMap.RemoveNode(N); 1117 break; 1118 } 1119 #ifndef NDEBUG 1120 // Verify that the node was actually in one of the CSE maps, unless it has a 1121 // flag result (which cannot be CSE'd) or is one of the special cases that are 1122 // not subject to CSE. 1123 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1124 !N->isMachineOpcode() && !doNotCSE(N)) { 1125 N->dump(this); 1126 dbgs() << "\n"; 1127 llvm_unreachable("Node is not in map!"); 1128 } 1129 #endif 1130 return Erased; 1131 } 1132 1133 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1134 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1135 /// node already exists, in which case transfer all its users to the existing 1136 /// node. This transfer can potentially trigger recursive merging. 1137 void 1138 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1139 // For node types that aren't CSE'd, just act as if no identical node 1140 // already exists. 1141 if (!doNotCSE(N)) { 1142 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1143 if (Existing != N) { 1144 // If there was already an existing matching node, use ReplaceAllUsesWith 1145 // to replace the dead one with the existing one. This can cause 1146 // recursive merging of other unrelated nodes down the line. 1147 ReplaceAllUsesWith(N, Existing); 1148 1149 // N is now dead. Inform the listeners and delete it. 1150 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1151 DUL->NodeDeleted(N, Existing); 1152 DeleteNodeNotInCSEMaps(N); 1153 return; 1154 } 1155 } 1156 1157 // If the node doesn't already exist, we updated it. Inform listeners. 1158 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1159 DUL->NodeUpdated(N); 1160 } 1161 1162 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1163 /// were replaced with those specified. If this node is never memoized, 1164 /// return null, otherwise return a pointer to the slot it would take. If a 1165 /// node already exists with these operands, the slot will be non-null. 1166 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1167 void *&InsertPos) { 1168 if (doNotCSE(N)) 1169 return nullptr; 1170 1171 SDValue Ops[] = { Op }; 1172 FoldingSetNodeID ID; 1173 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1174 AddNodeIDCustom(ID, N); 1175 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1176 if (Node) 1177 Node->intersectFlagsWith(N->getFlags()); 1178 return Node; 1179 } 1180 1181 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1182 /// were replaced with those specified. If this node is never memoized, 1183 /// return null, otherwise return a pointer to the slot it would take. If a 1184 /// node already exists with these operands, the slot will be non-null. 1185 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1186 SDValue Op1, SDValue Op2, 1187 void *&InsertPos) { 1188 if (doNotCSE(N)) 1189 return nullptr; 1190 1191 SDValue Ops[] = { Op1, Op2 }; 1192 FoldingSetNodeID ID; 1193 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1194 AddNodeIDCustom(ID, N); 1195 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1196 if (Node) 1197 Node->intersectFlagsWith(N->getFlags()); 1198 return Node; 1199 } 1200 1201 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1202 /// were replaced with those specified. If this node is never memoized, 1203 /// return null, otherwise return a pointer to the slot it would take. If a 1204 /// node already exists with these operands, the slot will be non-null. 1205 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1206 void *&InsertPos) { 1207 if (doNotCSE(N)) 1208 return nullptr; 1209 1210 FoldingSetNodeID ID; 1211 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1212 AddNodeIDCustom(ID, N); 1213 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1214 if (Node) 1215 Node->intersectFlagsWith(N->getFlags()); 1216 return Node; 1217 } 1218 1219 Align SelectionDAG::getEVTAlign(EVT VT) const { 1220 Type *Ty = VT == MVT::iPTR ? 1221 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1222 VT.getTypeForEVT(*getContext()); 1223 1224 return getDataLayout().getABITypeAlign(Ty); 1225 } 1226 1227 // EntryNode could meaningfully have debug info if we can find it... 1228 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1229 : TM(tm), OptLevel(OL), 1230 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1231 Root(getEntryNode()) { 1232 InsertNode(&EntryNode); 1233 DbgInfo = new SDDbgInfo(); 1234 } 1235 1236 void SelectionDAG::init(MachineFunction &NewMF, 1237 OptimizationRemarkEmitter &NewORE, 1238 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1239 LegacyDivergenceAnalysis * Divergence, 1240 ProfileSummaryInfo *PSIin, 1241 BlockFrequencyInfo *BFIin) { 1242 MF = &NewMF; 1243 SDAGISelPass = PassPtr; 1244 ORE = &NewORE; 1245 TLI = getSubtarget().getTargetLowering(); 1246 TSI = getSubtarget().getSelectionDAGInfo(); 1247 LibInfo = LibraryInfo; 1248 Context = &MF->getFunction().getContext(); 1249 DA = Divergence; 1250 PSI = PSIin; 1251 BFI = BFIin; 1252 } 1253 1254 SelectionDAG::~SelectionDAG() { 1255 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1256 allnodes_clear(); 1257 OperandRecycler.clear(OperandAllocator); 1258 delete DbgInfo; 1259 } 1260 1261 bool SelectionDAG::shouldOptForSize() const { 1262 return MF->getFunction().hasOptSize() || 1263 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1264 } 1265 1266 void SelectionDAG::allnodes_clear() { 1267 assert(&*AllNodes.begin() == &EntryNode); 1268 AllNodes.remove(AllNodes.begin()); 1269 while (!AllNodes.empty()) 1270 DeallocateNode(&AllNodes.front()); 1271 #ifndef NDEBUG 1272 NextPersistentId = 0; 1273 #endif 1274 } 1275 1276 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1277 void *&InsertPos) { 1278 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1279 if (N) { 1280 switch (N->getOpcode()) { 1281 default: break; 1282 case ISD::Constant: 1283 case ISD::ConstantFP: 1284 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1285 "debug location. Use another overload."); 1286 } 1287 } 1288 return N; 1289 } 1290 1291 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1292 const SDLoc &DL, void *&InsertPos) { 1293 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1294 if (N) { 1295 switch (N->getOpcode()) { 1296 case ISD::Constant: 1297 case ISD::ConstantFP: 1298 // Erase debug location from the node if the node is used at several 1299 // different places. Do not propagate one location to all uses as it 1300 // will cause a worse single stepping debugging experience. 1301 if (N->getDebugLoc() != DL.getDebugLoc()) 1302 N->setDebugLoc(DebugLoc()); 1303 break; 1304 default: 1305 // When the node's point of use is located earlier in the instruction 1306 // sequence than its prior point of use, update its debug info to the 1307 // earlier location. 1308 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1309 N->setDebugLoc(DL.getDebugLoc()); 1310 break; 1311 } 1312 } 1313 return N; 1314 } 1315 1316 void SelectionDAG::clear() { 1317 allnodes_clear(); 1318 OperandRecycler.clear(OperandAllocator); 1319 OperandAllocator.Reset(); 1320 CSEMap.clear(); 1321 1322 ExtendedValueTypeNodes.clear(); 1323 ExternalSymbols.clear(); 1324 TargetExternalSymbols.clear(); 1325 MCSymbols.clear(); 1326 SDCallSiteDbgInfo.clear(); 1327 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1328 static_cast<CondCodeSDNode*>(nullptr)); 1329 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1330 static_cast<SDNode*>(nullptr)); 1331 1332 EntryNode.UseList = nullptr; 1333 InsertNode(&EntryNode); 1334 Root = getEntryNode(); 1335 DbgInfo->clear(); 1336 } 1337 1338 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1339 return VT.bitsGT(Op.getValueType()) 1340 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1341 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1342 } 1343 1344 std::pair<SDValue, SDValue> 1345 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1346 const SDLoc &DL, EVT VT) { 1347 assert(!VT.bitsEq(Op.getValueType()) && 1348 "Strict no-op FP extend/round not allowed."); 1349 SDValue Res = 1350 VT.bitsGT(Op.getValueType()) 1351 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1352 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1353 {Chain, Op, getIntPtrConstant(0, DL)}); 1354 1355 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1356 } 1357 1358 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1359 return VT.bitsGT(Op.getValueType()) ? 1360 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1361 getNode(ISD::TRUNCATE, DL, VT, Op); 1362 } 1363 1364 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1365 return VT.bitsGT(Op.getValueType()) ? 1366 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1367 getNode(ISD::TRUNCATE, DL, VT, Op); 1368 } 1369 1370 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1371 return VT.bitsGT(Op.getValueType()) ? 1372 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1373 getNode(ISD::TRUNCATE, DL, VT, Op); 1374 } 1375 1376 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1377 EVT OpVT) { 1378 if (VT.bitsLE(Op.getValueType())) 1379 return getNode(ISD::TRUNCATE, SL, VT, Op); 1380 1381 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1382 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1383 } 1384 1385 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1386 EVT OpVT = Op.getValueType(); 1387 assert(VT.isInteger() && OpVT.isInteger() && 1388 "Cannot getZeroExtendInReg FP types"); 1389 assert(VT.isVector() == OpVT.isVector() && 1390 "getZeroExtendInReg type should be vector iff the operand " 1391 "type is vector!"); 1392 assert((!VT.isVector() || 1393 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1394 "Vector element counts must match in getZeroExtendInReg"); 1395 assert(VT.bitsLE(OpVT) && "Not extending!"); 1396 if (OpVT == VT) 1397 return Op; 1398 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1399 VT.getScalarSizeInBits()); 1400 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1401 } 1402 1403 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1404 // Only unsigned pointer semantics are supported right now. In the future this 1405 // might delegate to TLI to check pointer signedness. 1406 return getZExtOrTrunc(Op, DL, VT); 1407 } 1408 1409 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1410 // Only unsigned pointer semantics are supported right now. In the future this 1411 // might delegate to TLI to check pointer signedness. 1412 return getZeroExtendInReg(Op, DL, VT); 1413 } 1414 1415 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1416 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1417 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1418 } 1419 1420 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1421 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1422 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1423 } 1424 1425 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1426 EVT OpVT) { 1427 if (!V) 1428 return getConstant(0, DL, VT); 1429 1430 switch (TLI->getBooleanContents(OpVT)) { 1431 case TargetLowering::ZeroOrOneBooleanContent: 1432 case TargetLowering::UndefinedBooleanContent: 1433 return getConstant(1, DL, VT); 1434 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1435 return getAllOnesConstant(DL, VT); 1436 } 1437 llvm_unreachable("Unexpected boolean content enum!"); 1438 } 1439 1440 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1441 bool isT, bool isO) { 1442 EVT EltVT = VT.getScalarType(); 1443 assert((EltVT.getSizeInBits() >= 64 || 1444 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1445 "getConstant with a uint64_t value that doesn't fit in the type!"); 1446 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1447 } 1448 1449 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1450 bool isT, bool isO) { 1451 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1452 } 1453 1454 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1455 EVT VT, bool isT, bool isO) { 1456 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1457 1458 EVT EltVT = VT.getScalarType(); 1459 const ConstantInt *Elt = &Val; 1460 1461 // In some cases the vector type is legal but the element type is illegal and 1462 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1463 // inserted value (the type does not need to match the vector element type). 1464 // Any extra bits introduced will be truncated away. 1465 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1466 TargetLowering::TypePromoteInteger) { 1467 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1468 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1469 Elt = ConstantInt::get(*getContext(), NewVal); 1470 } 1471 // In other cases the element type is illegal and needs to be expanded, for 1472 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1473 // the value into n parts and use a vector type with n-times the elements. 1474 // Then bitcast to the type requested. 1475 // Legalizing constants too early makes the DAGCombiner's job harder so we 1476 // only legalize if the DAG tells us we must produce legal types. 1477 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1478 TLI->getTypeAction(*getContext(), EltVT) == 1479 TargetLowering::TypeExpandInteger) { 1480 const APInt &NewVal = Elt->getValue(); 1481 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1482 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1483 1484 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1485 if (VT.isScalableVector()) { 1486 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1487 "Can only handle an even split!"); 1488 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1489 1490 SmallVector<SDValue, 2> ScalarParts; 1491 for (unsigned i = 0; i != Parts; ++i) 1492 ScalarParts.push_back(getConstant( 1493 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1494 ViaEltVT, isT, isO)); 1495 1496 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1497 } 1498 1499 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1500 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1501 1502 // Check the temporary vector is the correct size. If this fails then 1503 // getTypeToTransformTo() probably returned a type whose size (in bits) 1504 // isn't a power-of-2 factor of the requested type size. 1505 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1506 1507 SmallVector<SDValue, 2> EltParts; 1508 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1509 EltParts.push_back(getConstant( 1510 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1511 ViaEltVT, isT, isO)); 1512 1513 // EltParts is currently in little endian order. If we actually want 1514 // big-endian order then reverse it now. 1515 if (getDataLayout().isBigEndian()) 1516 std::reverse(EltParts.begin(), EltParts.end()); 1517 1518 // The elements must be reversed when the element order is different 1519 // to the endianness of the elements (because the BITCAST is itself a 1520 // vector shuffle in this situation). However, we do not need any code to 1521 // perform this reversal because getConstant() is producing a vector 1522 // splat. 1523 // This situation occurs in MIPS MSA. 1524 1525 SmallVector<SDValue, 8> Ops; 1526 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1527 llvm::append_range(Ops, EltParts); 1528 1529 SDValue V = 1530 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1531 return V; 1532 } 1533 1534 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1535 "APInt size does not match type size!"); 1536 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1537 FoldingSetNodeID ID; 1538 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1539 ID.AddPointer(Elt); 1540 ID.AddBoolean(isO); 1541 void *IP = nullptr; 1542 SDNode *N = nullptr; 1543 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1544 if (!VT.isVector()) 1545 return SDValue(N, 0); 1546 1547 if (!N) { 1548 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1549 CSEMap.InsertNode(N, IP); 1550 InsertNode(N); 1551 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1552 } 1553 1554 SDValue Result(N, 0); 1555 if (VT.isScalableVector()) 1556 Result = getSplatVector(VT, DL, Result); 1557 else if (VT.isVector()) 1558 Result = getSplatBuildVector(VT, DL, Result); 1559 1560 return Result; 1561 } 1562 1563 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1564 bool isTarget) { 1565 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1566 } 1567 1568 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1569 const SDLoc &DL, bool LegalTypes) { 1570 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1571 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1572 return getConstant(Val, DL, ShiftVT); 1573 } 1574 1575 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1576 bool isTarget) { 1577 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1578 } 1579 1580 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1581 bool isTarget) { 1582 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1583 } 1584 1585 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1586 EVT VT, bool isTarget) { 1587 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1588 1589 EVT EltVT = VT.getScalarType(); 1590 1591 // Do the map lookup using the actual bit pattern for the floating point 1592 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1593 // we don't have issues with SNANs. 1594 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1595 FoldingSetNodeID ID; 1596 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1597 ID.AddPointer(&V); 1598 void *IP = nullptr; 1599 SDNode *N = nullptr; 1600 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1601 if (!VT.isVector()) 1602 return SDValue(N, 0); 1603 1604 if (!N) { 1605 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1606 CSEMap.InsertNode(N, IP); 1607 InsertNode(N); 1608 } 1609 1610 SDValue Result(N, 0); 1611 if (VT.isScalableVector()) 1612 Result = getSplatVector(VT, DL, Result); 1613 else if (VT.isVector()) 1614 Result = getSplatBuildVector(VT, DL, Result); 1615 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1616 return Result; 1617 } 1618 1619 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1620 bool isTarget) { 1621 EVT EltVT = VT.getScalarType(); 1622 if (EltVT == MVT::f32) 1623 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1624 if (EltVT == MVT::f64) 1625 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1626 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1627 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1628 bool Ignored; 1629 APFloat APF = APFloat(Val); 1630 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1631 &Ignored); 1632 return getConstantFP(APF, DL, VT, isTarget); 1633 } 1634 llvm_unreachable("Unsupported type in getConstantFP"); 1635 } 1636 1637 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1638 EVT VT, int64_t Offset, bool isTargetGA, 1639 unsigned TargetFlags) { 1640 assert((TargetFlags == 0 || isTargetGA) && 1641 "Cannot set target flags on target-independent globals"); 1642 1643 // Truncate (with sign-extension) the offset value to the pointer size. 1644 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1645 if (BitWidth < 64) 1646 Offset = SignExtend64(Offset, BitWidth); 1647 1648 unsigned Opc; 1649 if (GV->isThreadLocal()) 1650 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1651 else 1652 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1653 1654 FoldingSetNodeID ID; 1655 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1656 ID.AddPointer(GV); 1657 ID.AddInteger(Offset); 1658 ID.AddInteger(TargetFlags); 1659 void *IP = nullptr; 1660 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1661 return SDValue(E, 0); 1662 1663 auto *N = newSDNode<GlobalAddressSDNode>( 1664 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1665 CSEMap.InsertNode(N, IP); 1666 InsertNode(N); 1667 return SDValue(N, 0); 1668 } 1669 1670 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1671 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1672 FoldingSetNodeID ID; 1673 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1674 ID.AddInteger(FI); 1675 void *IP = nullptr; 1676 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1677 return SDValue(E, 0); 1678 1679 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1680 CSEMap.InsertNode(N, IP); 1681 InsertNode(N); 1682 return SDValue(N, 0); 1683 } 1684 1685 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1686 unsigned TargetFlags) { 1687 assert((TargetFlags == 0 || isTarget) && 1688 "Cannot set target flags on target-independent jump tables"); 1689 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1690 FoldingSetNodeID ID; 1691 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1692 ID.AddInteger(JTI); 1693 ID.AddInteger(TargetFlags); 1694 void *IP = nullptr; 1695 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1696 return SDValue(E, 0); 1697 1698 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1699 CSEMap.InsertNode(N, IP); 1700 InsertNode(N); 1701 return SDValue(N, 0); 1702 } 1703 1704 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1705 MaybeAlign Alignment, int Offset, 1706 bool isTarget, unsigned TargetFlags) { 1707 assert((TargetFlags == 0 || isTarget) && 1708 "Cannot set target flags on target-independent globals"); 1709 if (!Alignment) 1710 Alignment = shouldOptForSize() 1711 ? getDataLayout().getABITypeAlign(C->getType()) 1712 : getDataLayout().getPrefTypeAlign(C->getType()); 1713 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1714 FoldingSetNodeID ID; 1715 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1716 ID.AddInteger(Alignment->value()); 1717 ID.AddInteger(Offset); 1718 ID.AddPointer(C); 1719 ID.AddInteger(TargetFlags); 1720 void *IP = nullptr; 1721 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1722 return SDValue(E, 0); 1723 1724 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1725 TargetFlags); 1726 CSEMap.InsertNode(N, IP); 1727 InsertNode(N); 1728 SDValue V = SDValue(N, 0); 1729 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1730 return V; 1731 } 1732 1733 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1734 MaybeAlign Alignment, int Offset, 1735 bool isTarget, unsigned TargetFlags) { 1736 assert((TargetFlags == 0 || isTarget) && 1737 "Cannot set target flags on target-independent globals"); 1738 if (!Alignment) 1739 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1740 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1741 FoldingSetNodeID ID; 1742 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1743 ID.AddInteger(Alignment->value()); 1744 ID.AddInteger(Offset); 1745 C->addSelectionDAGCSEId(ID); 1746 ID.AddInteger(TargetFlags); 1747 void *IP = nullptr; 1748 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1749 return SDValue(E, 0); 1750 1751 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1752 TargetFlags); 1753 CSEMap.InsertNode(N, IP); 1754 InsertNode(N); 1755 return SDValue(N, 0); 1756 } 1757 1758 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1759 unsigned TargetFlags) { 1760 FoldingSetNodeID ID; 1761 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1762 ID.AddInteger(Index); 1763 ID.AddInteger(Offset); 1764 ID.AddInteger(TargetFlags); 1765 void *IP = nullptr; 1766 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1767 return SDValue(E, 0); 1768 1769 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1770 CSEMap.InsertNode(N, IP); 1771 InsertNode(N); 1772 return SDValue(N, 0); 1773 } 1774 1775 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1776 FoldingSetNodeID ID; 1777 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1778 ID.AddPointer(MBB); 1779 void *IP = nullptr; 1780 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1781 return SDValue(E, 0); 1782 1783 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1784 CSEMap.InsertNode(N, IP); 1785 InsertNode(N); 1786 return SDValue(N, 0); 1787 } 1788 1789 SDValue SelectionDAG::getValueType(EVT VT) { 1790 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1791 ValueTypeNodes.size()) 1792 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1793 1794 SDNode *&N = VT.isExtended() ? 1795 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1796 1797 if (N) return SDValue(N, 0); 1798 N = newSDNode<VTSDNode>(VT); 1799 InsertNode(N); 1800 return SDValue(N, 0); 1801 } 1802 1803 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1804 SDNode *&N = ExternalSymbols[Sym]; 1805 if (N) return SDValue(N, 0); 1806 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1807 InsertNode(N); 1808 return SDValue(N, 0); 1809 } 1810 1811 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1812 SDNode *&N = MCSymbols[Sym]; 1813 if (N) 1814 return SDValue(N, 0); 1815 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1816 InsertNode(N); 1817 return SDValue(N, 0); 1818 } 1819 1820 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1821 unsigned TargetFlags) { 1822 SDNode *&N = 1823 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1824 if (N) return SDValue(N, 0); 1825 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1826 InsertNode(N); 1827 return SDValue(N, 0); 1828 } 1829 1830 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1831 if ((unsigned)Cond >= CondCodeNodes.size()) 1832 CondCodeNodes.resize(Cond+1); 1833 1834 if (!CondCodeNodes[Cond]) { 1835 auto *N = newSDNode<CondCodeSDNode>(Cond); 1836 CondCodeNodes[Cond] = N; 1837 InsertNode(N); 1838 } 1839 1840 return SDValue(CondCodeNodes[Cond], 0); 1841 } 1842 1843 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1844 APInt One(ResVT.getScalarSizeInBits(), 1); 1845 return getStepVector(DL, ResVT, One); 1846 } 1847 1848 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1849 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1850 if (ResVT.isScalableVector()) 1851 return getNode( 1852 ISD::STEP_VECTOR, DL, ResVT, 1853 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1854 1855 SmallVector<SDValue, 16> OpsStepConstants; 1856 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1857 OpsStepConstants.push_back( 1858 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1859 return getBuildVector(ResVT, DL, OpsStepConstants); 1860 } 1861 1862 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1863 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1864 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1865 std::swap(N1, N2); 1866 ShuffleVectorSDNode::commuteMask(M); 1867 } 1868 1869 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1870 SDValue N2, ArrayRef<int> Mask) { 1871 assert(VT.getVectorNumElements() == Mask.size() && 1872 "Must have the same number of vector elements as mask elements!"); 1873 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1874 "Invalid VECTOR_SHUFFLE"); 1875 1876 // Canonicalize shuffle undef, undef -> undef 1877 if (N1.isUndef() && N2.isUndef()) 1878 return getUNDEF(VT); 1879 1880 // Validate that all indices in Mask are within the range of the elements 1881 // input to the shuffle. 1882 int NElts = Mask.size(); 1883 assert(llvm::all_of(Mask, 1884 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1885 "Index out of range"); 1886 1887 // Copy the mask so we can do any needed cleanup. 1888 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1889 1890 // Canonicalize shuffle v, v -> v, undef 1891 if (N1 == N2) { 1892 N2 = getUNDEF(VT); 1893 for (int i = 0; i != NElts; ++i) 1894 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1895 } 1896 1897 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1898 if (N1.isUndef()) 1899 commuteShuffle(N1, N2, MaskVec); 1900 1901 if (TLI->hasVectorBlend()) { 1902 // If shuffling a splat, try to blend the splat instead. We do this here so 1903 // that even when this arises during lowering we don't have to re-handle it. 1904 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1905 BitVector UndefElements; 1906 SDValue Splat = BV->getSplatValue(&UndefElements); 1907 if (!Splat) 1908 return; 1909 1910 for (int i = 0; i < NElts; ++i) { 1911 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1912 continue; 1913 1914 // If this input comes from undef, mark it as such. 1915 if (UndefElements[MaskVec[i] - Offset]) { 1916 MaskVec[i] = -1; 1917 continue; 1918 } 1919 1920 // If we can blend a non-undef lane, use that instead. 1921 if (!UndefElements[i]) 1922 MaskVec[i] = i + Offset; 1923 } 1924 }; 1925 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1926 BlendSplat(N1BV, 0); 1927 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1928 BlendSplat(N2BV, NElts); 1929 } 1930 1931 // Canonicalize all index into lhs, -> shuffle lhs, undef 1932 // Canonicalize all index into rhs, -> shuffle rhs, undef 1933 bool AllLHS = true, AllRHS = true; 1934 bool N2Undef = N2.isUndef(); 1935 for (int i = 0; i != NElts; ++i) { 1936 if (MaskVec[i] >= NElts) { 1937 if (N2Undef) 1938 MaskVec[i] = -1; 1939 else 1940 AllLHS = false; 1941 } else if (MaskVec[i] >= 0) { 1942 AllRHS = false; 1943 } 1944 } 1945 if (AllLHS && AllRHS) 1946 return getUNDEF(VT); 1947 if (AllLHS && !N2Undef) 1948 N2 = getUNDEF(VT); 1949 if (AllRHS) { 1950 N1 = getUNDEF(VT); 1951 commuteShuffle(N1, N2, MaskVec); 1952 } 1953 // Reset our undef status after accounting for the mask. 1954 N2Undef = N2.isUndef(); 1955 // Re-check whether both sides ended up undef. 1956 if (N1.isUndef() && N2Undef) 1957 return getUNDEF(VT); 1958 1959 // If Identity shuffle return that node. 1960 bool Identity = true, AllSame = true; 1961 for (int i = 0; i != NElts; ++i) { 1962 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1963 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1964 } 1965 if (Identity && NElts) 1966 return N1; 1967 1968 // Shuffling a constant splat doesn't change the result. 1969 if (N2Undef) { 1970 SDValue V = N1; 1971 1972 // Look through any bitcasts. We check that these don't change the number 1973 // (and size) of elements and just changes their types. 1974 while (V.getOpcode() == ISD::BITCAST) 1975 V = V->getOperand(0); 1976 1977 // A splat should always show up as a build vector node. 1978 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1979 BitVector UndefElements; 1980 SDValue Splat = BV->getSplatValue(&UndefElements); 1981 // If this is a splat of an undef, shuffling it is also undef. 1982 if (Splat && Splat.isUndef()) 1983 return getUNDEF(VT); 1984 1985 bool SameNumElts = 1986 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1987 1988 // We only have a splat which can skip shuffles if there is a splatted 1989 // value and no undef lanes rearranged by the shuffle. 1990 if (Splat && UndefElements.none()) { 1991 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1992 // number of elements match or the value splatted is a zero constant. 1993 if (SameNumElts) 1994 return N1; 1995 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1996 if (C->isZero()) 1997 return N1; 1998 } 1999 2000 // If the shuffle itself creates a splat, build the vector directly. 2001 if (AllSame && SameNumElts) { 2002 EVT BuildVT = BV->getValueType(0); 2003 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2004 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2005 2006 // We may have jumped through bitcasts, so the type of the 2007 // BUILD_VECTOR may not match the type of the shuffle. 2008 if (BuildVT != VT) 2009 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2010 return NewBV; 2011 } 2012 } 2013 } 2014 2015 FoldingSetNodeID ID; 2016 SDValue Ops[2] = { N1, N2 }; 2017 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2018 for (int i = 0; i != NElts; ++i) 2019 ID.AddInteger(MaskVec[i]); 2020 2021 void* IP = nullptr; 2022 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2023 return SDValue(E, 0); 2024 2025 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2026 // SDNode doesn't have access to it. This memory will be "leaked" when 2027 // the node is deallocated, but recovered when the NodeAllocator is released. 2028 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2029 llvm::copy(MaskVec, MaskAlloc); 2030 2031 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2032 dl.getDebugLoc(), MaskAlloc); 2033 createOperands(N, Ops); 2034 2035 CSEMap.InsertNode(N, IP); 2036 InsertNode(N); 2037 SDValue V = SDValue(N, 0); 2038 NewSDValueDbgMsg(V, "Creating new node: ", this); 2039 return V; 2040 } 2041 2042 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2043 EVT VT = SV.getValueType(0); 2044 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2045 ShuffleVectorSDNode::commuteMask(MaskVec); 2046 2047 SDValue Op0 = SV.getOperand(0); 2048 SDValue Op1 = SV.getOperand(1); 2049 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2050 } 2051 2052 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2053 FoldingSetNodeID ID; 2054 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2055 ID.AddInteger(RegNo); 2056 void *IP = nullptr; 2057 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2058 return SDValue(E, 0); 2059 2060 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2061 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2062 CSEMap.InsertNode(N, IP); 2063 InsertNode(N); 2064 return SDValue(N, 0); 2065 } 2066 2067 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2068 FoldingSetNodeID ID; 2069 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2070 ID.AddPointer(RegMask); 2071 void *IP = nullptr; 2072 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2073 return SDValue(E, 0); 2074 2075 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2076 CSEMap.InsertNode(N, IP); 2077 InsertNode(N); 2078 return SDValue(N, 0); 2079 } 2080 2081 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2082 MCSymbol *Label) { 2083 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2084 } 2085 2086 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2087 SDValue Root, MCSymbol *Label) { 2088 FoldingSetNodeID ID; 2089 SDValue Ops[] = { Root }; 2090 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2091 ID.AddPointer(Label); 2092 void *IP = nullptr; 2093 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2094 return SDValue(E, 0); 2095 2096 auto *N = 2097 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2098 createOperands(N, Ops); 2099 2100 CSEMap.InsertNode(N, IP); 2101 InsertNode(N); 2102 return SDValue(N, 0); 2103 } 2104 2105 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2106 int64_t Offset, bool isTarget, 2107 unsigned TargetFlags) { 2108 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2109 2110 FoldingSetNodeID ID; 2111 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2112 ID.AddPointer(BA); 2113 ID.AddInteger(Offset); 2114 ID.AddInteger(TargetFlags); 2115 void *IP = nullptr; 2116 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2117 return SDValue(E, 0); 2118 2119 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2120 CSEMap.InsertNode(N, IP); 2121 InsertNode(N); 2122 return SDValue(N, 0); 2123 } 2124 2125 SDValue SelectionDAG::getSrcValue(const Value *V) { 2126 FoldingSetNodeID ID; 2127 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2128 ID.AddPointer(V); 2129 2130 void *IP = nullptr; 2131 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2132 return SDValue(E, 0); 2133 2134 auto *N = newSDNode<SrcValueSDNode>(V); 2135 CSEMap.InsertNode(N, IP); 2136 InsertNode(N); 2137 return SDValue(N, 0); 2138 } 2139 2140 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2141 FoldingSetNodeID ID; 2142 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2143 ID.AddPointer(MD); 2144 2145 void *IP = nullptr; 2146 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2147 return SDValue(E, 0); 2148 2149 auto *N = newSDNode<MDNodeSDNode>(MD); 2150 CSEMap.InsertNode(N, IP); 2151 InsertNode(N); 2152 return SDValue(N, 0); 2153 } 2154 2155 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2156 if (VT == V.getValueType()) 2157 return V; 2158 2159 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2160 } 2161 2162 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2163 unsigned SrcAS, unsigned DestAS) { 2164 SDValue Ops[] = {Ptr}; 2165 FoldingSetNodeID ID; 2166 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2167 ID.AddInteger(SrcAS); 2168 ID.AddInteger(DestAS); 2169 2170 void *IP = nullptr; 2171 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2172 return SDValue(E, 0); 2173 2174 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2175 VT, SrcAS, DestAS); 2176 createOperands(N, Ops); 2177 2178 CSEMap.InsertNode(N, IP); 2179 InsertNode(N); 2180 return SDValue(N, 0); 2181 } 2182 2183 SDValue SelectionDAG::getFreeze(SDValue V) { 2184 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2185 } 2186 2187 /// getShiftAmountOperand - Return the specified value casted to 2188 /// the target's desired shift amount type. 2189 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2190 EVT OpTy = Op.getValueType(); 2191 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2192 if (OpTy == ShTy || OpTy.isVector()) return Op; 2193 2194 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2195 } 2196 2197 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2198 SDLoc dl(Node); 2199 const TargetLowering &TLI = getTargetLoweringInfo(); 2200 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2201 EVT VT = Node->getValueType(0); 2202 SDValue Tmp1 = Node->getOperand(0); 2203 SDValue Tmp2 = Node->getOperand(1); 2204 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2205 2206 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2207 Tmp2, MachinePointerInfo(V)); 2208 SDValue VAList = VAListLoad; 2209 2210 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2211 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2212 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2213 2214 VAList = 2215 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2216 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2217 } 2218 2219 // Increment the pointer, VAList, to the next vaarg 2220 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2221 getConstant(getDataLayout().getTypeAllocSize( 2222 VT.getTypeForEVT(*getContext())), 2223 dl, VAList.getValueType())); 2224 // Store the incremented VAList to the legalized pointer 2225 Tmp1 = 2226 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2227 // Load the actual argument out of the pointer VAList 2228 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2229 } 2230 2231 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2232 SDLoc dl(Node); 2233 const TargetLowering &TLI = getTargetLoweringInfo(); 2234 // This defaults to loading a pointer from the input and storing it to the 2235 // output, returning the chain. 2236 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2237 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2238 SDValue Tmp1 = 2239 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2240 Node->getOperand(2), MachinePointerInfo(VS)); 2241 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2242 MachinePointerInfo(VD)); 2243 } 2244 2245 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2246 const DataLayout &DL = getDataLayout(); 2247 Type *Ty = VT.getTypeForEVT(*getContext()); 2248 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2249 2250 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2251 return RedAlign; 2252 2253 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2254 const Align StackAlign = TFI->getStackAlign(); 2255 2256 // See if we can choose a smaller ABI alignment in cases where it's an 2257 // illegal vector type that will get broken down. 2258 if (RedAlign > StackAlign) { 2259 EVT IntermediateVT; 2260 MVT RegisterVT; 2261 unsigned NumIntermediates; 2262 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2263 NumIntermediates, RegisterVT); 2264 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2265 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2266 if (RedAlign2 < RedAlign) 2267 RedAlign = RedAlign2; 2268 } 2269 2270 return RedAlign; 2271 } 2272 2273 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2274 MachineFrameInfo &MFI = MF->getFrameInfo(); 2275 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2276 int StackID = 0; 2277 if (Bytes.isScalable()) 2278 StackID = TFI->getStackIDForScalableVectors(); 2279 // The stack id gives an indication of whether the object is scalable or 2280 // not, so it's safe to pass in the minimum size here. 2281 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2282 false, nullptr, StackID); 2283 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2284 } 2285 2286 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2287 Type *Ty = VT.getTypeForEVT(*getContext()); 2288 Align StackAlign = 2289 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2290 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2291 } 2292 2293 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2294 TypeSize VT1Size = VT1.getStoreSize(); 2295 TypeSize VT2Size = VT2.getStoreSize(); 2296 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2297 "Don't know how to choose the maximum size when creating a stack " 2298 "temporary"); 2299 TypeSize Bytes = 2300 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2301 2302 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2303 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2304 const DataLayout &DL = getDataLayout(); 2305 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2306 return CreateStackTemporary(Bytes, Align); 2307 } 2308 2309 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2310 ISD::CondCode Cond, const SDLoc &dl) { 2311 EVT OpVT = N1.getValueType(); 2312 2313 // These setcc operations always fold. 2314 switch (Cond) { 2315 default: break; 2316 case ISD::SETFALSE: 2317 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2318 case ISD::SETTRUE: 2319 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2320 2321 case ISD::SETOEQ: 2322 case ISD::SETOGT: 2323 case ISD::SETOGE: 2324 case ISD::SETOLT: 2325 case ISD::SETOLE: 2326 case ISD::SETONE: 2327 case ISD::SETO: 2328 case ISD::SETUO: 2329 case ISD::SETUEQ: 2330 case ISD::SETUNE: 2331 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2332 break; 2333 } 2334 2335 if (OpVT.isInteger()) { 2336 // For EQ and NE, we can always pick a value for the undef to make the 2337 // predicate pass or fail, so we can return undef. 2338 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2339 // icmp eq/ne X, undef -> undef. 2340 if ((N1.isUndef() || N2.isUndef()) && 2341 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2342 return getUNDEF(VT); 2343 2344 // If both operands are undef, we can return undef for int comparison. 2345 // icmp undef, undef -> undef. 2346 if (N1.isUndef() && N2.isUndef()) 2347 return getUNDEF(VT); 2348 2349 // icmp X, X -> true/false 2350 // icmp X, undef -> true/false because undef could be X. 2351 if (N1 == N2) 2352 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2353 } 2354 2355 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2356 const APInt &C2 = N2C->getAPIntValue(); 2357 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2358 const APInt &C1 = N1C->getAPIntValue(); 2359 2360 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2361 dl, VT, OpVT); 2362 } 2363 } 2364 2365 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2366 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2367 2368 if (N1CFP && N2CFP) { 2369 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2370 switch (Cond) { 2371 default: break; 2372 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2373 return getUNDEF(VT); 2374 LLVM_FALLTHROUGH; 2375 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2376 OpVT); 2377 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2378 return getUNDEF(VT); 2379 LLVM_FALLTHROUGH; 2380 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2381 R==APFloat::cmpLessThan, dl, VT, 2382 OpVT); 2383 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2384 return getUNDEF(VT); 2385 LLVM_FALLTHROUGH; 2386 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2387 OpVT); 2388 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2389 return getUNDEF(VT); 2390 LLVM_FALLTHROUGH; 2391 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2392 VT, OpVT); 2393 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2394 return getUNDEF(VT); 2395 LLVM_FALLTHROUGH; 2396 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2397 R==APFloat::cmpEqual, dl, VT, 2398 OpVT); 2399 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2400 return getUNDEF(VT); 2401 LLVM_FALLTHROUGH; 2402 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2403 R==APFloat::cmpEqual, dl, VT, OpVT); 2404 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2405 OpVT); 2406 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2407 OpVT); 2408 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2409 R==APFloat::cmpEqual, dl, VT, 2410 OpVT); 2411 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2412 OpVT); 2413 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2414 R==APFloat::cmpLessThan, dl, VT, 2415 OpVT); 2416 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2417 R==APFloat::cmpUnordered, dl, VT, 2418 OpVT); 2419 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2420 VT, OpVT); 2421 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2422 OpVT); 2423 } 2424 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2425 // Ensure that the constant occurs on the RHS. 2426 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2427 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2428 return SDValue(); 2429 return getSetCC(dl, VT, N2, N1, SwappedCond); 2430 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2431 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2432 // If an operand is known to be a nan (or undef that could be a nan), we can 2433 // fold it. 2434 // Choosing NaN for the undef will always make unordered comparison succeed 2435 // and ordered comparison fails. 2436 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2437 switch (ISD::getUnorderedFlavor(Cond)) { 2438 default: 2439 llvm_unreachable("Unknown flavor!"); 2440 case 0: // Known false. 2441 return getBoolConstant(false, dl, VT, OpVT); 2442 case 1: // Known true. 2443 return getBoolConstant(true, dl, VT, OpVT); 2444 case 2: // Undefined. 2445 return getUNDEF(VT); 2446 } 2447 } 2448 2449 // Could not fold it. 2450 return SDValue(); 2451 } 2452 2453 /// See if the specified operand can be simplified with the knowledge that only 2454 /// the bits specified by DemandedBits are used. 2455 /// TODO: really we should be making this into the DAG equivalent of 2456 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2457 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2458 EVT VT = V.getValueType(); 2459 2460 if (VT.isScalableVector()) 2461 return SDValue(); 2462 2463 APInt DemandedElts = VT.isVector() 2464 ? APInt::getAllOnes(VT.getVectorNumElements()) 2465 : APInt(1, 1); 2466 return GetDemandedBits(V, DemandedBits, DemandedElts); 2467 } 2468 2469 /// See if the specified operand can be simplified with the knowledge that only 2470 /// the bits specified by DemandedBits are used in the elements specified by 2471 /// DemandedElts. 2472 /// TODO: really we should be making this into the DAG equivalent of 2473 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2474 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2475 const APInt &DemandedElts) { 2476 switch (V.getOpcode()) { 2477 default: 2478 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2479 *this); 2480 case ISD::Constant: { 2481 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2482 APInt NewVal = CVal & DemandedBits; 2483 if (NewVal != CVal) 2484 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2485 break; 2486 } 2487 case ISD::SRL: 2488 // Only look at single-use SRLs. 2489 if (!V.getNode()->hasOneUse()) 2490 break; 2491 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2492 // See if we can recursively simplify the LHS. 2493 unsigned Amt = RHSC->getZExtValue(); 2494 2495 // Watch out for shift count overflow though. 2496 if (Amt >= DemandedBits.getBitWidth()) 2497 break; 2498 APInt SrcDemandedBits = DemandedBits << Amt; 2499 if (SDValue SimplifyLHS = 2500 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2501 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2502 V.getOperand(1)); 2503 } 2504 break; 2505 } 2506 return SDValue(); 2507 } 2508 2509 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2510 /// use this predicate to simplify operations downstream. 2511 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2512 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2513 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2514 } 2515 2516 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2517 /// this predicate to simplify operations downstream. Mask is known to be zero 2518 /// for bits that V cannot have. 2519 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2520 unsigned Depth) const { 2521 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2522 } 2523 2524 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2525 /// DemandedElts. We use this predicate to simplify operations downstream. 2526 /// Mask is known to be zero for bits that V cannot have. 2527 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2528 const APInt &DemandedElts, 2529 unsigned Depth) const { 2530 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2531 } 2532 2533 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2534 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2535 unsigned Depth) const { 2536 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2537 } 2538 2539 /// isSplatValue - Return true if the vector V has the same value 2540 /// across all DemandedElts. For scalable vectors it does not make 2541 /// sense to specify which elements are demanded or undefined, therefore 2542 /// they are simply ignored. 2543 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2544 APInt &UndefElts, unsigned Depth) const { 2545 unsigned Opcode = V.getOpcode(); 2546 EVT VT = V.getValueType(); 2547 assert(VT.isVector() && "Vector type expected"); 2548 2549 if (!VT.isScalableVector() && !DemandedElts) 2550 return false; // No demanded elts, better to assume we don't know anything. 2551 2552 if (Depth >= MaxRecursionDepth) 2553 return false; // Limit search depth. 2554 2555 // Deal with some common cases here that work for both fixed and scalable 2556 // vector types. 2557 switch (Opcode) { 2558 case ISD::SPLAT_VECTOR: 2559 UndefElts = V.getOperand(0).isUndef() 2560 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2561 : APInt(DemandedElts.getBitWidth(), 0); 2562 return true; 2563 case ISD::ADD: 2564 case ISD::SUB: 2565 case ISD::AND: 2566 case ISD::XOR: 2567 case ISD::OR: { 2568 APInt UndefLHS, UndefRHS; 2569 SDValue LHS = V.getOperand(0); 2570 SDValue RHS = V.getOperand(1); 2571 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2572 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2573 UndefElts = UndefLHS | UndefRHS; 2574 return true; 2575 } 2576 return false; 2577 } 2578 case ISD::ABS: 2579 case ISD::TRUNCATE: 2580 case ISD::SIGN_EXTEND: 2581 case ISD::ZERO_EXTEND: 2582 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2583 default: 2584 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2585 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2586 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth); 2587 break; 2588 } 2589 2590 // We don't support other cases than those above for scalable vectors at 2591 // the moment. 2592 if (VT.isScalableVector()) 2593 return false; 2594 2595 unsigned NumElts = VT.getVectorNumElements(); 2596 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2597 UndefElts = APInt::getZero(NumElts); 2598 2599 switch (Opcode) { 2600 case ISD::BUILD_VECTOR: { 2601 SDValue Scl; 2602 for (unsigned i = 0; i != NumElts; ++i) { 2603 SDValue Op = V.getOperand(i); 2604 if (Op.isUndef()) { 2605 UndefElts.setBit(i); 2606 continue; 2607 } 2608 if (!DemandedElts[i]) 2609 continue; 2610 if (Scl && Scl != Op) 2611 return false; 2612 Scl = Op; 2613 } 2614 return true; 2615 } 2616 case ISD::VECTOR_SHUFFLE: { 2617 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2618 APInt DemandedLHS = APInt::getNullValue(NumElts); 2619 APInt DemandedRHS = APInt::getNullValue(NumElts); 2620 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2621 for (int i = 0; i != (int)NumElts; ++i) { 2622 int M = Mask[i]; 2623 if (M < 0) { 2624 UndefElts.setBit(i); 2625 continue; 2626 } 2627 if (!DemandedElts[i]) 2628 continue; 2629 if (M < (int)NumElts) 2630 DemandedLHS.setBit(M); 2631 else 2632 DemandedRHS.setBit(M - NumElts); 2633 } 2634 2635 // If we aren't demanding either op, assume there's no splat. 2636 // If we are demanding both ops, assume there's no splat. 2637 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2638 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2639 return false; 2640 2641 // See if the demanded elts of the source op is a splat or we only demand 2642 // one element, which should always be a splat. 2643 // TODO: Handle source ops splats with undefs. 2644 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2645 APInt SrcUndefs; 2646 return (SrcElts.countPopulation() == 1) || 2647 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2648 (SrcElts & SrcUndefs).isZero()); 2649 }; 2650 if (!DemandedLHS.isZero()) 2651 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2652 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2653 } 2654 case ISD::EXTRACT_SUBVECTOR: { 2655 // Offset the demanded elts by the subvector index. 2656 SDValue Src = V.getOperand(0); 2657 // We don't support scalable vectors at the moment. 2658 if (Src.getValueType().isScalableVector()) 2659 return false; 2660 uint64_t Idx = V.getConstantOperandVal(1); 2661 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2662 APInt UndefSrcElts; 2663 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2664 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2665 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2666 return true; 2667 } 2668 break; 2669 } 2670 case ISD::ANY_EXTEND_VECTOR_INREG: 2671 case ISD::SIGN_EXTEND_VECTOR_INREG: 2672 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2673 // Widen the demanded elts by the src element count. 2674 SDValue Src = V.getOperand(0); 2675 // We don't support scalable vectors at the moment. 2676 if (Src.getValueType().isScalableVector()) 2677 return false; 2678 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2679 APInt UndefSrcElts; 2680 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 2681 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2682 UndefElts = UndefSrcElts.truncOrSelf(NumElts); 2683 return true; 2684 } 2685 break; 2686 } 2687 case ISD::BITCAST: { 2688 SDValue Src = V.getOperand(0); 2689 EVT SrcVT = Src.getValueType(); 2690 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2691 unsigned BitWidth = VT.getScalarSizeInBits(); 2692 2693 // Ignore bitcasts from unsupported types. 2694 // TODO: Add fp support? 2695 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2696 break; 2697 2698 // Bitcast 'small element' vector to 'large element' vector. 2699 if ((BitWidth % SrcBitWidth) == 0) { 2700 // See if each sub element is a splat. 2701 unsigned Scale = BitWidth / SrcBitWidth; 2702 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2703 APInt ScaledDemandedElts = 2704 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2705 for (unsigned I = 0; I != Scale; ++I) { 2706 APInt SubUndefElts; 2707 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2708 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2709 SubDemandedElts &= ScaledDemandedElts; 2710 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2711 return false; 2712 // TODO: Add support for merging sub undef elements. 2713 if (SubDemandedElts.isSubsetOf(SubUndefElts)) 2714 return false; 2715 } 2716 return true; 2717 } 2718 break; 2719 } 2720 } 2721 2722 return false; 2723 } 2724 2725 /// Helper wrapper to main isSplatValue function. 2726 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2727 EVT VT = V.getValueType(); 2728 assert(VT.isVector() && "Vector type expected"); 2729 2730 APInt UndefElts; 2731 APInt DemandedElts; 2732 2733 // For now we don't support this with scalable vectors. 2734 if (!VT.isScalableVector()) 2735 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2736 return isSplatValue(V, DemandedElts, UndefElts) && 2737 (AllowUndefs || !UndefElts); 2738 } 2739 2740 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2741 V = peekThroughExtractSubvectors(V); 2742 2743 EVT VT = V.getValueType(); 2744 unsigned Opcode = V.getOpcode(); 2745 switch (Opcode) { 2746 default: { 2747 APInt UndefElts; 2748 APInt DemandedElts; 2749 2750 if (!VT.isScalableVector()) 2751 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2752 2753 if (isSplatValue(V, DemandedElts, UndefElts)) { 2754 if (VT.isScalableVector()) { 2755 // DemandedElts and UndefElts are ignored for scalable vectors, since 2756 // the only supported cases are SPLAT_VECTOR nodes. 2757 SplatIdx = 0; 2758 } else { 2759 // Handle case where all demanded elements are UNDEF. 2760 if (DemandedElts.isSubsetOf(UndefElts)) { 2761 SplatIdx = 0; 2762 return getUNDEF(VT); 2763 } 2764 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2765 } 2766 return V; 2767 } 2768 break; 2769 } 2770 case ISD::SPLAT_VECTOR: 2771 SplatIdx = 0; 2772 return V; 2773 case ISD::VECTOR_SHUFFLE: { 2774 if (VT.isScalableVector()) 2775 return SDValue(); 2776 2777 // Check if this is a shuffle node doing a splat. 2778 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2779 // getTargetVShiftNode currently struggles without the splat source. 2780 auto *SVN = cast<ShuffleVectorSDNode>(V); 2781 if (!SVN->isSplat()) 2782 break; 2783 int Idx = SVN->getSplatIndex(); 2784 int NumElts = V.getValueType().getVectorNumElements(); 2785 SplatIdx = Idx % NumElts; 2786 return V.getOperand(Idx / NumElts); 2787 } 2788 } 2789 2790 return SDValue(); 2791 } 2792 2793 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2794 int SplatIdx; 2795 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2796 EVT SVT = SrcVector.getValueType().getScalarType(); 2797 EVT LegalSVT = SVT; 2798 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2799 if (!SVT.isInteger()) 2800 return SDValue(); 2801 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2802 if (LegalSVT.bitsLT(SVT)) 2803 return SDValue(); 2804 } 2805 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2806 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2807 } 2808 return SDValue(); 2809 } 2810 2811 const APInt * 2812 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2813 const APInt &DemandedElts) const { 2814 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2815 V.getOpcode() == ISD::SRA) && 2816 "Unknown shift node"); 2817 unsigned BitWidth = V.getScalarValueSizeInBits(); 2818 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2819 // Shifting more than the bitwidth is not valid. 2820 const APInt &ShAmt = SA->getAPIntValue(); 2821 if (ShAmt.ult(BitWidth)) 2822 return &ShAmt; 2823 } 2824 return nullptr; 2825 } 2826 2827 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2828 SDValue V, const APInt &DemandedElts) const { 2829 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2830 V.getOpcode() == ISD::SRA) && 2831 "Unknown shift node"); 2832 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2833 return ValidAmt; 2834 unsigned BitWidth = V.getScalarValueSizeInBits(); 2835 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2836 if (!BV) 2837 return nullptr; 2838 const APInt *MinShAmt = nullptr; 2839 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2840 if (!DemandedElts[i]) 2841 continue; 2842 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2843 if (!SA) 2844 return nullptr; 2845 // Shifting more than the bitwidth is not valid. 2846 const APInt &ShAmt = SA->getAPIntValue(); 2847 if (ShAmt.uge(BitWidth)) 2848 return nullptr; 2849 if (MinShAmt && MinShAmt->ule(ShAmt)) 2850 continue; 2851 MinShAmt = &ShAmt; 2852 } 2853 return MinShAmt; 2854 } 2855 2856 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2857 SDValue V, const APInt &DemandedElts) const { 2858 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2859 V.getOpcode() == ISD::SRA) && 2860 "Unknown shift node"); 2861 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2862 return ValidAmt; 2863 unsigned BitWidth = V.getScalarValueSizeInBits(); 2864 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2865 if (!BV) 2866 return nullptr; 2867 const APInt *MaxShAmt = nullptr; 2868 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2869 if (!DemandedElts[i]) 2870 continue; 2871 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2872 if (!SA) 2873 return nullptr; 2874 // Shifting more than the bitwidth is not valid. 2875 const APInt &ShAmt = SA->getAPIntValue(); 2876 if (ShAmt.uge(BitWidth)) 2877 return nullptr; 2878 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2879 continue; 2880 MaxShAmt = &ShAmt; 2881 } 2882 return MaxShAmt; 2883 } 2884 2885 /// Determine which bits of Op are known to be either zero or one and return 2886 /// them in Known. For vectors, the known bits are those that are shared by 2887 /// every vector element. 2888 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2889 EVT VT = Op.getValueType(); 2890 2891 // TOOD: Until we have a plan for how to represent demanded elements for 2892 // scalable vectors, we can just bail out for now. 2893 if (Op.getValueType().isScalableVector()) { 2894 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2895 return KnownBits(BitWidth); 2896 } 2897 2898 APInt DemandedElts = VT.isVector() 2899 ? APInt::getAllOnes(VT.getVectorNumElements()) 2900 : APInt(1, 1); 2901 return computeKnownBits(Op, DemandedElts, Depth); 2902 } 2903 2904 /// Determine which bits of Op are known to be either zero or one and return 2905 /// them in Known. The DemandedElts argument allows us to only collect the known 2906 /// bits that are shared by the requested vector elements. 2907 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2908 unsigned Depth) const { 2909 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2910 2911 KnownBits Known(BitWidth); // Don't know anything. 2912 2913 // TOOD: Until we have a plan for how to represent demanded elements for 2914 // scalable vectors, we can just bail out for now. 2915 if (Op.getValueType().isScalableVector()) 2916 return Known; 2917 2918 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2919 // We know all of the bits for a constant! 2920 return KnownBits::makeConstant(C->getAPIntValue()); 2921 } 2922 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2923 // We know all of the bits for a constant fp! 2924 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2925 } 2926 2927 if (Depth >= MaxRecursionDepth) 2928 return Known; // Limit search depth. 2929 2930 KnownBits Known2; 2931 unsigned NumElts = DemandedElts.getBitWidth(); 2932 assert((!Op.getValueType().isVector() || 2933 NumElts == Op.getValueType().getVectorNumElements()) && 2934 "Unexpected vector size"); 2935 2936 if (!DemandedElts) 2937 return Known; // No demanded elts, better to assume we don't know anything. 2938 2939 unsigned Opcode = Op.getOpcode(); 2940 switch (Opcode) { 2941 case ISD::BUILD_VECTOR: 2942 // Collect the known bits that are shared by every demanded vector element. 2943 Known.Zero.setAllBits(); Known.One.setAllBits(); 2944 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2945 if (!DemandedElts[i]) 2946 continue; 2947 2948 SDValue SrcOp = Op.getOperand(i); 2949 Known2 = computeKnownBits(SrcOp, Depth + 1); 2950 2951 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2952 if (SrcOp.getValueSizeInBits() != BitWidth) { 2953 assert(SrcOp.getValueSizeInBits() > BitWidth && 2954 "Expected BUILD_VECTOR implicit truncation"); 2955 Known2 = Known2.trunc(BitWidth); 2956 } 2957 2958 // Known bits are the values that are shared by every demanded element. 2959 Known = KnownBits::commonBits(Known, Known2); 2960 2961 // If we don't know any bits, early out. 2962 if (Known.isUnknown()) 2963 break; 2964 } 2965 break; 2966 case ISD::VECTOR_SHUFFLE: { 2967 // Collect the known bits that are shared by every vector element referenced 2968 // by the shuffle. 2969 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2970 Known.Zero.setAllBits(); Known.One.setAllBits(); 2971 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2972 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2973 for (unsigned i = 0; i != NumElts; ++i) { 2974 if (!DemandedElts[i]) 2975 continue; 2976 2977 int M = SVN->getMaskElt(i); 2978 if (M < 0) { 2979 // For UNDEF elements, we don't know anything about the common state of 2980 // the shuffle result. 2981 Known.resetAll(); 2982 DemandedLHS.clearAllBits(); 2983 DemandedRHS.clearAllBits(); 2984 break; 2985 } 2986 2987 if ((unsigned)M < NumElts) 2988 DemandedLHS.setBit((unsigned)M % NumElts); 2989 else 2990 DemandedRHS.setBit((unsigned)M % NumElts); 2991 } 2992 // Known bits are the values that are shared by every demanded element. 2993 if (!!DemandedLHS) { 2994 SDValue LHS = Op.getOperand(0); 2995 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2996 Known = KnownBits::commonBits(Known, Known2); 2997 } 2998 // If we don't know any bits, early out. 2999 if (Known.isUnknown()) 3000 break; 3001 if (!!DemandedRHS) { 3002 SDValue RHS = Op.getOperand(1); 3003 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3004 Known = KnownBits::commonBits(Known, Known2); 3005 } 3006 break; 3007 } 3008 case ISD::CONCAT_VECTORS: { 3009 // Split DemandedElts and test each of the demanded subvectors. 3010 Known.Zero.setAllBits(); Known.One.setAllBits(); 3011 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3012 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3013 unsigned NumSubVectors = Op.getNumOperands(); 3014 for (unsigned i = 0; i != NumSubVectors; ++i) { 3015 APInt DemandedSub = 3016 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3017 if (!!DemandedSub) { 3018 SDValue Sub = Op.getOperand(i); 3019 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3020 Known = KnownBits::commonBits(Known, Known2); 3021 } 3022 // If we don't know any bits, early out. 3023 if (Known.isUnknown()) 3024 break; 3025 } 3026 break; 3027 } 3028 case ISD::INSERT_SUBVECTOR: { 3029 // Demand any elements from the subvector and the remainder from the src its 3030 // inserted into. 3031 SDValue Src = Op.getOperand(0); 3032 SDValue Sub = Op.getOperand(1); 3033 uint64_t Idx = Op.getConstantOperandVal(2); 3034 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3035 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3036 APInt DemandedSrcElts = DemandedElts; 3037 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3038 3039 Known.One.setAllBits(); 3040 Known.Zero.setAllBits(); 3041 if (!!DemandedSubElts) { 3042 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3043 if (Known.isUnknown()) 3044 break; // early-out. 3045 } 3046 if (!!DemandedSrcElts) { 3047 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3048 Known = KnownBits::commonBits(Known, Known2); 3049 } 3050 break; 3051 } 3052 case ISD::EXTRACT_SUBVECTOR: { 3053 // Offset the demanded elts by the subvector index. 3054 SDValue Src = Op.getOperand(0); 3055 // Bail until we can represent demanded elements for scalable vectors. 3056 if (Src.getValueType().isScalableVector()) 3057 break; 3058 uint64_t Idx = Op.getConstantOperandVal(1); 3059 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3060 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 3061 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3062 break; 3063 } 3064 case ISD::SCALAR_TO_VECTOR: { 3065 // We know about scalar_to_vector as much as we know about it source, 3066 // which becomes the first element of otherwise unknown vector. 3067 if (DemandedElts != 1) 3068 break; 3069 3070 SDValue N0 = Op.getOperand(0); 3071 Known = computeKnownBits(N0, Depth + 1); 3072 if (N0.getValueSizeInBits() != BitWidth) 3073 Known = Known.trunc(BitWidth); 3074 3075 break; 3076 } 3077 case ISD::BITCAST: { 3078 SDValue N0 = Op.getOperand(0); 3079 EVT SubVT = N0.getValueType(); 3080 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3081 3082 // Ignore bitcasts from unsupported types. 3083 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3084 break; 3085 3086 // Fast handling of 'identity' bitcasts. 3087 if (BitWidth == SubBitWidth) { 3088 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3089 break; 3090 } 3091 3092 bool IsLE = getDataLayout().isLittleEndian(); 3093 3094 // Bitcast 'small element' vector to 'large element' scalar/vector. 3095 if ((BitWidth % SubBitWidth) == 0) { 3096 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3097 3098 // Collect known bits for the (larger) output by collecting the known 3099 // bits from each set of sub elements and shift these into place. 3100 // We need to separately call computeKnownBits for each set of 3101 // sub elements as the knownbits for each is likely to be different. 3102 unsigned SubScale = BitWidth / SubBitWidth; 3103 APInt SubDemandedElts(NumElts * SubScale, 0); 3104 for (unsigned i = 0; i != NumElts; ++i) 3105 if (DemandedElts[i]) 3106 SubDemandedElts.setBit(i * SubScale); 3107 3108 for (unsigned i = 0; i != SubScale; ++i) { 3109 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3110 Depth + 1); 3111 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3112 Known.insertBits(Known2, SubBitWidth * Shifts); 3113 } 3114 } 3115 3116 // Bitcast 'large element' scalar/vector to 'small element' vector. 3117 if ((SubBitWidth % BitWidth) == 0) { 3118 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3119 3120 // Collect known bits for the (smaller) output by collecting the known 3121 // bits from the overlapping larger input elements and extracting the 3122 // sub sections we actually care about. 3123 unsigned SubScale = SubBitWidth / BitWidth; 3124 APInt SubDemandedElts = 3125 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3126 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3127 3128 Known.Zero.setAllBits(); Known.One.setAllBits(); 3129 for (unsigned i = 0; i != NumElts; ++i) 3130 if (DemandedElts[i]) { 3131 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3132 unsigned Offset = (Shifts % SubScale) * BitWidth; 3133 Known = KnownBits::commonBits(Known, 3134 Known2.extractBits(BitWidth, Offset)); 3135 // If we don't know any bits, early out. 3136 if (Known.isUnknown()) 3137 break; 3138 } 3139 } 3140 break; 3141 } 3142 case ISD::AND: 3143 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3144 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3145 3146 Known &= Known2; 3147 break; 3148 case ISD::OR: 3149 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3150 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3151 3152 Known |= Known2; 3153 break; 3154 case ISD::XOR: 3155 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3156 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3157 3158 Known ^= Known2; 3159 break; 3160 case ISD::MUL: { 3161 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3162 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3163 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3164 // TODO: SelfMultiply can be poison, but not undef. 3165 if (SelfMultiply) 3166 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3167 Op.getOperand(0), DemandedElts, false, Depth + 1); 3168 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3169 break; 3170 } 3171 case ISD::MULHU: { 3172 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3173 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3174 Known = KnownBits::mulhu(Known, Known2); 3175 break; 3176 } 3177 case ISD::MULHS: { 3178 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3179 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3180 Known = KnownBits::mulhs(Known, Known2); 3181 break; 3182 } 3183 case ISD::UMUL_LOHI: { 3184 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3185 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3186 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3187 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3188 if (Op.getResNo() == 0) 3189 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3190 else 3191 Known = KnownBits::mulhu(Known, Known2); 3192 break; 3193 } 3194 case ISD::SMUL_LOHI: { 3195 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3196 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3197 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3198 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3199 if (Op.getResNo() == 0) 3200 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3201 else 3202 Known = KnownBits::mulhs(Known, Known2); 3203 break; 3204 } 3205 case ISD::UDIV: { 3206 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3207 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3208 Known = KnownBits::udiv(Known, Known2); 3209 break; 3210 } 3211 case ISD::AVGCEILU: { 3212 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3213 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3214 Known = Known.zext(BitWidth + 1); 3215 Known2 = Known2.zext(BitWidth + 1); 3216 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3217 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3218 Known = Known.extractBits(BitWidth, 1); 3219 break; 3220 } 3221 case ISD::SELECT: 3222 case ISD::VSELECT: 3223 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3224 // If we don't know any bits, early out. 3225 if (Known.isUnknown()) 3226 break; 3227 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3228 3229 // Only known if known in both the LHS and RHS. 3230 Known = KnownBits::commonBits(Known, Known2); 3231 break; 3232 case ISD::SELECT_CC: 3233 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3234 // If we don't know any bits, early out. 3235 if (Known.isUnknown()) 3236 break; 3237 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3238 3239 // Only known if known in both the LHS and RHS. 3240 Known = KnownBits::commonBits(Known, Known2); 3241 break; 3242 case ISD::SMULO: 3243 case ISD::UMULO: 3244 if (Op.getResNo() != 1) 3245 break; 3246 // The boolean result conforms to getBooleanContents. 3247 // If we know the result of a setcc has the top bits zero, use this info. 3248 // We know that we have an integer-based boolean since these operations 3249 // are only available for integer. 3250 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3251 TargetLowering::ZeroOrOneBooleanContent && 3252 BitWidth > 1) 3253 Known.Zero.setBitsFrom(1); 3254 break; 3255 case ISD::SETCC: 3256 case ISD::STRICT_FSETCC: 3257 case ISD::STRICT_FSETCCS: { 3258 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3259 // If we know the result of a setcc has the top bits zero, use this info. 3260 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3261 TargetLowering::ZeroOrOneBooleanContent && 3262 BitWidth > 1) 3263 Known.Zero.setBitsFrom(1); 3264 break; 3265 } 3266 case ISD::SHL: 3267 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3268 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3269 Known = KnownBits::shl(Known, Known2); 3270 3271 // Minimum shift low bits are known zero. 3272 if (const APInt *ShMinAmt = 3273 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3274 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3275 break; 3276 case ISD::SRL: 3277 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3278 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3279 Known = KnownBits::lshr(Known, Known2); 3280 3281 // Minimum shift high bits are known zero. 3282 if (const APInt *ShMinAmt = 3283 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3284 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3285 break; 3286 case ISD::SRA: 3287 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3288 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3289 Known = KnownBits::ashr(Known, Known2); 3290 // TODO: Add minimum shift high known sign bits. 3291 break; 3292 case ISD::FSHL: 3293 case ISD::FSHR: 3294 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3295 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3296 3297 // For fshl, 0-shift returns the 1st arg. 3298 // For fshr, 0-shift returns the 2nd arg. 3299 if (Amt == 0) { 3300 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3301 DemandedElts, Depth + 1); 3302 break; 3303 } 3304 3305 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3306 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3307 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3308 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3309 if (Opcode == ISD::FSHL) { 3310 Known.One <<= Amt; 3311 Known.Zero <<= Amt; 3312 Known2.One.lshrInPlace(BitWidth - Amt); 3313 Known2.Zero.lshrInPlace(BitWidth - Amt); 3314 } else { 3315 Known.One <<= BitWidth - Amt; 3316 Known.Zero <<= BitWidth - Amt; 3317 Known2.One.lshrInPlace(Amt); 3318 Known2.Zero.lshrInPlace(Amt); 3319 } 3320 Known.One |= Known2.One; 3321 Known.Zero |= Known2.Zero; 3322 } 3323 break; 3324 case ISD::SIGN_EXTEND_INREG: { 3325 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3326 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3327 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3328 break; 3329 } 3330 case ISD::CTTZ: 3331 case ISD::CTTZ_ZERO_UNDEF: { 3332 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3333 // If we have a known 1, its position is our upper bound. 3334 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3335 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3336 Known.Zero.setBitsFrom(LowBits); 3337 break; 3338 } 3339 case ISD::CTLZ: 3340 case ISD::CTLZ_ZERO_UNDEF: { 3341 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3342 // If we have a known 1, its position is our upper bound. 3343 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3344 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3345 Known.Zero.setBitsFrom(LowBits); 3346 break; 3347 } 3348 case ISD::CTPOP: { 3349 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3350 // If we know some of the bits are zero, they can't be one. 3351 unsigned PossibleOnes = Known2.countMaxPopulation(); 3352 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3353 break; 3354 } 3355 case ISD::PARITY: { 3356 // Parity returns 0 everywhere but the LSB. 3357 Known.Zero.setBitsFrom(1); 3358 break; 3359 } 3360 case ISD::LOAD: { 3361 LoadSDNode *LD = cast<LoadSDNode>(Op); 3362 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3363 if (ISD::isNON_EXTLoad(LD) && Cst) { 3364 // Determine any common known bits from the loaded constant pool value. 3365 Type *CstTy = Cst->getType(); 3366 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3367 // If its a vector splat, then we can (quickly) reuse the scalar path. 3368 // NOTE: We assume all elements match and none are UNDEF. 3369 if (CstTy->isVectorTy()) { 3370 if (const Constant *Splat = Cst->getSplatValue()) { 3371 Cst = Splat; 3372 CstTy = Cst->getType(); 3373 } 3374 } 3375 // TODO - do we need to handle different bitwidths? 3376 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3377 // Iterate across all vector elements finding common known bits. 3378 Known.One.setAllBits(); 3379 Known.Zero.setAllBits(); 3380 for (unsigned i = 0; i != NumElts; ++i) { 3381 if (!DemandedElts[i]) 3382 continue; 3383 if (Constant *Elt = Cst->getAggregateElement(i)) { 3384 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3385 const APInt &Value = CInt->getValue(); 3386 Known.One &= Value; 3387 Known.Zero &= ~Value; 3388 continue; 3389 } 3390 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3391 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3392 Known.One &= Value; 3393 Known.Zero &= ~Value; 3394 continue; 3395 } 3396 } 3397 Known.One.clearAllBits(); 3398 Known.Zero.clearAllBits(); 3399 break; 3400 } 3401 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3402 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3403 Known = KnownBits::makeConstant(CInt->getValue()); 3404 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3405 Known = 3406 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3407 } 3408 } 3409 } 3410 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3411 // If this is a ZEXTLoad and we are looking at the loaded value. 3412 EVT VT = LD->getMemoryVT(); 3413 unsigned MemBits = VT.getScalarSizeInBits(); 3414 Known.Zero.setBitsFrom(MemBits); 3415 } else if (const MDNode *Ranges = LD->getRanges()) { 3416 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3417 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3418 } 3419 break; 3420 } 3421 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3422 EVT InVT = Op.getOperand(0).getValueType(); 3423 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3424 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3425 Known = Known.zext(BitWidth); 3426 break; 3427 } 3428 case ISD::ZERO_EXTEND: { 3429 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3430 Known = Known.zext(BitWidth); 3431 break; 3432 } 3433 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3434 EVT InVT = Op.getOperand(0).getValueType(); 3435 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3436 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3437 // If the sign bit is known to be zero or one, then sext will extend 3438 // it to the top bits, else it will just zext. 3439 Known = Known.sext(BitWidth); 3440 break; 3441 } 3442 case ISD::SIGN_EXTEND: { 3443 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3444 // If the sign bit is known to be zero or one, then sext will extend 3445 // it to the top bits, else it will just zext. 3446 Known = Known.sext(BitWidth); 3447 break; 3448 } 3449 case ISD::ANY_EXTEND_VECTOR_INREG: { 3450 EVT InVT = Op.getOperand(0).getValueType(); 3451 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3452 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3453 Known = Known.anyext(BitWidth); 3454 break; 3455 } 3456 case ISD::ANY_EXTEND: { 3457 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3458 Known = Known.anyext(BitWidth); 3459 break; 3460 } 3461 case ISD::TRUNCATE: { 3462 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3463 Known = Known.trunc(BitWidth); 3464 break; 3465 } 3466 case ISD::AssertZext: { 3467 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3468 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3469 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3470 Known.Zero |= (~InMask); 3471 Known.One &= (~Known.Zero); 3472 break; 3473 } 3474 case ISD::AssertAlign: { 3475 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3476 assert(LogOfAlign != 0); 3477 3478 // TODO: Should use maximum with source 3479 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3480 // well as clearing one bits. 3481 Known.Zero.setLowBits(LogOfAlign); 3482 Known.One.clearLowBits(LogOfAlign); 3483 break; 3484 } 3485 case ISD::FGETSIGN: 3486 // All bits are zero except the low bit. 3487 Known.Zero.setBitsFrom(1); 3488 break; 3489 case ISD::USUBO: 3490 case ISD::SSUBO: 3491 if (Op.getResNo() == 1) { 3492 // If we know the result of a setcc has the top bits zero, use this info. 3493 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3494 TargetLowering::ZeroOrOneBooleanContent && 3495 BitWidth > 1) 3496 Known.Zero.setBitsFrom(1); 3497 break; 3498 } 3499 LLVM_FALLTHROUGH; 3500 case ISD::SUB: 3501 case ISD::SUBC: { 3502 assert(Op.getResNo() == 0 && 3503 "We only compute knownbits for the difference here."); 3504 3505 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3506 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3507 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3508 Known, Known2); 3509 break; 3510 } 3511 case ISD::UADDO: 3512 case ISD::SADDO: 3513 case ISD::ADDCARRY: 3514 if (Op.getResNo() == 1) { 3515 // If we know the result of a setcc has the top bits zero, use this info. 3516 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3517 TargetLowering::ZeroOrOneBooleanContent && 3518 BitWidth > 1) 3519 Known.Zero.setBitsFrom(1); 3520 break; 3521 } 3522 LLVM_FALLTHROUGH; 3523 case ISD::ADD: 3524 case ISD::ADDC: 3525 case ISD::ADDE: { 3526 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3527 3528 // With ADDE and ADDCARRY, a carry bit may be added in. 3529 KnownBits Carry(1); 3530 if (Opcode == ISD::ADDE) 3531 // Can't track carry from glue, set carry to unknown. 3532 Carry.resetAll(); 3533 else if (Opcode == ISD::ADDCARRY) 3534 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3535 // the trouble (how often will we find a known carry bit). And I haven't 3536 // tested this very much yet, but something like this might work: 3537 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3538 // Carry = Carry.zextOrTrunc(1, false); 3539 Carry.resetAll(); 3540 else 3541 Carry.setAllZero(); 3542 3543 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3544 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3545 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3546 break; 3547 } 3548 case ISD::SREM: { 3549 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3550 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3551 Known = KnownBits::srem(Known, Known2); 3552 break; 3553 } 3554 case ISD::UREM: { 3555 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3556 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3557 Known = KnownBits::urem(Known, Known2); 3558 break; 3559 } 3560 case ISD::EXTRACT_ELEMENT: { 3561 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3562 const unsigned Index = Op.getConstantOperandVal(1); 3563 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3564 3565 // Remove low part of known bits mask 3566 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3567 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3568 3569 // Remove high part of known bit mask 3570 Known = Known.trunc(EltBitWidth); 3571 break; 3572 } 3573 case ISD::EXTRACT_VECTOR_ELT: { 3574 SDValue InVec = Op.getOperand(0); 3575 SDValue EltNo = Op.getOperand(1); 3576 EVT VecVT = InVec.getValueType(); 3577 // computeKnownBits not yet implemented for scalable vectors. 3578 if (VecVT.isScalableVector()) 3579 break; 3580 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3581 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3582 3583 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3584 // anything about the extended bits. 3585 if (BitWidth > EltBitWidth) 3586 Known = Known.trunc(EltBitWidth); 3587 3588 // If we know the element index, just demand that vector element, else for 3589 // an unknown element index, ignore DemandedElts and demand them all. 3590 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3591 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3592 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3593 DemandedSrcElts = 3594 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3595 3596 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3597 if (BitWidth > EltBitWidth) 3598 Known = Known.anyext(BitWidth); 3599 break; 3600 } 3601 case ISD::INSERT_VECTOR_ELT: { 3602 // If we know the element index, split the demand between the 3603 // source vector and the inserted element, otherwise assume we need 3604 // the original demanded vector elements and the value. 3605 SDValue InVec = Op.getOperand(0); 3606 SDValue InVal = Op.getOperand(1); 3607 SDValue EltNo = Op.getOperand(2); 3608 bool DemandedVal = true; 3609 APInt DemandedVecElts = DemandedElts; 3610 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3611 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3612 unsigned EltIdx = CEltNo->getZExtValue(); 3613 DemandedVal = !!DemandedElts[EltIdx]; 3614 DemandedVecElts.clearBit(EltIdx); 3615 } 3616 Known.One.setAllBits(); 3617 Known.Zero.setAllBits(); 3618 if (DemandedVal) { 3619 Known2 = computeKnownBits(InVal, Depth + 1); 3620 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3621 } 3622 if (!!DemandedVecElts) { 3623 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3624 Known = KnownBits::commonBits(Known, Known2); 3625 } 3626 break; 3627 } 3628 case ISD::BITREVERSE: { 3629 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3630 Known = Known2.reverseBits(); 3631 break; 3632 } 3633 case ISD::BSWAP: { 3634 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3635 Known = Known2.byteSwap(); 3636 break; 3637 } 3638 case ISD::ABS: { 3639 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3640 Known = Known2.abs(); 3641 break; 3642 } 3643 case ISD::USUBSAT: { 3644 // The result of usubsat will never be larger than the LHS. 3645 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3646 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3647 break; 3648 } 3649 case ISD::UMIN: { 3650 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3651 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3652 Known = KnownBits::umin(Known, Known2); 3653 break; 3654 } 3655 case ISD::UMAX: { 3656 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3657 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3658 Known = KnownBits::umax(Known, Known2); 3659 break; 3660 } 3661 case ISD::SMIN: 3662 case ISD::SMAX: { 3663 // If we have a clamp pattern, we know that the number of sign bits will be 3664 // the minimum of the clamp min/max range. 3665 bool IsMax = (Opcode == ISD::SMAX); 3666 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3667 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3668 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3669 CstHigh = 3670 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3671 if (CstLow && CstHigh) { 3672 if (!IsMax) 3673 std::swap(CstLow, CstHigh); 3674 3675 const APInt &ValueLow = CstLow->getAPIntValue(); 3676 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3677 if (ValueLow.sle(ValueHigh)) { 3678 unsigned LowSignBits = ValueLow.getNumSignBits(); 3679 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3680 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3681 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3682 Known.One.setHighBits(MinSignBits); 3683 break; 3684 } 3685 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3686 Known.Zero.setHighBits(MinSignBits); 3687 break; 3688 } 3689 } 3690 } 3691 3692 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3693 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3694 if (IsMax) 3695 Known = KnownBits::smax(Known, Known2); 3696 else 3697 Known = KnownBits::smin(Known, Known2); 3698 break; 3699 } 3700 case ISD::FP_TO_UINT_SAT: { 3701 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3702 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3703 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3704 break; 3705 } 3706 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3707 if (Op.getResNo() == 1) { 3708 // The boolean result conforms to getBooleanContents. 3709 // If we know the result of a setcc has the top bits zero, use this info. 3710 // We know that we have an integer-based boolean since these operations 3711 // are only available for integer. 3712 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3713 TargetLowering::ZeroOrOneBooleanContent && 3714 BitWidth > 1) 3715 Known.Zero.setBitsFrom(1); 3716 break; 3717 } 3718 LLVM_FALLTHROUGH; 3719 case ISD::ATOMIC_CMP_SWAP: 3720 case ISD::ATOMIC_SWAP: 3721 case ISD::ATOMIC_LOAD_ADD: 3722 case ISD::ATOMIC_LOAD_SUB: 3723 case ISD::ATOMIC_LOAD_AND: 3724 case ISD::ATOMIC_LOAD_CLR: 3725 case ISD::ATOMIC_LOAD_OR: 3726 case ISD::ATOMIC_LOAD_XOR: 3727 case ISD::ATOMIC_LOAD_NAND: 3728 case ISD::ATOMIC_LOAD_MIN: 3729 case ISD::ATOMIC_LOAD_MAX: 3730 case ISD::ATOMIC_LOAD_UMIN: 3731 case ISD::ATOMIC_LOAD_UMAX: 3732 case ISD::ATOMIC_LOAD: { 3733 unsigned MemBits = 3734 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3735 // If we are looking at the loaded value. 3736 if (Op.getResNo() == 0) { 3737 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3738 Known.Zero.setBitsFrom(MemBits); 3739 } 3740 break; 3741 } 3742 case ISD::FrameIndex: 3743 case ISD::TargetFrameIndex: 3744 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3745 Known, getMachineFunction()); 3746 break; 3747 3748 default: 3749 if (Opcode < ISD::BUILTIN_OP_END) 3750 break; 3751 LLVM_FALLTHROUGH; 3752 case ISD::INTRINSIC_WO_CHAIN: 3753 case ISD::INTRINSIC_W_CHAIN: 3754 case ISD::INTRINSIC_VOID: 3755 // Allow the target to implement this method for its nodes. 3756 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3757 break; 3758 } 3759 3760 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3761 return Known; 3762 } 3763 3764 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3765 SDValue N1) const { 3766 // X + 0 never overflow 3767 if (isNullConstant(N1)) 3768 return OFK_Never; 3769 3770 KnownBits N1Known = computeKnownBits(N1); 3771 if (N1Known.Zero.getBoolValue()) { 3772 KnownBits N0Known = computeKnownBits(N0); 3773 3774 bool overflow; 3775 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3776 if (!overflow) 3777 return OFK_Never; 3778 } 3779 3780 // mulhi + 1 never overflow 3781 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3782 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3783 return OFK_Never; 3784 3785 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3786 KnownBits N0Known = computeKnownBits(N0); 3787 3788 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3789 return OFK_Never; 3790 } 3791 3792 return OFK_Sometime; 3793 } 3794 3795 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3796 EVT OpVT = Val.getValueType(); 3797 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3798 3799 // Is the constant a known power of 2? 3800 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3801 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3802 3803 // A left-shift of a constant one will have exactly one bit set because 3804 // shifting the bit off the end is undefined. 3805 if (Val.getOpcode() == ISD::SHL) { 3806 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3807 if (C && C->getAPIntValue() == 1) 3808 return true; 3809 } 3810 3811 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3812 // one bit set. 3813 if (Val.getOpcode() == ISD::SRL) { 3814 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3815 if (C && C->getAPIntValue().isSignMask()) 3816 return true; 3817 } 3818 3819 // Are all operands of a build vector constant powers of two? 3820 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3821 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3822 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3823 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3824 return false; 3825 })) 3826 return true; 3827 3828 // Is the operand of a splat vector a constant power of two? 3829 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3830 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3831 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3832 return true; 3833 3834 // More could be done here, though the above checks are enough 3835 // to handle some common cases. 3836 3837 // Fall back to computeKnownBits to catch other known cases. 3838 KnownBits Known = computeKnownBits(Val); 3839 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3840 } 3841 3842 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3843 EVT VT = Op.getValueType(); 3844 3845 // TODO: Assume we don't know anything for now. 3846 if (VT.isScalableVector()) 3847 return 1; 3848 3849 APInt DemandedElts = VT.isVector() 3850 ? APInt::getAllOnes(VT.getVectorNumElements()) 3851 : APInt(1, 1); 3852 return ComputeNumSignBits(Op, DemandedElts, Depth); 3853 } 3854 3855 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3856 unsigned Depth) const { 3857 EVT VT = Op.getValueType(); 3858 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3859 unsigned VTBits = VT.getScalarSizeInBits(); 3860 unsigned NumElts = DemandedElts.getBitWidth(); 3861 unsigned Tmp, Tmp2; 3862 unsigned FirstAnswer = 1; 3863 3864 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3865 const APInt &Val = C->getAPIntValue(); 3866 return Val.getNumSignBits(); 3867 } 3868 3869 if (Depth >= MaxRecursionDepth) 3870 return 1; // Limit search depth. 3871 3872 if (!DemandedElts || VT.isScalableVector()) 3873 return 1; // No demanded elts, better to assume we don't know anything. 3874 3875 unsigned Opcode = Op.getOpcode(); 3876 switch (Opcode) { 3877 default: break; 3878 case ISD::AssertSext: 3879 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3880 return VTBits-Tmp+1; 3881 case ISD::AssertZext: 3882 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3883 return VTBits-Tmp; 3884 3885 case ISD::BUILD_VECTOR: 3886 Tmp = VTBits; 3887 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3888 if (!DemandedElts[i]) 3889 continue; 3890 3891 SDValue SrcOp = Op.getOperand(i); 3892 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3893 3894 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3895 if (SrcOp.getValueSizeInBits() != VTBits) { 3896 assert(SrcOp.getValueSizeInBits() > VTBits && 3897 "Expected BUILD_VECTOR implicit truncation"); 3898 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3899 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3900 } 3901 Tmp = std::min(Tmp, Tmp2); 3902 } 3903 return Tmp; 3904 3905 case ISD::VECTOR_SHUFFLE: { 3906 // Collect the minimum number of sign bits that are shared by every vector 3907 // element referenced by the shuffle. 3908 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3909 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3910 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3911 for (unsigned i = 0; i != NumElts; ++i) { 3912 int M = SVN->getMaskElt(i); 3913 if (!DemandedElts[i]) 3914 continue; 3915 // For UNDEF elements, we don't know anything about the common state of 3916 // the shuffle result. 3917 if (M < 0) 3918 return 1; 3919 if ((unsigned)M < NumElts) 3920 DemandedLHS.setBit((unsigned)M % NumElts); 3921 else 3922 DemandedRHS.setBit((unsigned)M % NumElts); 3923 } 3924 Tmp = std::numeric_limits<unsigned>::max(); 3925 if (!!DemandedLHS) 3926 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3927 if (!!DemandedRHS) { 3928 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3929 Tmp = std::min(Tmp, Tmp2); 3930 } 3931 // If we don't know anything, early out and try computeKnownBits fall-back. 3932 if (Tmp == 1) 3933 break; 3934 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3935 return Tmp; 3936 } 3937 3938 case ISD::BITCAST: { 3939 SDValue N0 = Op.getOperand(0); 3940 EVT SrcVT = N0.getValueType(); 3941 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3942 3943 // Ignore bitcasts from unsupported types.. 3944 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3945 break; 3946 3947 // Fast handling of 'identity' bitcasts. 3948 if (VTBits == SrcBits) 3949 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3950 3951 bool IsLE = getDataLayout().isLittleEndian(); 3952 3953 // Bitcast 'large element' scalar/vector to 'small element' vector. 3954 if ((SrcBits % VTBits) == 0) { 3955 assert(VT.isVector() && "Expected bitcast to vector"); 3956 3957 unsigned Scale = SrcBits / VTBits; 3958 APInt SrcDemandedElts = 3959 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3960 3961 // Fast case - sign splat can be simply split across the small elements. 3962 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3963 if (Tmp == SrcBits) 3964 return VTBits; 3965 3966 // Slow case - determine how far the sign extends into each sub-element. 3967 Tmp2 = VTBits; 3968 for (unsigned i = 0; i != NumElts; ++i) 3969 if (DemandedElts[i]) { 3970 unsigned SubOffset = i % Scale; 3971 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3972 SubOffset = SubOffset * VTBits; 3973 if (Tmp <= SubOffset) 3974 return 1; 3975 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3976 } 3977 return Tmp2; 3978 } 3979 break; 3980 } 3981 3982 case ISD::FP_TO_SINT_SAT: 3983 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 3984 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3985 return VTBits - Tmp + 1; 3986 case ISD::SIGN_EXTEND: 3987 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3988 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3989 case ISD::SIGN_EXTEND_INREG: 3990 // Max of the input and what this extends. 3991 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3992 Tmp = VTBits-Tmp+1; 3993 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3994 return std::max(Tmp, Tmp2); 3995 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3996 SDValue Src = Op.getOperand(0); 3997 EVT SrcVT = Src.getValueType(); 3998 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3999 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4000 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4001 } 4002 case ISD::SRA: 4003 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4004 // SRA X, C -> adds C sign bits. 4005 if (const APInt *ShAmt = 4006 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4007 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4008 return Tmp; 4009 case ISD::SHL: 4010 if (const APInt *ShAmt = 4011 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4012 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4013 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4014 if (ShAmt->ult(Tmp)) 4015 return Tmp - ShAmt->getZExtValue(); 4016 } 4017 break; 4018 case ISD::AND: 4019 case ISD::OR: 4020 case ISD::XOR: // NOT is handled here. 4021 // Logical binary ops preserve the number of sign bits at the worst. 4022 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4023 if (Tmp != 1) { 4024 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4025 FirstAnswer = std::min(Tmp, Tmp2); 4026 // We computed what we know about the sign bits as our first 4027 // answer. Now proceed to the generic code that uses 4028 // computeKnownBits, and pick whichever answer is better. 4029 } 4030 break; 4031 4032 case ISD::SELECT: 4033 case ISD::VSELECT: 4034 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4035 if (Tmp == 1) return 1; // Early out. 4036 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4037 return std::min(Tmp, Tmp2); 4038 case ISD::SELECT_CC: 4039 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4040 if (Tmp == 1) return 1; // Early out. 4041 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4042 return std::min(Tmp, Tmp2); 4043 4044 case ISD::SMIN: 4045 case ISD::SMAX: { 4046 // If we have a clamp pattern, we know that the number of sign bits will be 4047 // the minimum of the clamp min/max range. 4048 bool IsMax = (Opcode == ISD::SMAX); 4049 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4050 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4051 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4052 CstHigh = 4053 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4054 if (CstLow && CstHigh) { 4055 if (!IsMax) 4056 std::swap(CstLow, CstHigh); 4057 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4058 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4059 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4060 return std::min(Tmp, Tmp2); 4061 } 4062 } 4063 4064 // Fallback - just get the minimum number of sign bits of the operands. 4065 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4066 if (Tmp == 1) 4067 return 1; // Early out. 4068 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4069 return std::min(Tmp, Tmp2); 4070 } 4071 case ISD::UMIN: 4072 case ISD::UMAX: 4073 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4074 if (Tmp == 1) 4075 return 1; // Early out. 4076 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4077 return std::min(Tmp, Tmp2); 4078 case ISD::SADDO: 4079 case ISD::UADDO: 4080 case ISD::SSUBO: 4081 case ISD::USUBO: 4082 case ISD::SMULO: 4083 case ISD::UMULO: 4084 if (Op.getResNo() != 1) 4085 break; 4086 // The boolean result conforms to getBooleanContents. Fall through. 4087 // If setcc returns 0/-1, all bits are sign bits. 4088 // We know that we have an integer-based boolean since these operations 4089 // are only available for integer. 4090 if (TLI->getBooleanContents(VT.isVector(), false) == 4091 TargetLowering::ZeroOrNegativeOneBooleanContent) 4092 return VTBits; 4093 break; 4094 case ISD::SETCC: 4095 case ISD::STRICT_FSETCC: 4096 case ISD::STRICT_FSETCCS: { 4097 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4098 // If setcc returns 0/-1, all bits are sign bits. 4099 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4100 TargetLowering::ZeroOrNegativeOneBooleanContent) 4101 return VTBits; 4102 break; 4103 } 4104 case ISD::ROTL: 4105 case ISD::ROTR: 4106 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4107 4108 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4109 if (Tmp == VTBits) 4110 return VTBits; 4111 4112 if (ConstantSDNode *C = 4113 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4114 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4115 4116 // Handle rotate right by N like a rotate left by 32-N. 4117 if (Opcode == ISD::ROTR) 4118 RotAmt = (VTBits - RotAmt) % VTBits; 4119 4120 // If we aren't rotating out all of the known-in sign bits, return the 4121 // number that are left. This handles rotl(sext(x), 1) for example. 4122 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4123 } 4124 break; 4125 case ISD::ADD: 4126 case ISD::ADDC: 4127 // Add can have at most one carry bit. Thus we know that the output 4128 // is, at worst, one more bit than the inputs. 4129 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4130 if (Tmp == 1) return 1; // Early out. 4131 4132 // Special case decrementing a value (ADD X, -1): 4133 if (ConstantSDNode *CRHS = 4134 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4135 if (CRHS->isAllOnes()) { 4136 KnownBits Known = 4137 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4138 4139 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4140 // sign bits set. 4141 if ((Known.Zero | 1).isAllOnes()) 4142 return VTBits; 4143 4144 // If we are subtracting one from a positive number, there is no carry 4145 // out of the result. 4146 if (Known.isNonNegative()) 4147 return Tmp; 4148 } 4149 4150 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4151 if (Tmp2 == 1) return 1; // Early out. 4152 return std::min(Tmp, Tmp2) - 1; 4153 case ISD::SUB: 4154 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4155 if (Tmp2 == 1) return 1; // Early out. 4156 4157 // Handle NEG. 4158 if (ConstantSDNode *CLHS = 4159 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4160 if (CLHS->isZero()) { 4161 KnownBits Known = 4162 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4163 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4164 // sign bits set. 4165 if ((Known.Zero | 1).isAllOnes()) 4166 return VTBits; 4167 4168 // If the input is known to be positive (the sign bit is known clear), 4169 // the output of the NEG has the same number of sign bits as the input. 4170 if (Known.isNonNegative()) 4171 return Tmp2; 4172 4173 // Otherwise, we treat this like a SUB. 4174 } 4175 4176 // Sub can have at most one carry bit. Thus we know that the output 4177 // is, at worst, one more bit than the inputs. 4178 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4179 if (Tmp == 1) return 1; // Early out. 4180 return std::min(Tmp, Tmp2) - 1; 4181 case ISD::MUL: { 4182 // The output of the Mul can be at most twice the valid bits in the inputs. 4183 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4184 if (SignBitsOp0 == 1) 4185 break; 4186 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4187 if (SignBitsOp1 == 1) 4188 break; 4189 unsigned OutValidBits = 4190 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4191 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4192 } 4193 case ISD::SREM: 4194 // The sign bit is the LHS's sign bit, except when the result of the 4195 // remainder is zero. The magnitude of the result should be less than or 4196 // equal to the magnitude of the LHS. Therefore, the result should have 4197 // at least as many sign bits as the left hand side. 4198 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4199 case ISD::TRUNCATE: { 4200 // Check if the sign bits of source go down as far as the truncated value. 4201 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4202 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4203 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4204 return NumSrcSignBits - (NumSrcBits - VTBits); 4205 break; 4206 } 4207 case ISD::EXTRACT_ELEMENT: { 4208 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4209 const int BitWidth = Op.getValueSizeInBits(); 4210 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4211 4212 // Get reverse index (starting from 1), Op1 value indexes elements from 4213 // little end. Sign starts at big end. 4214 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4215 4216 // If the sign portion ends in our element the subtraction gives correct 4217 // result. Otherwise it gives either negative or > bitwidth result 4218 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4219 } 4220 case ISD::INSERT_VECTOR_ELT: { 4221 // If we know the element index, split the demand between the 4222 // source vector and the inserted element, otherwise assume we need 4223 // the original demanded vector elements and the value. 4224 SDValue InVec = Op.getOperand(0); 4225 SDValue InVal = Op.getOperand(1); 4226 SDValue EltNo = Op.getOperand(2); 4227 bool DemandedVal = true; 4228 APInt DemandedVecElts = DemandedElts; 4229 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4230 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4231 unsigned EltIdx = CEltNo->getZExtValue(); 4232 DemandedVal = !!DemandedElts[EltIdx]; 4233 DemandedVecElts.clearBit(EltIdx); 4234 } 4235 Tmp = std::numeric_limits<unsigned>::max(); 4236 if (DemandedVal) { 4237 // TODO - handle implicit truncation of inserted elements. 4238 if (InVal.getScalarValueSizeInBits() != VTBits) 4239 break; 4240 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4241 Tmp = std::min(Tmp, Tmp2); 4242 } 4243 if (!!DemandedVecElts) { 4244 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4245 Tmp = std::min(Tmp, Tmp2); 4246 } 4247 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4248 return Tmp; 4249 } 4250 case ISD::EXTRACT_VECTOR_ELT: { 4251 SDValue InVec = Op.getOperand(0); 4252 SDValue EltNo = Op.getOperand(1); 4253 EVT VecVT = InVec.getValueType(); 4254 // ComputeNumSignBits not yet implemented for scalable vectors. 4255 if (VecVT.isScalableVector()) 4256 break; 4257 const unsigned BitWidth = Op.getValueSizeInBits(); 4258 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4259 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4260 4261 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4262 // anything about sign bits. But if the sizes match we can derive knowledge 4263 // about sign bits from the vector operand. 4264 if (BitWidth != EltBitWidth) 4265 break; 4266 4267 // If we know the element index, just demand that vector element, else for 4268 // an unknown element index, ignore DemandedElts and demand them all. 4269 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4270 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4271 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4272 DemandedSrcElts = 4273 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4274 4275 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4276 } 4277 case ISD::EXTRACT_SUBVECTOR: { 4278 // Offset the demanded elts by the subvector index. 4279 SDValue Src = Op.getOperand(0); 4280 // Bail until we can represent demanded elements for scalable vectors. 4281 if (Src.getValueType().isScalableVector()) 4282 break; 4283 uint64_t Idx = Op.getConstantOperandVal(1); 4284 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4285 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4286 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4287 } 4288 case ISD::CONCAT_VECTORS: { 4289 // Determine the minimum number of sign bits across all demanded 4290 // elts of the input vectors. Early out if the result is already 1. 4291 Tmp = std::numeric_limits<unsigned>::max(); 4292 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4293 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4294 unsigned NumSubVectors = Op.getNumOperands(); 4295 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4296 APInt DemandedSub = 4297 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4298 if (!DemandedSub) 4299 continue; 4300 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4301 Tmp = std::min(Tmp, Tmp2); 4302 } 4303 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4304 return Tmp; 4305 } 4306 case ISD::INSERT_SUBVECTOR: { 4307 // Demand any elements from the subvector and the remainder from the src its 4308 // inserted into. 4309 SDValue Src = Op.getOperand(0); 4310 SDValue Sub = Op.getOperand(1); 4311 uint64_t Idx = Op.getConstantOperandVal(2); 4312 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4313 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4314 APInt DemandedSrcElts = DemandedElts; 4315 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4316 4317 Tmp = std::numeric_limits<unsigned>::max(); 4318 if (!!DemandedSubElts) { 4319 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4320 if (Tmp == 1) 4321 return 1; // early-out 4322 } 4323 if (!!DemandedSrcElts) { 4324 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4325 Tmp = std::min(Tmp, Tmp2); 4326 } 4327 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4328 return Tmp; 4329 } 4330 case ISD::ATOMIC_CMP_SWAP: 4331 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4332 case ISD::ATOMIC_SWAP: 4333 case ISD::ATOMIC_LOAD_ADD: 4334 case ISD::ATOMIC_LOAD_SUB: 4335 case ISD::ATOMIC_LOAD_AND: 4336 case ISD::ATOMIC_LOAD_CLR: 4337 case ISD::ATOMIC_LOAD_OR: 4338 case ISD::ATOMIC_LOAD_XOR: 4339 case ISD::ATOMIC_LOAD_NAND: 4340 case ISD::ATOMIC_LOAD_MIN: 4341 case ISD::ATOMIC_LOAD_MAX: 4342 case ISD::ATOMIC_LOAD_UMIN: 4343 case ISD::ATOMIC_LOAD_UMAX: 4344 case ISD::ATOMIC_LOAD: { 4345 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4346 // If we are looking at the loaded value. 4347 if (Op.getResNo() == 0) { 4348 if (Tmp == VTBits) 4349 return 1; // early-out 4350 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4351 return VTBits - Tmp + 1; 4352 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4353 return VTBits - Tmp; 4354 } 4355 break; 4356 } 4357 } 4358 4359 // If we are looking at the loaded value of the SDNode. 4360 if (Op.getResNo() == 0) { 4361 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4362 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4363 unsigned ExtType = LD->getExtensionType(); 4364 switch (ExtType) { 4365 default: break; 4366 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4367 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4368 return VTBits - Tmp + 1; 4369 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4370 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4371 return VTBits - Tmp; 4372 case ISD::NON_EXTLOAD: 4373 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4374 // We only need to handle vectors - computeKnownBits should handle 4375 // scalar cases. 4376 Type *CstTy = Cst->getType(); 4377 if (CstTy->isVectorTy() && 4378 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4379 VTBits == CstTy->getScalarSizeInBits()) { 4380 Tmp = VTBits; 4381 for (unsigned i = 0; i != NumElts; ++i) { 4382 if (!DemandedElts[i]) 4383 continue; 4384 if (Constant *Elt = Cst->getAggregateElement(i)) { 4385 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4386 const APInt &Value = CInt->getValue(); 4387 Tmp = std::min(Tmp, Value.getNumSignBits()); 4388 continue; 4389 } 4390 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4391 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4392 Tmp = std::min(Tmp, Value.getNumSignBits()); 4393 continue; 4394 } 4395 } 4396 // Unknown type. Conservatively assume no bits match sign bit. 4397 return 1; 4398 } 4399 return Tmp; 4400 } 4401 } 4402 break; 4403 } 4404 } 4405 } 4406 4407 // Allow the target to implement this method for its nodes. 4408 if (Opcode >= ISD::BUILTIN_OP_END || 4409 Opcode == ISD::INTRINSIC_WO_CHAIN || 4410 Opcode == ISD::INTRINSIC_W_CHAIN || 4411 Opcode == ISD::INTRINSIC_VOID) { 4412 unsigned NumBits = 4413 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4414 if (NumBits > 1) 4415 FirstAnswer = std::max(FirstAnswer, NumBits); 4416 } 4417 4418 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4419 // use this information. 4420 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4421 return std::max(FirstAnswer, Known.countMinSignBits()); 4422 } 4423 4424 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4425 unsigned Depth) const { 4426 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4427 return Op.getScalarValueSizeInBits() - SignBits + 1; 4428 } 4429 4430 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4431 const APInt &DemandedElts, 4432 unsigned Depth) const { 4433 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4434 return Op.getScalarValueSizeInBits() - SignBits + 1; 4435 } 4436 4437 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4438 unsigned Depth) const { 4439 // Early out for FREEZE. 4440 if (Op.getOpcode() == ISD::FREEZE) 4441 return true; 4442 4443 // TODO: Assume we don't know anything for now. 4444 EVT VT = Op.getValueType(); 4445 if (VT.isScalableVector()) 4446 return false; 4447 4448 APInt DemandedElts = VT.isVector() 4449 ? APInt::getAllOnes(VT.getVectorNumElements()) 4450 : APInt(1, 1); 4451 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4452 } 4453 4454 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4455 const APInt &DemandedElts, 4456 bool PoisonOnly, 4457 unsigned Depth) const { 4458 unsigned Opcode = Op.getOpcode(); 4459 4460 // Early out for FREEZE. 4461 if (Opcode == ISD::FREEZE) 4462 return true; 4463 4464 if (Depth >= MaxRecursionDepth) 4465 return false; // Limit search depth. 4466 4467 if (isIntOrFPConstant(Op)) 4468 return true; 4469 4470 switch (Opcode) { 4471 case ISD::UNDEF: 4472 return PoisonOnly; 4473 4474 case ISD::BUILD_VECTOR: 4475 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4476 // this shouldn't affect the result. 4477 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4478 if (!DemandedElts[i]) 4479 continue; 4480 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4481 Depth + 1)) 4482 return false; 4483 } 4484 return true; 4485 4486 // TODO: Search for noundef attributes from library functions. 4487 4488 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4489 4490 default: 4491 // Allow the target to implement this method for its nodes. 4492 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4493 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4494 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4495 Op, DemandedElts, *this, PoisonOnly, Depth); 4496 break; 4497 } 4498 4499 return false; 4500 } 4501 4502 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4503 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4504 !isa<ConstantSDNode>(Op.getOperand(1))) 4505 return false; 4506 4507 if (Op.getOpcode() == ISD::OR && 4508 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4509 return false; 4510 4511 return true; 4512 } 4513 4514 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4515 // If we're told that NaNs won't happen, assume they won't. 4516 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4517 return true; 4518 4519 if (Depth >= MaxRecursionDepth) 4520 return false; // Limit search depth. 4521 4522 // TODO: Handle vectors. 4523 // If the value is a constant, we can obviously see if it is a NaN or not. 4524 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4525 return !C->getValueAPF().isNaN() || 4526 (SNaN && !C->getValueAPF().isSignaling()); 4527 } 4528 4529 unsigned Opcode = Op.getOpcode(); 4530 switch (Opcode) { 4531 case ISD::FADD: 4532 case ISD::FSUB: 4533 case ISD::FMUL: 4534 case ISD::FDIV: 4535 case ISD::FREM: 4536 case ISD::FSIN: 4537 case ISD::FCOS: { 4538 if (SNaN) 4539 return true; 4540 // TODO: Need isKnownNeverInfinity 4541 return false; 4542 } 4543 case ISD::FCANONICALIZE: 4544 case ISD::FEXP: 4545 case ISD::FEXP2: 4546 case ISD::FTRUNC: 4547 case ISD::FFLOOR: 4548 case ISD::FCEIL: 4549 case ISD::FROUND: 4550 case ISD::FROUNDEVEN: 4551 case ISD::FRINT: 4552 case ISD::FNEARBYINT: { 4553 if (SNaN) 4554 return true; 4555 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4556 } 4557 case ISD::FABS: 4558 case ISD::FNEG: 4559 case ISD::FCOPYSIGN: { 4560 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4561 } 4562 case ISD::SELECT: 4563 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4564 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4565 case ISD::FP_EXTEND: 4566 case ISD::FP_ROUND: { 4567 if (SNaN) 4568 return true; 4569 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4570 } 4571 case ISD::SINT_TO_FP: 4572 case ISD::UINT_TO_FP: 4573 return true; 4574 case ISD::FMA: 4575 case ISD::FMAD: { 4576 if (SNaN) 4577 return true; 4578 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4579 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4580 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4581 } 4582 case ISD::FSQRT: // Need is known positive 4583 case ISD::FLOG: 4584 case ISD::FLOG2: 4585 case ISD::FLOG10: 4586 case ISD::FPOWI: 4587 case ISD::FPOW: { 4588 if (SNaN) 4589 return true; 4590 // TODO: Refine on operand 4591 return false; 4592 } 4593 case ISD::FMINNUM: 4594 case ISD::FMAXNUM: { 4595 // Only one needs to be known not-nan, since it will be returned if the 4596 // other ends up being one. 4597 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4598 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4599 } 4600 case ISD::FMINNUM_IEEE: 4601 case ISD::FMAXNUM_IEEE: { 4602 if (SNaN) 4603 return true; 4604 // This can return a NaN if either operand is an sNaN, or if both operands 4605 // are NaN. 4606 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4607 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4608 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4609 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4610 } 4611 case ISD::FMINIMUM: 4612 case ISD::FMAXIMUM: { 4613 // TODO: Does this quiet or return the origina NaN as-is? 4614 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4615 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4616 } 4617 case ISD::EXTRACT_VECTOR_ELT: { 4618 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4619 } 4620 default: 4621 if (Opcode >= ISD::BUILTIN_OP_END || 4622 Opcode == ISD::INTRINSIC_WO_CHAIN || 4623 Opcode == ISD::INTRINSIC_W_CHAIN || 4624 Opcode == ISD::INTRINSIC_VOID) { 4625 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4626 } 4627 4628 return false; 4629 } 4630 } 4631 4632 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4633 assert(Op.getValueType().isFloatingPoint() && 4634 "Floating point type expected"); 4635 4636 // If the value is a constant, we can obviously see if it is a zero or not. 4637 // TODO: Add BuildVector support. 4638 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4639 return !C->isZero(); 4640 return false; 4641 } 4642 4643 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4644 assert(!Op.getValueType().isFloatingPoint() && 4645 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4646 4647 // If the value is a constant, we can obviously see if it is a zero or not. 4648 if (ISD::matchUnaryPredicate(Op, 4649 [](ConstantSDNode *C) { return !C->isZero(); })) 4650 return true; 4651 4652 // TODO: Recognize more cases here. 4653 switch (Op.getOpcode()) { 4654 default: break; 4655 case ISD::OR: 4656 if (isKnownNeverZero(Op.getOperand(1)) || 4657 isKnownNeverZero(Op.getOperand(0))) 4658 return true; 4659 break; 4660 } 4661 4662 return false; 4663 } 4664 4665 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4666 // Check the obvious case. 4667 if (A == B) return true; 4668 4669 // For for negative and positive zero. 4670 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4671 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4672 if (CA->isZero() && CB->isZero()) return true; 4673 4674 // Otherwise they may not be equal. 4675 return false; 4676 } 4677 4678 // FIXME: unify with llvm::haveNoCommonBitsSet. 4679 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4680 assert(A.getValueType() == B.getValueType() && 4681 "Values must have the same type"); 4682 // Match masked merge pattern (X & ~M) op (Y & M) 4683 if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) { 4684 auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) { 4685 if (isBitwiseNot(NotM, true)) { 4686 SDValue NotOperand = NotM->getOperand(0); 4687 return NotOperand == And->getOperand(0) || 4688 NotOperand == And->getOperand(1); 4689 } 4690 return false; 4691 }; 4692 if (MatchNoCommonBitsPattern(A->getOperand(0), B) || 4693 MatchNoCommonBitsPattern(A->getOperand(1), B) || 4694 MatchNoCommonBitsPattern(B->getOperand(0), A) || 4695 MatchNoCommonBitsPattern(B->getOperand(1), A)) 4696 return true; 4697 } 4698 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4699 computeKnownBits(B)); 4700 } 4701 4702 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4703 SelectionDAG &DAG) { 4704 if (cast<ConstantSDNode>(Step)->isZero()) 4705 return DAG.getConstant(0, DL, VT); 4706 4707 return SDValue(); 4708 } 4709 4710 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4711 ArrayRef<SDValue> Ops, 4712 SelectionDAG &DAG) { 4713 int NumOps = Ops.size(); 4714 assert(NumOps != 0 && "Can't build an empty vector!"); 4715 assert(!VT.isScalableVector() && 4716 "BUILD_VECTOR cannot be used with scalable types"); 4717 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4718 "Incorrect element count in BUILD_VECTOR!"); 4719 4720 // BUILD_VECTOR of UNDEFs is UNDEF. 4721 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4722 return DAG.getUNDEF(VT); 4723 4724 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4725 SDValue IdentitySrc; 4726 bool IsIdentity = true; 4727 for (int i = 0; i != NumOps; ++i) { 4728 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4729 Ops[i].getOperand(0).getValueType() != VT || 4730 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4731 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4732 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4733 IsIdentity = false; 4734 break; 4735 } 4736 IdentitySrc = Ops[i].getOperand(0); 4737 } 4738 if (IsIdentity) 4739 return IdentitySrc; 4740 4741 return SDValue(); 4742 } 4743 4744 /// Try to simplify vector concatenation to an input value, undef, or build 4745 /// vector. 4746 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4747 ArrayRef<SDValue> Ops, 4748 SelectionDAG &DAG) { 4749 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4750 assert(llvm::all_of(Ops, 4751 [Ops](SDValue Op) { 4752 return Ops[0].getValueType() == Op.getValueType(); 4753 }) && 4754 "Concatenation of vectors with inconsistent value types!"); 4755 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4756 VT.getVectorElementCount() && 4757 "Incorrect element count in vector concatenation!"); 4758 4759 if (Ops.size() == 1) 4760 return Ops[0]; 4761 4762 // Concat of UNDEFs is UNDEF. 4763 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4764 return DAG.getUNDEF(VT); 4765 4766 // Scan the operands and look for extract operations from a single source 4767 // that correspond to insertion at the same location via this concatenation: 4768 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4769 SDValue IdentitySrc; 4770 bool IsIdentity = true; 4771 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4772 SDValue Op = Ops[i]; 4773 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4774 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4775 Op.getOperand(0).getValueType() != VT || 4776 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4777 Op.getConstantOperandVal(1) != IdentityIndex) { 4778 IsIdentity = false; 4779 break; 4780 } 4781 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4782 "Unexpected identity source vector for concat of extracts"); 4783 IdentitySrc = Op.getOperand(0); 4784 } 4785 if (IsIdentity) { 4786 assert(IdentitySrc && "Failed to set source vector of extracts"); 4787 return IdentitySrc; 4788 } 4789 4790 // The code below this point is only designed to work for fixed width 4791 // vectors, so we bail out for now. 4792 if (VT.isScalableVector()) 4793 return SDValue(); 4794 4795 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4796 // simplified to one big BUILD_VECTOR. 4797 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4798 EVT SVT = VT.getScalarType(); 4799 SmallVector<SDValue, 16> Elts; 4800 for (SDValue Op : Ops) { 4801 EVT OpVT = Op.getValueType(); 4802 if (Op.isUndef()) 4803 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4804 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4805 Elts.append(Op->op_begin(), Op->op_end()); 4806 else 4807 return SDValue(); 4808 } 4809 4810 // BUILD_VECTOR requires all inputs to be of the same type, find the 4811 // maximum type and extend them all. 4812 for (SDValue Op : Elts) 4813 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4814 4815 if (SVT.bitsGT(VT.getScalarType())) { 4816 for (SDValue &Op : Elts) { 4817 if (Op.isUndef()) 4818 Op = DAG.getUNDEF(SVT); 4819 else 4820 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4821 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4822 : DAG.getSExtOrTrunc(Op, DL, SVT); 4823 } 4824 } 4825 4826 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4827 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4828 return V; 4829 } 4830 4831 /// Gets or creates the specified node. 4832 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4833 FoldingSetNodeID ID; 4834 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4835 void *IP = nullptr; 4836 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4837 return SDValue(E, 0); 4838 4839 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4840 getVTList(VT)); 4841 CSEMap.InsertNode(N, IP); 4842 4843 InsertNode(N); 4844 SDValue V = SDValue(N, 0); 4845 NewSDValueDbgMsg(V, "Creating new node: ", this); 4846 return V; 4847 } 4848 4849 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4850 SDValue Operand) { 4851 SDNodeFlags Flags; 4852 if (Inserter) 4853 Flags = Inserter->getFlags(); 4854 return getNode(Opcode, DL, VT, Operand, Flags); 4855 } 4856 4857 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4858 SDValue Operand, const SDNodeFlags Flags) { 4859 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4860 "Operand is DELETED_NODE!"); 4861 // Constant fold unary operations with an integer constant operand. Even 4862 // opaque constant will be folded, because the folding of unary operations 4863 // doesn't create new constants with different values. Nevertheless, the 4864 // opaque flag is preserved during folding to prevent future folding with 4865 // other constants. 4866 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4867 const APInt &Val = C->getAPIntValue(); 4868 switch (Opcode) { 4869 default: break; 4870 case ISD::SIGN_EXTEND: 4871 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4872 C->isTargetOpcode(), C->isOpaque()); 4873 case ISD::TRUNCATE: 4874 if (C->isOpaque()) 4875 break; 4876 LLVM_FALLTHROUGH; 4877 case ISD::ZERO_EXTEND: 4878 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4879 C->isTargetOpcode(), C->isOpaque()); 4880 case ISD::ANY_EXTEND: 4881 // Some targets like RISCV prefer to sign extend some types. 4882 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4883 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4884 C->isTargetOpcode(), C->isOpaque()); 4885 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4886 C->isTargetOpcode(), C->isOpaque()); 4887 case ISD::UINT_TO_FP: 4888 case ISD::SINT_TO_FP: { 4889 APFloat apf(EVTToAPFloatSemantics(VT), 4890 APInt::getZero(VT.getSizeInBits())); 4891 (void)apf.convertFromAPInt(Val, 4892 Opcode==ISD::SINT_TO_FP, 4893 APFloat::rmNearestTiesToEven); 4894 return getConstantFP(apf, DL, VT); 4895 } 4896 case ISD::BITCAST: 4897 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4898 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4899 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4900 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4901 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4902 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4903 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4904 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4905 break; 4906 case ISD::ABS: 4907 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4908 C->isOpaque()); 4909 case ISD::BITREVERSE: 4910 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4911 C->isOpaque()); 4912 case ISD::BSWAP: 4913 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4914 C->isOpaque()); 4915 case ISD::CTPOP: 4916 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4917 C->isOpaque()); 4918 case ISD::CTLZ: 4919 case ISD::CTLZ_ZERO_UNDEF: 4920 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4921 C->isOpaque()); 4922 case ISD::CTTZ: 4923 case ISD::CTTZ_ZERO_UNDEF: 4924 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4925 C->isOpaque()); 4926 case ISD::FP16_TO_FP: { 4927 bool Ignored; 4928 APFloat FPV(APFloat::IEEEhalf(), 4929 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4930 4931 // This can return overflow, underflow, or inexact; we don't care. 4932 // FIXME need to be more flexible about rounding mode. 4933 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4934 APFloat::rmNearestTiesToEven, &Ignored); 4935 return getConstantFP(FPV, DL, VT); 4936 } 4937 case ISD::STEP_VECTOR: { 4938 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4939 return V; 4940 break; 4941 } 4942 } 4943 } 4944 4945 // Constant fold unary operations with a floating point constant operand. 4946 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4947 APFloat V = C->getValueAPF(); // make copy 4948 switch (Opcode) { 4949 case ISD::FNEG: 4950 V.changeSign(); 4951 return getConstantFP(V, DL, VT); 4952 case ISD::FABS: 4953 V.clearSign(); 4954 return getConstantFP(V, DL, VT); 4955 case ISD::FCEIL: { 4956 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4957 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4958 return getConstantFP(V, DL, VT); 4959 break; 4960 } 4961 case ISD::FTRUNC: { 4962 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4963 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4964 return getConstantFP(V, DL, VT); 4965 break; 4966 } 4967 case ISD::FFLOOR: { 4968 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4969 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4970 return getConstantFP(V, DL, VT); 4971 break; 4972 } 4973 case ISD::FP_EXTEND: { 4974 bool ignored; 4975 // This can return overflow, underflow, or inexact; we don't care. 4976 // FIXME need to be more flexible about rounding mode. 4977 (void)V.convert(EVTToAPFloatSemantics(VT), 4978 APFloat::rmNearestTiesToEven, &ignored); 4979 return getConstantFP(V, DL, VT); 4980 } 4981 case ISD::FP_TO_SINT: 4982 case ISD::FP_TO_UINT: { 4983 bool ignored; 4984 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4985 // FIXME need to be more flexible about rounding mode. 4986 APFloat::opStatus s = 4987 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4988 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4989 break; 4990 return getConstant(IntVal, DL, VT); 4991 } 4992 case ISD::BITCAST: 4993 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4994 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4995 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4996 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4997 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4998 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4999 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 5000 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5001 break; 5002 case ISD::FP_TO_FP16: { 5003 bool Ignored; 5004 // This can return overflow, underflow, or inexact; we don't care. 5005 // FIXME need to be more flexible about rounding mode. 5006 (void)V.convert(APFloat::IEEEhalf(), 5007 APFloat::rmNearestTiesToEven, &Ignored); 5008 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5009 } 5010 } 5011 } 5012 5013 // Constant fold unary operations with a vector integer or float operand. 5014 switch (Opcode) { 5015 default: 5016 // FIXME: Entirely reasonable to perform folding of other unary 5017 // operations here as the need arises. 5018 break; 5019 case ISD::FNEG: 5020 case ISD::FABS: 5021 case ISD::FCEIL: 5022 case ISD::FTRUNC: 5023 case ISD::FFLOOR: 5024 case ISD::FP_EXTEND: 5025 case ISD::FP_TO_SINT: 5026 case ISD::FP_TO_UINT: 5027 case ISD::TRUNCATE: 5028 case ISD::ANY_EXTEND: 5029 case ISD::ZERO_EXTEND: 5030 case ISD::SIGN_EXTEND: 5031 case ISD::UINT_TO_FP: 5032 case ISD::SINT_TO_FP: 5033 case ISD::ABS: 5034 case ISD::BITREVERSE: 5035 case ISD::BSWAP: 5036 case ISD::CTLZ: 5037 case ISD::CTLZ_ZERO_UNDEF: 5038 case ISD::CTTZ: 5039 case ISD::CTTZ_ZERO_UNDEF: 5040 case ISD::CTPOP: { 5041 SDValue Ops = {Operand}; 5042 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5043 return Fold; 5044 } 5045 } 5046 5047 unsigned OpOpcode = Operand.getNode()->getOpcode(); 5048 switch (Opcode) { 5049 case ISD::STEP_VECTOR: 5050 assert(VT.isScalableVector() && 5051 "STEP_VECTOR can only be used with scalable types"); 5052 assert(OpOpcode == ISD::TargetConstant && 5053 VT.getVectorElementType() == Operand.getValueType() && 5054 "Unexpected step operand"); 5055 break; 5056 case ISD::FREEZE: 5057 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5058 break; 5059 case ISD::TokenFactor: 5060 case ISD::MERGE_VALUES: 5061 case ISD::CONCAT_VECTORS: 5062 return Operand; // Factor, merge or concat of one node? No need. 5063 case ISD::BUILD_VECTOR: { 5064 // Attempt to simplify BUILD_VECTOR. 5065 SDValue Ops[] = {Operand}; 5066 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5067 return V; 5068 break; 5069 } 5070 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5071 case ISD::FP_EXTEND: 5072 assert(VT.isFloatingPoint() && 5073 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 5074 if (Operand.getValueType() == VT) return Operand; // noop conversion. 5075 assert((!VT.isVector() || 5076 VT.getVectorElementCount() == 5077 Operand.getValueType().getVectorElementCount()) && 5078 "Vector element count mismatch!"); 5079 assert(Operand.getValueType().bitsLT(VT) && 5080 "Invalid fpext node, dst < src!"); 5081 if (Operand.isUndef()) 5082 return getUNDEF(VT); 5083 break; 5084 case ISD::FP_TO_SINT: 5085 case ISD::FP_TO_UINT: 5086 if (Operand.isUndef()) 5087 return getUNDEF(VT); 5088 break; 5089 case ISD::SINT_TO_FP: 5090 case ISD::UINT_TO_FP: 5091 // [us]itofp(undef) = 0, because the result value is bounded. 5092 if (Operand.isUndef()) 5093 return getConstantFP(0.0, DL, VT); 5094 break; 5095 case ISD::SIGN_EXTEND: 5096 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5097 "Invalid SIGN_EXTEND!"); 5098 assert(VT.isVector() == Operand.getValueType().isVector() && 5099 "SIGN_EXTEND result type type should be vector iff the operand " 5100 "type is vector!"); 5101 if (Operand.getValueType() == VT) return Operand; // noop extension 5102 assert((!VT.isVector() || 5103 VT.getVectorElementCount() == 5104 Operand.getValueType().getVectorElementCount()) && 5105 "Vector element count mismatch!"); 5106 assert(Operand.getValueType().bitsLT(VT) && 5107 "Invalid sext node, dst < src!"); 5108 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5109 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5110 if (OpOpcode == ISD::UNDEF) 5111 // sext(undef) = 0, because the top bits will all be the same. 5112 return getConstant(0, DL, VT); 5113 break; 5114 case ISD::ZERO_EXTEND: 5115 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5116 "Invalid ZERO_EXTEND!"); 5117 assert(VT.isVector() == Operand.getValueType().isVector() && 5118 "ZERO_EXTEND result type type should be vector iff the operand " 5119 "type is vector!"); 5120 if (Operand.getValueType() == VT) return Operand; // noop extension 5121 assert((!VT.isVector() || 5122 VT.getVectorElementCount() == 5123 Operand.getValueType().getVectorElementCount()) && 5124 "Vector element count mismatch!"); 5125 assert(Operand.getValueType().bitsLT(VT) && 5126 "Invalid zext node, dst < src!"); 5127 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5128 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5129 if (OpOpcode == ISD::UNDEF) 5130 // zext(undef) = 0, because the top bits will be zero. 5131 return getConstant(0, DL, VT); 5132 break; 5133 case ISD::ANY_EXTEND: 5134 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5135 "Invalid ANY_EXTEND!"); 5136 assert(VT.isVector() == Operand.getValueType().isVector() && 5137 "ANY_EXTEND result type type should be vector iff the operand " 5138 "type is vector!"); 5139 if (Operand.getValueType() == VT) return Operand; // noop extension 5140 assert((!VT.isVector() || 5141 VT.getVectorElementCount() == 5142 Operand.getValueType().getVectorElementCount()) && 5143 "Vector element count mismatch!"); 5144 assert(Operand.getValueType().bitsLT(VT) && 5145 "Invalid anyext node, dst < src!"); 5146 5147 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5148 OpOpcode == ISD::ANY_EXTEND) 5149 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5150 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5151 if (OpOpcode == ISD::UNDEF) 5152 return getUNDEF(VT); 5153 5154 // (ext (trunc x)) -> x 5155 if (OpOpcode == ISD::TRUNCATE) { 5156 SDValue OpOp = Operand.getOperand(0); 5157 if (OpOp.getValueType() == VT) { 5158 transferDbgValues(Operand, OpOp); 5159 return OpOp; 5160 } 5161 } 5162 break; 5163 case ISD::TRUNCATE: 5164 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5165 "Invalid TRUNCATE!"); 5166 assert(VT.isVector() == Operand.getValueType().isVector() && 5167 "TRUNCATE result type type should be vector iff the operand " 5168 "type is vector!"); 5169 if (Operand.getValueType() == VT) return Operand; // noop truncate 5170 assert((!VT.isVector() || 5171 VT.getVectorElementCount() == 5172 Operand.getValueType().getVectorElementCount()) && 5173 "Vector element count mismatch!"); 5174 assert(Operand.getValueType().bitsGT(VT) && 5175 "Invalid truncate node, src < dst!"); 5176 if (OpOpcode == ISD::TRUNCATE) 5177 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5178 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5179 OpOpcode == ISD::ANY_EXTEND) { 5180 // If the source is smaller than the dest, we still need an extend. 5181 if (Operand.getOperand(0).getValueType().getScalarType() 5182 .bitsLT(VT.getScalarType())) 5183 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5184 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5185 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5186 return Operand.getOperand(0); 5187 } 5188 if (OpOpcode == ISD::UNDEF) 5189 return getUNDEF(VT); 5190 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5191 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5192 break; 5193 case ISD::ANY_EXTEND_VECTOR_INREG: 5194 case ISD::ZERO_EXTEND_VECTOR_INREG: 5195 case ISD::SIGN_EXTEND_VECTOR_INREG: 5196 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5197 assert(Operand.getValueType().bitsLE(VT) && 5198 "The input must be the same size or smaller than the result."); 5199 assert(VT.getVectorMinNumElements() < 5200 Operand.getValueType().getVectorMinNumElements() && 5201 "The destination vector type must have fewer lanes than the input."); 5202 break; 5203 case ISD::ABS: 5204 assert(VT.isInteger() && VT == Operand.getValueType() && 5205 "Invalid ABS!"); 5206 if (OpOpcode == ISD::UNDEF) 5207 return getUNDEF(VT); 5208 break; 5209 case ISD::BSWAP: 5210 assert(VT.isInteger() && VT == Operand.getValueType() && 5211 "Invalid BSWAP!"); 5212 assert((VT.getScalarSizeInBits() % 16 == 0) && 5213 "BSWAP types must be a multiple of 16 bits!"); 5214 if (OpOpcode == ISD::UNDEF) 5215 return getUNDEF(VT); 5216 // bswap(bswap(X)) -> X. 5217 if (OpOpcode == ISD::BSWAP) 5218 return Operand.getOperand(0); 5219 break; 5220 case ISD::BITREVERSE: 5221 assert(VT.isInteger() && VT == Operand.getValueType() && 5222 "Invalid BITREVERSE!"); 5223 if (OpOpcode == ISD::UNDEF) 5224 return getUNDEF(VT); 5225 break; 5226 case ISD::BITCAST: 5227 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5228 "Cannot BITCAST between types of different sizes!"); 5229 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5230 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5231 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5232 if (OpOpcode == ISD::UNDEF) 5233 return getUNDEF(VT); 5234 break; 5235 case ISD::SCALAR_TO_VECTOR: 5236 assert(VT.isVector() && !Operand.getValueType().isVector() && 5237 (VT.getVectorElementType() == Operand.getValueType() || 5238 (VT.getVectorElementType().isInteger() && 5239 Operand.getValueType().isInteger() && 5240 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5241 "Illegal SCALAR_TO_VECTOR node!"); 5242 if (OpOpcode == ISD::UNDEF) 5243 return getUNDEF(VT); 5244 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5245 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5246 isa<ConstantSDNode>(Operand.getOperand(1)) && 5247 Operand.getConstantOperandVal(1) == 0 && 5248 Operand.getOperand(0).getValueType() == VT) 5249 return Operand.getOperand(0); 5250 break; 5251 case ISD::FNEG: 5252 // Negation of an unknown bag of bits is still completely undefined. 5253 if (OpOpcode == ISD::UNDEF) 5254 return getUNDEF(VT); 5255 5256 if (OpOpcode == ISD::FNEG) // --X -> X 5257 return Operand.getOperand(0); 5258 break; 5259 case ISD::FABS: 5260 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5261 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5262 break; 5263 case ISD::VSCALE: 5264 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5265 break; 5266 case ISD::CTPOP: 5267 if (Operand.getValueType().getScalarType() == MVT::i1) 5268 return Operand; 5269 break; 5270 case ISD::CTLZ: 5271 case ISD::CTTZ: 5272 if (Operand.getValueType().getScalarType() == MVT::i1) 5273 return getNOT(DL, Operand, Operand.getValueType()); 5274 break; 5275 case ISD::VECREDUCE_SMIN: 5276 case ISD::VECREDUCE_UMAX: 5277 if (Operand.getValueType().getScalarType() == MVT::i1) 5278 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5279 break; 5280 case ISD::VECREDUCE_SMAX: 5281 case ISD::VECREDUCE_UMIN: 5282 if (Operand.getValueType().getScalarType() == MVT::i1) 5283 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5284 break; 5285 } 5286 5287 SDNode *N; 5288 SDVTList VTs = getVTList(VT); 5289 SDValue Ops[] = {Operand}; 5290 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5291 FoldingSetNodeID ID; 5292 AddNodeIDNode(ID, Opcode, VTs, Ops); 5293 void *IP = nullptr; 5294 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5295 E->intersectFlagsWith(Flags); 5296 return SDValue(E, 0); 5297 } 5298 5299 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5300 N->setFlags(Flags); 5301 createOperands(N, Ops); 5302 CSEMap.InsertNode(N, IP); 5303 } else { 5304 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5305 createOperands(N, Ops); 5306 } 5307 5308 InsertNode(N); 5309 SDValue V = SDValue(N, 0); 5310 NewSDValueDbgMsg(V, "Creating new node: ", this); 5311 return V; 5312 } 5313 5314 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5315 const APInt &C2) { 5316 switch (Opcode) { 5317 case ISD::ADD: return C1 + C2; 5318 case ISD::SUB: return C1 - C2; 5319 case ISD::MUL: return C1 * C2; 5320 case ISD::AND: return C1 & C2; 5321 case ISD::OR: return C1 | C2; 5322 case ISD::XOR: return C1 ^ C2; 5323 case ISD::SHL: return C1 << C2; 5324 case ISD::SRL: return C1.lshr(C2); 5325 case ISD::SRA: return C1.ashr(C2); 5326 case ISD::ROTL: return C1.rotl(C2); 5327 case ISD::ROTR: return C1.rotr(C2); 5328 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5329 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5330 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5331 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5332 case ISD::SADDSAT: return C1.sadd_sat(C2); 5333 case ISD::UADDSAT: return C1.uadd_sat(C2); 5334 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5335 case ISD::USUBSAT: return C1.usub_sat(C2); 5336 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5337 case ISD::USHLSAT: return C1.ushl_sat(C2); 5338 case ISD::UDIV: 5339 if (!C2.getBoolValue()) 5340 break; 5341 return C1.udiv(C2); 5342 case ISD::UREM: 5343 if (!C2.getBoolValue()) 5344 break; 5345 return C1.urem(C2); 5346 case ISD::SDIV: 5347 if (!C2.getBoolValue()) 5348 break; 5349 return C1.sdiv(C2); 5350 case ISD::SREM: 5351 if (!C2.getBoolValue()) 5352 break; 5353 return C1.srem(C2); 5354 case ISD::MULHS: { 5355 unsigned FullWidth = C1.getBitWidth() * 2; 5356 APInt C1Ext = C1.sext(FullWidth); 5357 APInt C2Ext = C2.sext(FullWidth); 5358 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5359 } 5360 case ISD::MULHU: { 5361 unsigned FullWidth = C1.getBitWidth() * 2; 5362 APInt C1Ext = C1.zext(FullWidth); 5363 APInt C2Ext = C2.zext(FullWidth); 5364 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5365 } 5366 case ISD::AVGFLOORS: { 5367 unsigned FullWidth = C1.getBitWidth() + 1; 5368 APInt C1Ext = C1.sext(FullWidth); 5369 APInt C2Ext = C2.sext(FullWidth); 5370 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5371 } 5372 case ISD::AVGFLOORU: { 5373 unsigned FullWidth = C1.getBitWidth() + 1; 5374 APInt C1Ext = C1.zext(FullWidth); 5375 APInt C2Ext = C2.zext(FullWidth); 5376 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5377 } 5378 case ISD::AVGCEILS: { 5379 unsigned FullWidth = C1.getBitWidth() + 1; 5380 APInt C1Ext = C1.sext(FullWidth); 5381 APInt C2Ext = C2.sext(FullWidth); 5382 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5383 } 5384 case ISD::AVGCEILU: { 5385 unsigned FullWidth = C1.getBitWidth() + 1; 5386 APInt C1Ext = C1.zext(FullWidth); 5387 APInt C2Ext = C2.zext(FullWidth); 5388 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5389 } 5390 } 5391 return llvm::None; 5392 } 5393 5394 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5395 const GlobalAddressSDNode *GA, 5396 const SDNode *N2) { 5397 if (GA->getOpcode() != ISD::GlobalAddress) 5398 return SDValue(); 5399 if (!TLI->isOffsetFoldingLegal(GA)) 5400 return SDValue(); 5401 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5402 if (!C2) 5403 return SDValue(); 5404 int64_t Offset = C2->getSExtValue(); 5405 switch (Opcode) { 5406 case ISD::ADD: break; 5407 case ISD::SUB: Offset = -uint64_t(Offset); break; 5408 default: return SDValue(); 5409 } 5410 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5411 GA->getOffset() + uint64_t(Offset)); 5412 } 5413 5414 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5415 switch (Opcode) { 5416 case ISD::SDIV: 5417 case ISD::UDIV: 5418 case ISD::SREM: 5419 case ISD::UREM: { 5420 // If a divisor is zero/undef or any element of a divisor vector is 5421 // zero/undef, the whole op is undef. 5422 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5423 SDValue Divisor = Ops[1]; 5424 if (Divisor.isUndef() || isNullConstant(Divisor)) 5425 return true; 5426 5427 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5428 llvm::any_of(Divisor->op_values(), 5429 [](SDValue V) { return V.isUndef() || 5430 isNullConstant(V); }); 5431 // TODO: Handle signed overflow. 5432 } 5433 // TODO: Handle oversized shifts. 5434 default: 5435 return false; 5436 } 5437 } 5438 5439 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5440 EVT VT, ArrayRef<SDValue> Ops) { 5441 // If the opcode is a target-specific ISD node, there's nothing we can 5442 // do here and the operand rules may not line up with the below, so 5443 // bail early. 5444 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5445 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5446 // foldCONCAT_VECTORS in getNode before this is called. 5447 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5448 return SDValue(); 5449 5450 unsigned NumOps = Ops.size(); 5451 if (NumOps == 0) 5452 return SDValue(); 5453 5454 if (isUndef(Opcode, Ops)) 5455 return getUNDEF(VT); 5456 5457 // Handle binops special cases. 5458 if (NumOps == 2) { 5459 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5460 return CFP; 5461 5462 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5463 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5464 if (C1->isOpaque() || C2->isOpaque()) 5465 return SDValue(); 5466 5467 Optional<APInt> FoldAttempt = 5468 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5469 if (!FoldAttempt) 5470 return SDValue(); 5471 5472 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5473 assert((!Folded || !VT.isVector()) && 5474 "Can't fold vectors ops with scalar operands"); 5475 return Folded; 5476 } 5477 } 5478 5479 // fold (add Sym, c) -> Sym+c 5480 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5481 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5482 if (TLI->isCommutativeBinOp(Opcode)) 5483 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5484 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5485 } 5486 5487 // This is for vector folding only from here on. 5488 if (!VT.isVector()) 5489 return SDValue(); 5490 5491 ElementCount NumElts = VT.getVectorElementCount(); 5492 5493 // See if we can fold through bitcasted integer ops. 5494 // TODO: Can we handle undef elements? 5495 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5496 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5497 Ops[0].getOpcode() == ISD::BITCAST && 5498 Ops[1].getOpcode() == ISD::BITCAST) { 5499 SDValue N1 = peekThroughBitcasts(Ops[0]); 5500 SDValue N2 = peekThroughBitcasts(Ops[1]); 5501 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5502 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5503 EVT BVVT = N1.getValueType(); 5504 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5505 bool IsLE = getDataLayout().isLittleEndian(); 5506 unsigned EltBits = VT.getScalarSizeInBits(); 5507 SmallVector<APInt> RawBits1, RawBits2; 5508 BitVector UndefElts1, UndefElts2; 5509 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5510 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5511 UndefElts1.none() && UndefElts2.none()) { 5512 SmallVector<APInt> RawBits; 5513 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5514 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5515 if (!Fold) 5516 break; 5517 RawBits.push_back(Fold.getValue()); 5518 } 5519 if (RawBits.size() == NumElts.getFixedValue()) { 5520 // We have constant folded, but we need to cast this again back to 5521 // the original (possibly legalized) type. 5522 SmallVector<APInt> DstBits; 5523 BitVector DstUndefs; 5524 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5525 DstBits, RawBits, DstUndefs, 5526 BitVector(RawBits.size(), false)); 5527 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5528 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5529 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5530 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5531 if (DstUndefs[I]) 5532 continue; 5533 Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT); 5534 } 5535 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5536 } 5537 } 5538 } 5539 } 5540 5541 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5542 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5543 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5544 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5545 APInt RHSVal; 5546 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5547 APInt NewStep = Opcode == ISD::MUL 5548 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5549 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5550 return getStepVector(DL, VT, NewStep); 5551 } 5552 } 5553 5554 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5555 return !Op.getValueType().isVector() || 5556 Op.getValueType().getVectorElementCount() == NumElts; 5557 }; 5558 5559 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5560 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5561 Op.getOpcode() == ISD::BUILD_VECTOR || 5562 Op.getOpcode() == ISD::SPLAT_VECTOR; 5563 }; 5564 5565 // All operands must be vector types with the same number of elements as 5566 // the result type and must be either UNDEF or a build/splat vector 5567 // or UNDEF scalars. 5568 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5569 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5570 return SDValue(); 5571 5572 // If we are comparing vectors, then the result needs to be a i1 boolean 5573 // that is then sign-extended back to the legal result type. 5574 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5575 5576 // Find legal integer scalar type for constant promotion and 5577 // ensure that its scalar size is at least as large as source. 5578 EVT LegalSVT = VT.getScalarType(); 5579 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5580 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5581 if (LegalSVT.bitsLT(VT.getScalarType())) 5582 return SDValue(); 5583 } 5584 5585 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5586 // only have one operand to check. For fixed-length vector types we may have 5587 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5588 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5589 5590 // Constant fold each scalar lane separately. 5591 SmallVector<SDValue, 4> ScalarResults; 5592 for (unsigned I = 0; I != NumVectorElts; I++) { 5593 SmallVector<SDValue, 4> ScalarOps; 5594 for (SDValue Op : Ops) { 5595 EVT InSVT = Op.getValueType().getScalarType(); 5596 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5597 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5598 if (Op.isUndef()) 5599 ScalarOps.push_back(getUNDEF(InSVT)); 5600 else 5601 ScalarOps.push_back(Op); 5602 continue; 5603 } 5604 5605 SDValue ScalarOp = 5606 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5607 EVT ScalarVT = ScalarOp.getValueType(); 5608 5609 // Build vector (integer) scalar operands may need implicit 5610 // truncation - do this before constant folding. 5611 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5612 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5613 5614 ScalarOps.push_back(ScalarOp); 5615 } 5616 5617 // Constant fold the scalar operands. 5618 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5619 5620 // Legalize the (integer) scalar constant if necessary. 5621 if (LegalSVT != SVT) 5622 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5623 5624 // Scalar folding only succeeded if the result is a constant or UNDEF. 5625 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5626 ScalarResult.getOpcode() != ISD::ConstantFP) 5627 return SDValue(); 5628 ScalarResults.push_back(ScalarResult); 5629 } 5630 5631 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5632 : getBuildVector(VT, DL, ScalarResults); 5633 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5634 return V; 5635 } 5636 5637 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5638 EVT VT, SDValue N1, SDValue N2) { 5639 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5640 // should. That will require dealing with a potentially non-default 5641 // rounding mode, checking the "opStatus" return value from the APFloat 5642 // math calculations, and possibly other variations. 5643 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5644 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5645 if (N1CFP && N2CFP) { 5646 APFloat C1 = N1CFP->getValueAPF(); // make copy 5647 const APFloat &C2 = N2CFP->getValueAPF(); 5648 switch (Opcode) { 5649 case ISD::FADD: 5650 C1.add(C2, APFloat::rmNearestTiesToEven); 5651 return getConstantFP(C1, DL, VT); 5652 case ISD::FSUB: 5653 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5654 return getConstantFP(C1, DL, VT); 5655 case ISD::FMUL: 5656 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5657 return getConstantFP(C1, DL, VT); 5658 case ISD::FDIV: 5659 C1.divide(C2, APFloat::rmNearestTiesToEven); 5660 return getConstantFP(C1, DL, VT); 5661 case ISD::FREM: 5662 C1.mod(C2); 5663 return getConstantFP(C1, DL, VT); 5664 case ISD::FCOPYSIGN: 5665 C1.copySign(C2); 5666 return getConstantFP(C1, DL, VT); 5667 case ISD::FMINNUM: 5668 return getConstantFP(minnum(C1, C2), DL, VT); 5669 case ISD::FMAXNUM: 5670 return getConstantFP(maxnum(C1, C2), DL, VT); 5671 case ISD::FMINIMUM: 5672 return getConstantFP(minimum(C1, C2), DL, VT); 5673 case ISD::FMAXIMUM: 5674 return getConstantFP(maximum(C1, C2), DL, VT); 5675 default: break; 5676 } 5677 } 5678 if (N1CFP && Opcode == ISD::FP_ROUND) { 5679 APFloat C1 = N1CFP->getValueAPF(); // make copy 5680 bool Unused; 5681 // This can return overflow, underflow, or inexact; we don't care. 5682 // FIXME need to be more flexible about rounding mode. 5683 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5684 &Unused); 5685 return getConstantFP(C1, DL, VT); 5686 } 5687 5688 switch (Opcode) { 5689 case ISD::FSUB: 5690 // -0.0 - undef --> undef (consistent with "fneg undef") 5691 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5692 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5693 return getUNDEF(VT); 5694 LLVM_FALLTHROUGH; 5695 5696 case ISD::FADD: 5697 case ISD::FMUL: 5698 case ISD::FDIV: 5699 case ISD::FREM: 5700 // If both operands are undef, the result is undef. If 1 operand is undef, 5701 // the result is NaN. This should match the behavior of the IR optimizer. 5702 if (N1.isUndef() && N2.isUndef()) 5703 return getUNDEF(VT); 5704 if (N1.isUndef() || N2.isUndef()) 5705 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5706 } 5707 return SDValue(); 5708 } 5709 5710 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5711 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5712 5713 // There's no need to assert on a byte-aligned pointer. All pointers are at 5714 // least byte aligned. 5715 if (A == Align(1)) 5716 return Val; 5717 5718 FoldingSetNodeID ID; 5719 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5720 ID.AddInteger(A.value()); 5721 5722 void *IP = nullptr; 5723 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5724 return SDValue(E, 0); 5725 5726 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5727 Val.getValueType(), A); 5728 createOperands(N, {Val}); 5729 5730 CSEMap.InsertNode(N, IP); 5731 InsertNode(N); 5732 5733 SDValue V(N, 0); 5734 NewSDValueDbgMsg(V, "Creating new node: ", this); 5735 return V; 5736 } 5737 5738 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5739 SDValue N1, SDValue N2) { 5740 SDNodeFlags Flags; 5741 if (Inserter) 5742 Flags = Inserter->getFlags(); 5743 return getNode(Opcode, DL, VT, N1, N2, Flags); 5744 } 5745 5746 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5747 SDValue &N2) const { 5748 if (!TLI->isCommutativeBinOp(Opcode)) 5749 return; 5750 5751 // Canonicalize: 5752 // binop(const, nonconst) -> binop(nonconst, const) 5753 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5754 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5755 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5756 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5757 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5758 std::swap(N1, N2); 5759 5760 // Canonicalize: 5761 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5762 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5763 N2.getOpcode() == ISD::STEP_VECTOR) 5764 std::swap(N1, N2); 5765 } 5766 5767 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5768 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5769 assert(N1.getOpcode() != ISD::DELETED_NODE && 5770 N2.getOpcode() != ISD::DELETED_NODE && 5771 "Operand is DELETED_NODE!"); 5772 5773 canonicalizeCommutativeBinop(Opcode, N1, N2); 5774 5775 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5776 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5777 5778 // Don't allow undefs in vector splats - we might be returning N2 when folding 5779 // to zero etc. 5780 ConstantSDNode *N2CV = 5781 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5782 5783 switch (Opcode) { 5784 default: break; 5785 case ISD::TokenFactor: 5786 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5787 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5788 // Fold trivial token factors. 5789 if (N1.getOpcode() == ISD::EntryToken) return N2; 5790 if (N2.getOpcode() == ISD::EntryToken) return N1; 5791 if (N1 == N2) return N1; 5792 break; 5793 case ISD::BUILD_VECTOR: { 5794 // Attempt to simplify BUILD_VECTOR. 5795 SDValue Ops[] = {N1, N2}; 5796 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5797 return V; 5798 break; 5799 } 5800 case ISD::CONCAT_VECTORS: { 5801 SDValue Ops[] = {N1, N2}; 5802 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5803 return V; 5804 break; 5805 } 5806 case ISD::AND: 5807 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5808 assert(N1.getValueType() == N2.getValueType() && 5809 N1.getValueType() == VT && "Binary operator types must match!"); 5810 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5811 // worth handling here. 5812 if (N2CV && N2CV->isZero()) 5813 return N2; 5814 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5815 return N1; 5816 break; 5817 case ISD::OR: 5818 case ISD::XOR: 5819 case ISD::ADD: 5820 case ISD::SUB: 5821 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5822 assert(N1.getValueType() == N2.getValueType() && 5823 N1.getValueType() == VT && "Binary operator types must match!"); 5824 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5825 // it's worth handling here. 5826 if (N2CV && N2CV->isZero()) 5827 return N1; 5828 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5829 VT.getVectorElementType() == MVT::i1) 5830 return getNode(ISD::XOR, DL, VT, N1, N2); 5831 break; 5832 case ISD::MUL: 5833 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5834 assert(N1.getValueType() == N2.getValueType() && 5835 N1.getValueType() == VT && "Binary operator types must match!"); 5836 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5837 return getNode(ISD::AND, DL, VT, N1, N2); 5838 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5839 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5840 const APInt &N2CImm = N2C->getAPIntValue(); 5841 return getVScale(DL, VT, MulImm * N2CImm); 5842 } 5843 break; 5844 case ISD::UDIV: 5845 case ISD::UREM: 5846 case ISD::MULHU: 5847 case ISD::MULHS: 5848 case ISD::SDIV: 5849 case ISD::SREM: 5850 case ISD::SADDSAT: 5851 case ISD::SSUBSAT: 5852 case ISD::UADDSAT: 5853 case ISD::USUBSAT: 5854 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5855 assert(N1.getValueType() == N2.getValueType() && 5856 N1.getValueType() == VT && "Binary operator types must match!"); 5857 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5858 // fold (add_sat x, y) -> (or x, y) for bool types. 5859 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5860 return getNode(ISD::OR, DL, VT, N1, N2); 5861 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5862 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5863 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5864 } 5865 break; 5866 case ISD::SMIN: 5867 case ISD::UMAX: 5868 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5869 assert(N1.getValueType() == N2.getValueType() && 5870 N1.getValueType() == VT && "Binary operator types must match!"); 5871 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5872 return getNode(ISD::OR, DL, VT, N1, N2); 5873 break; 5874 case ISD::SMAX: 5875 case ISD::UMIN: 5876 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5877 assert(N1.getValueType() == N2.getValueType() && 5878 N1.getValueType() == VT && "Binary operator types must match!"); 5879 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5880 return getNode(ISD::AND, DL, VT, N1, N2); 5881 break; 5882 case ISD::FADD: 5883 case ISD::FSUB: 5884 case ISD::FMUL: 5885 case ISD::FDIV: 5886 case ISD::FREM: 5887 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5888 assert(N1.getValueType() == N2.getValueType() && 5889 N1.getValueType() == VT && "Binary operator types must match!"); 5890 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5891 return V; 5892 break; 5893 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5894 assert(N1.getValueType() == VT && 5895 N1.getValueType().isFloatingPoint() && 5896 N2.getValueType().isFloatingPoint() && 5897 "Invalid FCOPYSIGN!"); 5898 break; 5899 case ISD::SHL: 5900 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5901 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5902 const APInt &ShiftImm = N2C->getAPIntValue(); 5903 return getVScale(DL, VT, MulImm << ShiftImm); 5904 } 5905 LLVM_FALLTHROUGH; 5906 case ISD::SRA: 5907 case ISD::SRL: 5908 if (SDValue V = simplifyShift(N1, N2)) 5909 return V; 5910 LLVM_FALLTHROUGH; 5911 case ISD::ROTL: 5912 case ISD::ROTR: 5913 assert(VT == N1.getValueType() && 5914 "Shift operators return type must be the same as their first arg"); 5915 assert(VT.isInteger() && N2.getValueType().isInteger() && 5916 "Shifts only work on integers"); 5917 assert((!VT.isVector() || VT == N2.getValueType()) && 5918 "Vector shift amounts must be in the same as their first arg"); 5919 // Verify that the shift amount VT is big enough to hold valid shift 5920 // amounts. This catches things like trying to shift an i1024 value by an 5921 // i8, which is easy to fall into in generic code that uses 5922 // TLI.getShiftAmount(). 5923 assert(N2.getValueType().getScalarSizeInBits() >= 5924 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5925 "Invalid use of small shift amount with oversized value!"); 5926 5927 // Always fold shifts of i1 values so the code generator doesn't need to 5928 // handle them. Since we know the size of the shift has to be less than the 5929 // size of the value, the shift/rotate count is guaranteed to be zero. 5930 if (VT == MVT::i1) 5931 return N1; 5932 if (N2CV && N2CV->isZero()) 5933 return N1; 5934 break; 5935 case ISD::FP_ROUND: 5936 assert(VT.isFloatingPoint() && 5937 N1.getValueType().isFloatingPoint() && 5938 VT.bitsLE(N1.getValueType()) && 5939 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5940 "Invalid FP_ROUND!"); 5941 if (N1.getValueType() == VT) return N1; // noop conversion. 5942 break; 5943 case ISD::AssertSext: 5944 case ISD::AssertZext: { 5945 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5946 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5947 assert(VT.isInteger() && EVT.isInteger() && 5948 "Cannot *_EXTEND_INREG FP types"); 5949 assert(!EVT.isVector() && 5950 "AssertSExt/AssertZExt type should be the vector element type " 5951 "rather than the vector type!"); 5952 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5953 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5954 break; 5955 } 5956 case ISD::SIGN_EXTEND_INREG: { 5957 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5958 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5959 assert(VT.isInteger() && EVT.isInteger() && 5960 "Cannot *_EXTEND_INREG FP types"); 5961 assert(EVT.isVector() == VT.isVector() && 5962 "SIGN_EXTEND_INREG type should be vector iff the operand " 5963 "type is vector!"); 5964 assert((!EVT.isVector() || 5965 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5966 "Vector element counts must match in SIGN_EXTEND_INREG"); 5967 assert(EVT.bitsLE(VT) && "Not extending!"); 5968 if (EVT == VT) return N1; // Not actually extending 5969 5970 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5971 unsigned FromBits = EVT.getScalarSizeInBits(); 5972 Val <<= Val.getBitWidth() - FromBits; 5973 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5974 return getConstant(Val, DL, ConstantVT); 5975 }; 5976 5977 if (N1C) { 5978 const APInt &Val = N1C->getAPIntValue(); 5979 return SignExtendInReg(Val, VT); 5980 } 5981 5982 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5983 SmallVector<SDValue, 8> Ops; 5984 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5985 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5986 SDValue Op = N1.getOperand(i); 5987 if (Op.isUndef()) { 5988 Ops.push_back(getUNDEF(OpVT)); 5989 continue; 5990 } 5991 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5992 APInt Val = C->getAPIntValue(); 5993 Ops.push_back(SignExtendInReg(Val, OpVT)); 5994 } 5995 return getBuildVector(VT, DL, Ops); 5996 } 5997 break; 5998 } 5999 case ISD::FP_TO_SINT_SAT: 6000 case ISD::FP_TO_UINT_SAT: { 6001 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6002 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6003 assert(N1.getValueType().isVector() == VT.isVector() && 6004 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6005 "vector!"); 6006 assert((!VT.isVector() || VT.getVectorNumElements() == 6007 N1.getValueType().getVectorNumElements()) && 6008 "Vector element counts must match in FP_TO_*INT_SAT"); 6009 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6010 "Type to saturate to must be a scalar."); 6011 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6012 "Not extending!"); 6013 break; 6014 } 6015 case ISD::EXTRACT_VECTOR_ELT: 6016 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6017 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6018 element type of the vector."); 6019 6020 // Extract from an undefined value or using an undefined index is undefined. 6021 if (N1.isUndef() || N2.isUndef()) 6022 return getUNDEF(VT); 6023 6024 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6025 // vectors. For scalable vectors we will provide appropriate support for 6026 // dealing with arbitrary indices. 6027 if (N2C && N1.getValueType().isFixedLengthVector() && 6028 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6029 return getUNDEF(VT); 6030 6031 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6032 // expanding copies of large vectors from registers. This only works for 6033 // fixed length vectors, since we need to know the exact number of 6034 // elements. 6035 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6036 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6037 unsigned Factor = 6038 N1.getOperand(0).getValueType().getVectorNumElements(); 6039 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6040 N1.getOperand(N2C->getZExtValue() / Factor), 6041 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6042 } 6043 6044 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6045 // lowering is expanding large vector constants. 6046 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6047 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6048 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6049 N1.getValueType().isFixedLengthVector()) && 6050 "BUILD_VECTOR used for scalable vectors"); 6051 unsigned Index = 6052 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6053 SDValue Elt = N1.getOperand(Index); 6054 6055 if (VT != Elt.getValueType()) 6056 // If the vector element type is not legal, the BUILD_VECTOR operands 6057 // are promoted and implicitly truncated, and the result implicitly 6058 // extended. Make that explicit here. 6059 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6060 6061 return Elt; 6062 } 6063 6064 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6065 // operations are lowered to scalars. 6066 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6067 // If the indices are the same, return the inserted element else 6068 // if the indices are known different, extract the element from 6069 // the original vector. 6070 SDValue N1Op2 = N1.getOperand(2); 6071 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6072 6073 if (N1Op2C && N2C) { 6074 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6075 if (VT == N1.getOperand(1).getValueType()) 6076 return N1.getOperand(1); 6077 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6078 } 6079 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6080 } 6081 } 6082 6083 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6084 // when vector types are scalarized and v1iX is legal. 6085 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6086 // Here we are completely ignoring the extract element index (N2), 6087 // which is fine for fixed width vectors, since any index other than 0 6088 // is undefined anyway. However, this cannot be ignored for scalable 6089 // vectors - in theory we could support this, but we don't want to do this 6090 // without a profitability check. 6091 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6092 N1.getValueType().isFixedLengthVector() && 6093 N1.getValueType().getVectorNumElements() == 1) { 6094 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6095 N1.getOperand(1)); 6096 } 6097 break; 6098 case ISD::EXTRACT_ELEMENT: 6099 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6100 assert(!N1.getValueType().isVector() && !VT.isVector() && 6101 (N1.getValueType().isInteger() == VT.isInteger()) && 6102 N1.getValueType() != VT && 6103 "Wrong types for EXTRACT_ELEMENT!"); 6104 6105 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6106 // 64-bit integers into 32-bit parts. Instead of building the extract of 6107 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6108 if (N1.getOpcode() == ISD::BUILD_PAIR) 6109 return N1.getOperand(N2C->getZExtValue()); 6110 6111 // EXTRACT_ELEMENT of a constant int is also very common. 6112 if (N1C) { 6113 unsigned ElementSize = VT.getSizeInBits(); 6114 unsigned Shift = ElementSize * N2C->getZExtValue(); 6115 const APInt &Val = N1C->getAPIntValue(); 6116 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6117 } 6118 break; 6119 case ISD::EXTRACT_SUBVECTOR: { 6120 EVT N1VT = N1.getValueType(); 6121 assert(VT.isVector() && N1VT.isVector() && 6122 "Extract subvector VTs must be vectors!"); 6123 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6124 "Extract subvector VTs must have the same element type!"); 6125 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6126 "Cannot extract a scalable vector from a fixed length vector!"); 6127 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6128 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6129 "Extract subvector must be from larger vector to smaller vector!"); 6130 assert(N2C && "Extract subvector index must be a constant"); 6131 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6132 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6133 N1VT.getVectorMinNumElements()) && 6134 "Extract subvector overflow!"); 6135 assert(N2C->getAPIntValue().getBitWidth() == 6136 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6137 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6138 6139 // Trivial extraction. 6140 if (VT == N1VT) 6141 return N1; 6142 6143 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6144 if (N1.isUndef()) 6145 return getUNDEF(VT); 6146 6147 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6148 // the concat have the same type as the extract. 6149 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6150 VT == N1.getOperand(0).getValueType()) { 6151 unsigned Factor = VT.getVectorMinNumElements(); 6152 return N1.getOperand(N2C->getZExtValue() / Factor); 6153 } 6154 6155 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6156 // during shuffle legalization. 6157 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6158 VT == N1.getOperand(1).getValueType()) 6159 return N1.getOperand(1); 6160 break; 6161 } 6162 } 6163 6164 // Perform trivial constant folding. 6165 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6166 return SV; 6167 6168 // Canonicalize an UNDEF to the RHS, even over a constant. 6169 if (N1.isUndef()) { 6170 if (TLI->isCommutativeBinOp(Opcode)) { 6171 std::swap(N1, N2); 6172 } else { 6173 switch (Opcode) { 6174 case ISD::SIGN_EXTEND_INREG: 6175 case ISD::SUB: 6176 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6177 case ISD::UDIV: 6178 case ISD::SDIV: 6179 case ISD::UREM: 6180 case ISD::SREM: 6181 case ISD::SSUBSAT: 6182 case ISD::USUBSAT: 6183 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6184 } 6185 } 6186 } 6187 6188 // Fold a bunch of operators when the RHS is undef. 6189 if (N2.isUndef()) { 6190 switch (Opcode) { 6191 case ISD::XOR: 6192 if (N1.isUndef()) 6193 // Handle undef ^ undef -> 0 special case. This is a common 6194 // idiom (misuse). 6195 return getConstant(0, DL, VT); 6196 LLVM_FALLTHROUGH; 6197 case ISD::ADD: 6198 case ISD::SUB: 6199 case ISD::UDIV: 6200 case ISD::SDIV: 6201 case ISD::UREM: 6202 case ISD::SREM: 6203 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6204 case ISD::MUL: 6205 case ISD::AND: 6206 case ISD::SSUBSAT: 6207 case ISD::USUBSAT: 6208 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6209 case ISD::OR: 6210 case ISD::SADDSAT: 6211 case ISD::UADDSAT: 6212 return getAllOnesConstant(DL, VT); 6213 } 6214 } 6215 6216 // Memoize this node if possible. 6217 SDNode *N; 6218 SDVTList VTs = getVTList(VT); 6219 SDValue Ops[] = {N1, N2}; 6220 if (VT != MVT::Glue) { 6221 FoldingSetNodeID ID; 6222 AddNodeIDNode(ID, Opcode, VTs, Ops); 6223 void *IP = nullptr; 6224 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6225 E->intersectFlagsWith(Flags); 6226 return SDValue(E, 0); 6227 } 6228 6229 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6230 N->setFlags(Flags); 6231 createOperands(N, Ops); 6232 CSEMap.InsertNode(N, IP); 6233 } else { 6234 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6235 createOperands(N, Ops); 6236 } 6237 6238 InsertNode(N); 6239 SDValue V = SDValue(N, 0); 6240 NewSDValueDbgMsg(V, "Creating new node: ", this); 6241 return V; 6242 } 6243 6244 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6245 SDValue N1, SDValue N2, SDValue N3) { 6246 SDNodeFlags Flags; 6247 if (Inserter) 6248 Flags = Inserter->getFlags(); 6249 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6250 } 6251 6252 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6253 SDValue N1, SDValue N2, SDValue N3, 6254 const SDNodeFlags Flags) { 6255 assert(N1.getOpcode() != ISD::DELETED_NODE && 6256 N2.getOpcode() != ISD::DELETED_NODE && 6257 N3.getOpcode() != ISD::DELETED_NODE && 6258 "Operand is DELETED_NODE!"); 6259 // Perform various simplifications. 6260 switch (Opcode) { 6261 case ISD::FMA: { 6262 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6263 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6264 N3.getValueType() == VT && "FMA types must match!"); 6265 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6266 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6267 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6268 if (N1CFP && N2CFP && N3CFP) { 6269 APFloat V1 = N1CFP->getValueAPF(); 6270 const APFloat &V2 = N2CFP->getValueAPF(); 6271 const APFloat &V3 = N3CFP->getValueAPF(); 6272 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6273 return getConstantFP(V1, DL, VT); 6274 } 6275 break; 6276 } 6277 case ISD::BUILD_VECTOR: { 6278 // Attempt to simplify BUILD_VECTOR. 6279 SDValue Ops[] = {N1, N2, N3}; 6280 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6281 return V; 6282 break; 6283 } 6284 case ISD::CONCAT_VECTORS: { 6285 SDValue Ops[] = {N1, N2, N3}; 6286 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6287 return V; 6288 break; 6289 } 6290 case ISD::SETCC: { 6291 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6292 assert(N1.getValueType() == N2.getValueType() && 6293 "SETCC operands must have the same type!"); 6294 assert(VT.isVector() == N1.getValueType().isVector() && 6295 "SETCC type should be vector iff the operand type is vector!"); 6296 assert((!VT.isVector() || VT.getVectorElementCount() == 6297 N1.getValueType().getVectorElementCount()) && 6298 "SETCC vector element counts must match!"); 6299 // Use FoldSetCC to simplify SETCC's. 6300 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6301 return V; 6302 // Vector constant folding. 6303 SDValue Ops[] = {N1, N2, N3}; 6304 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6305 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6306 return V; 6307 } 6308 break; 6309 } 6310 case ISD::SELECT: 6311 case ISD::VSELECT: 6312 if (SDValue V = simplifySelect(N1, N2, N3)) 6313 return V; 6314 break; 6315 case ISD::VECTOR_SHUFFLE: 6316 llvm_unreachable("should use getVectorShuffle constructor!"); 6317 case ISD::VECTOR_SPLICE: { 6318 if (cast<ConstantSDNode>(N3)->isNullValue()) 6319 return N1; 6320 break; 6321 } 6322 case ISD::INSERT_VECTOR_ELT: { 6323 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6324 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6325 // for scalable vectors where we will generate appropriate code to 6326 // deal with out-of-bounds cases correctly. 6327 if (N3C && N1.getValueType().isFixedLengthVector() && 6328 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6329 return getUNDEF(VT); 6330 6331 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6332 if (N3.isUndef()) 6333 return getUNDEF(VT); 6334 6335 // If the inserted element is an UNDEF, just use the input vector. 6336 if (N2.isUndef()) 6337 return N1; 6338 6339 break; 6340 } 6341 case ISD::INSERT_SUBVECTOR: { 6342 // Inserting undef into undef is still undef. 6343 if (N1.isUndef() && N2.isUndef()) 6344 return getUNDEF(VT); 6345 6346 EVT N2VT = N2.getValueType(); 6347 assert(VT == N1.getValueType() && 6348 "Dest and insert subvector source types must match!"); 6349 assert(VT.isVector() && N2VT.isVector() && 6350 "Insert subvector VTs must be vectors!"); 6351 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6352 "Cannot insert a scalable vector into a fixed length vector!"); 6353 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6354 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6355 "Insert subvector must be from smaller vector to larger vector!"); 6356 assert(isa<ConstantSDNode>(N3) && 6357 "Insert subvector index must be constant"); 6358 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6359 (N2VT.getVectorMinNumElements() + 6360 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6361 VT.getVectorMinNumElements()) && 6362 "Insert subvector overflow!"); 6363 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6364 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6365 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6366 6367 // Trivial insertion. 6368 if (VT == N2VT) 6369 return N2; 6370 6371 // If this is an insert of an extracted vector into an undef vector, we 6372 // can just use the input to the extract. 6373 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6374 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6375 return N2.getOperand(0); 6376 break; 6377 } 6378 case ISD::BITCAST: 6379 // Fold bit_convert nodes from a type to themselves. 6380 if (N1.getValueType() == VT) 6381 return N1; 6382 break; 6383 } 6384 6385 // Memoize node if it doesn't produce a flag. 6386 SDNode *N; 6387 SDVTList VTs = getVTList(VT); 6388 SDValue Ops[] = {N1, N2, N3}; 6389 if (VT != MVT::Glue) { 6390 FoldingSetNodeID ID; 6391 AddNodeIDNode(ID, Opcode, VTs, Ops); 6392 void *IP = nullptr; 6393 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6394 E->intersectFlagsWith(Flags); 6395 return SDValue(E, 0); 6396 } 6397 6398 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6399 N->setFlags(Flags); 6400 createOperands(N, Ops); 6401 CSEMap.InsertNode(N, IP); 6402 } else { 6403 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6404 createOperands(N, Ops); 6405 } 6406 6407 InsertNode(N); 6408 SDValue V = SDValue(N, 0); 6409 NewSDValueDbgMsg(V, "Creating new node: ", this); 6410 return V; 6411 } 6412 6413 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6414 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6415 SDValue Ops[] = { N1, N2, N3, N4 }; 6416 return getNode(Opcode, DL, VT, Ops); 6417 } 6418 6419 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6420 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6421 SDValue N5) { 6422 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6423 return getNode(Opcode, DL, VT, Ops); 6424 } 6425 6426 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6427 /// the incoming stack arguments to be loaded from the stack. 6428 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6429 SmallVector<SDValue, 8> ArgChains; 6430 6431 // Include the original chain at the beginning of the list. When this is 6432 // used by target LowerCall hooks, this helps legalize find the 6433 // CALLSEQ_BEGIN node. 6434 ArgChains.push_back(Chain); 6435 6436 // Add a chain value for each stack argument. 6437 for (SDNode *U : getEntryNode().getNode()->uses()) 6438 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6439 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6440 if (FI->getIndex() < 0) 6441 ArgChains.push_back(SDValue(L, 1)); 6442 6443 // Build a tokenfactor for all the chains. 6444 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6445 } 6446 6447 /// getMemsetValue - Vectorized representation of the memset value 6448 /// operand. 6449 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6450 const SDLoc &dl) { 6451 assert(!Value.isUndef()); 6452 6453 unsigned NumBits = VT.getScalarSizeInBits(); 6454 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6455 assert(C->getAPIntValue().getBitWidth() == 8); 6456 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6457 if (VT.isInteger()) { 6458 bool IsOpaque = VT.getSizeInBits() > 64 || 6459 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6460 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6461 } 6462 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6463 VT); 6464 } 6465 6466 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6467 EVT IntVT = VT.getScalarType(); 6468 if (!IntVT.isInteger()) 6469 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6470 6471 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6472 if (NumBits > 8) { 6473 // Use a multiplication with 0x010101... to extend the input to the 6474 // required length. 6475 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6476 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6477 DAG.getConstant(Magic, dl, IntVT)); 6478 } 6479 6480 if (VT != Value.getValueType() && !VT.isInteger()) 6481 Value = DAG.getBitcast(VT.getScalarType(), Value); 6482 if (VT != Value.getValueType()) 6483 Value = DAG.getSplatBuildVector(VT, dl, Value); 6484 6485 return Value; 6486 } 6487 6488 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6489 /// used when a memcpy is turned into a memset when the source is a constant 6490 /// string ptr. 6491 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6492 const TargetLowering &TLI, 6493 const ConstantDataArraySlice &Slice) { 6494 // Handle vector with all elements zero. 6495 if (Slice.Array == nullptr) { 6496 if (VT.isInteger()) 6497 return DAG.getConstant(0, dl, VT); 6498 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6499 return DAG.getConstantFP(0.0, dl, VT); 6500 if (VT.isVector()) { 6501 unsigned NumElts = VT.getVectorNumElements(); 6502 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6503 return DAG.getNode(ISD::BITCAST, dl, VT, 6504 DAG.getConstant(0, dl, 6505 EVT::getVectorVT(*DAG.getContext(), 6506 EltVT, NumElts))); 6507 } 6508 llvm_unreachable("Expected type!"); 6509 } 6510 6511 assert(!VT.isVector() && "Can't handle vector type here!"); 6512 unsigned NumVTBits = VT.getSizeInBits(); 6513 unsigned NumVTBytes = NumVTBits / 8; 6514 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6515 6516 APInt Val(NumVTBits, 0); 6517 if (DAG.getDataLayout().isLittleEndian()) { 6518 for (unsigned i = 0; i != NumBytes; ++i) 6519 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6520 } else { 6521 for (unsigned i = 0; i != NumBytes; ++i) 6522 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6523 } 6524 6525 // If the "cost" of materializing the integer immediate is less than the cost 6526 // of a load, then it is cost effective to turn the load into the immediate. 6527 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6528 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6529 return DAG.getConstant(Val, dl, VT); 6530 return SDValue(); 6531 } 6532 6533 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6534 const SDLoc &DL, 6535 const SDNodeFlags Flags) { 6536 EVT VT = Base.getValueType(); 6537 SDValue Index; 6538 6539 if (Offset.isScalable()) 6540 Index = getVScale(DL, Base.getValueType(), 6541 APInt(Base.getValueSizeInBits().getFixedSize(), 6542 Offset.getKnownMinSize())); 6543 else 6544 Index = getConstant(Offset.getFixedSize(), DL, VT); 6545 6546 return getMemBasePlusOffset(Base, Index, DL, Flags); 6547 } 6548 6549 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6550 const SDLoc &DL, 6551 const SDNodeFlags Flags) { 6552 assert(Offset.getValueType().isInteger()); 6553 EVT BasePtrVT = Ptr.getValueType(); 6554 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6555 } 6556 6557 /// Returns true if memcpy source is constant data. 6558 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6559 uint64_t SrcDelta = 0; 6560 GlobalAddressSDNode *G = nullptr; 6561 if (Src.getOpcode() == ISD::GlobalAddress) 6562 G = cast<GlobalAddressSDNode>(Src); 6563 else if (Src.getOpcode() == ISD::ADD && 6564 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6565 Src.getOperand(1).getOpcode() == ISD::Constant) { 6566 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6567 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6568 } 6569 if (!G) 6570 return false; 6571 6572 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6573 SrcDelta + G->getOffset()); 6574 } 6575 6576 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6577 SelectionDAG &DAG) { 6578 // On Darwin, -Os means optimize for size without hurting performance, so 6579 // only really optimize for size when -Oz (MinSize) is used. 6580 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6581 return MF.getFunction().hasMinSize(); 6582 return DAG.shouldOptForSize(); 6583 } 6584 6585 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6586 SmallVector<SDValue, 32> &OutChains, unsigned From, 6587 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6588 SmallVector<SDValue, 16> &OutStoreChains) { 6589 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6590 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6591 SmallVector<SDValue, 16> GluedLoadChains; 6592 for (unsigned i = From; i < To; ++i) { 6593 OutChains.push_back(OutLoadChains[i]); 6594 GluedLoadChains.push_back(OutLoadChains[i]); 6595 } 6596 6597 // Chain for all loads. 6598 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6599 GluedLoadChains); 6600 6601 for (unsigned i = From; i < To; ++i) { 6602 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6603 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6604 ST->getBasePtr(), ST->getMemoryVT(), 6605 ST->getMemOperand()); 6606 OutChains.push_back(NewStore); 6607 } 6608 } 6609 6610 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6611 SDValue Chain, SDValue Dst, SDValue Src, 6612 uint64_t Size, Align Alignment, 6613 bool isVol, bool AlwaysInline, 6614 MachinePointerInfo DstPtrInfo, 6615 MachinePointerInfo SrcPtrInfo, 6616 const AAMDNodes &AAInfo) { 6617 // Turn a memcpy of undef to nop. 6618 // FIXME: We need to honor volatile even is Src is undef. 6619 if (Src.isUndef()) 6620 return Chain; 6621 6622 // Expand memcpy to a series of load and store ops if the size operand falls 6623 // below a certain threshold. 6624 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6625 // rather than maybe a humongous number of loads and stores. 6626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6627 const DataLayout &DL = DAG.getDataLayout(); 6628 LLVMContext &C = *DAG.getContext(); 6629 std::vector<EVT> MemOps; 6630 bool DstAlignCanChange = false; 6631 MachineFunction &MF = DAG.getMachineFunction(); 6632 MachineFrameInfo &MFI = MF.getFrameInfo(); 6633 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6634 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6635 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6636 DstAlignCanChange = true; 6637 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6638 if (!SrcAlign || Alignment > *SrcAlign) 6639 SrcAlign = Alignment; 6640 assert(SrcAlign && "SrcAlign must be set"); 6641 ConstantDataArraySlice Slice; 6642 // If marked as volatile, perform a copy even when marked as constant. 6643 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6644 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6645 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6646 const MemOp Op = isZeroConstant 6647 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6648 /*IsZeroMemset*/ true, isVol) 6649 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6650 *SrcAlign, isVol, CopyFromConstant); 6651 if (!TLI.findOptimalMemOpLowering( 6652 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6653 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6654 return SDValue(); 6655 6656 if (DstAlignCanChange) { 6657 Type *Ty = MemOps[0].getTypeForEVT(C); 6658 Align NewAlign = DL.getABITypeAlign(Ty); 6659 6660 // Don't promote to an alignment that would require dynamic stack 6661 // realignment. 6662 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6663 if (!TRI->hasStackRealignment(MF)) 6664 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6665 NewAlign = NewAlign / 2; 6666 6667 if (NewAlign > Alignment) { 6668 // Give the stack frame object a larger alignment if needed. 6669 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6670 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6671 Alignment = NewAlign; 6672 } 6673 } 6674 6675 // Prepare AAInfo for loads/stores after lowering this memcpy. 6676 AAMDNodes NewAAInfo = AAInfo; 6677 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6678 6679 MachineMemOperand::Flags MMOFlags = 6680 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6681 SmallVector<SDValue, 16> OutLoadChains; 6682 SmallVector<SDValue, 16> OutStoreChains; 6683 SmallVector<SDValue, 32> OutChains; 6684 unsigned NumMemOps = MemOps.size(); 6685 uint64_t SrcOff = 0, DstOff = 0; 6686 for (unsigned i = 0; i != NumMemOps; ++i) { 6687 EVT VT = MemOps[i]; 6688 unsigned VTSize = VT.getSizeInBits() / 8; 6689 SDValue Value, Store; 6690 6691 if (VTSize > Size) { 6692 // Issuing an unaligned load / store pair that overlaps with the previous 6693 // pair. Adjust the offset accordingly. 6694 assert(i == NumMemOps-1 && i != 0); 6695 SrcOff -= VTSize - Size; 6696 DstOff -= VTSize - Size; 6697 } 6698 6699 if (CopyFromConstant && 6700 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6701 // It's unlikely a store of a vector immediate can be done in a single 6702 // instruction. It would require a load from a constantpool first. 6703 // We only handle zero vectors here. 6704 // FIXME: Handle other cases where store of vector immediate is done in 6705 // a single instruction. 6706 ConstantDataArraySlice SubSlice; 6707 if (SrcOff < Slice.Length) { 6708 SubSlice = Slice; 6709 SubSlice.move(SrcOff); 6710 } else { 6711 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6712 SubSlice.Array = nullptr; 6713 SubSlice.Offset = 0; 6714 SubSlice.Length = VTSize; 6715 } 6716 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6717 if (Value.getNode()) { 6718 Store = DAG.getStore( 6719 Chain, dl, Value, 6720 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6721 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6722 OutChains.push_back(Store); 6723 } 6724 } 6725 6726 if (!Store.getNode()) { 6727 // The type might not be legal for the target. This should only happen 6728 // if the type is smaller than a legal type, as on PPC, so the right 6729 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6730 // to Load/Store if NVT==VT. 6731 // FIXME does the case above also need this? 6732 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6733 assert(NVT.bitsGE(VT)); 6734 6735 bool isDereferenceable = 6736 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6737 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6738 if (isDereferenceable) 6739 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6740 6741 Value = DAG.getExtLoad( 6742 ISD::EXTLOAD, dl, NVT, Chain, 6743 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6744 SrcPtrInfo.getWithOffset(SrcOff), VT, 6745 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6746 OutLoadChains.push_back(Value.getValue(1)); 6747 6748 Store = DAG.getTruncStore( 6749 Chain, dl, Value, 6750 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6751 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6752 OutStoreChains.push_back(Store); 6753 } 6754 SrcOff += VTSize; 6755 DstOff += VTSize; 6756 Size -= VTSize; 6757 } 6758 6759 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6760 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6761 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6762 6763 if (NumLdStInMemcpy) { 6764 // It may be that memcpy might be converted to memset if it's memcpy 6765 // of constants. In such a case, we won't have loads and stores, but 6766 // just stores. In the absence of loads, there is nothing to gang up. 6767 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6768 // If target does not care, just leave as it. 6769 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6770 OutChains.push_back(OutLoadChains[i]); 6771 OutChains.push_back(OutStoreChains[i]); 6772 } 6773 } else { 6774 // Ld/St less than/equal limit set by target. 6775 if (NumLdStInMemcpy <= GluedLdStLimit) { 6776 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6777 NumLdStInMemcpy, OutLoadChains, 6778 OutStoreChains); 6779 } else { 6780 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6781 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6782 unsigned GlueIter = 0; 6783 6784 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6785 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6786 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6787 6788 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6789 OutLoadChains, OutStoreChains); 6790 GlueIter += GluedLdStLimit; 6791 } 6792 6793 // Residual ld/st. 6794 if (RemainingLdStInMemcpy) { 6795 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6796 RemainingLdStInMemcpy, OutLoadChains, 6797 OutStoreChains); 6798 } 6799 } 6800 } 6801 } 6802 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6803 } 6804 6805 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6806 SDValue Chain, SDValue Dst, SDValue Src, 6807 uint64_t Size, Align Alignment, 6808 bool isVol, bool AlwaysInline, 6809 MachinePointerInfo DstPtrInfo, 6810 MachinePointerInfo SrcPtrInfo, 6811 const AAMDNodes &AAInfo) { 6812 // Turn a memmove of undef to nop. 6813 // FIXME: We need to honor volatile even is Src is undef. 6814 if (Src.isUndef()) 6815 return Chain; 6816 6817 // Expand memmove to a series of load and store ops if the size operand falls 6818 // below a certain threshold. 6819 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6820 const DataLayout &DL = DAG.getDataLayout(); 6821 LLVMContext &C = *DAG.getContext(); 6822 std::vector<EVT> MemOps; 6823 bool DstAlignCanChange = false; 6824 MachineFunction &MF = DAG.getMachineFunction(); 6825 MachineFrameInfo &MFI = MF.getFrameInfo(); 6826 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6827 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6828 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6829 DstAlignCanChange = true; 6830 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6831 if (!SrcAlign || Alignment > *SrcAlign) 6832 SrcAlign = Alignment; 6833 assert(SrcAlign && "SrcAlign must be set"); 6834 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6835 if (!TLI.findOptimalMemOpLowering( 6836 MemOps, Limit, 6837 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6838 /*IsVolatile*/ true), 6839 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6840 MF.getFunction().getAttributes())) 6841 return SDValue(); 6842 6843 if (DstAlignCanChange) { 6844 Type *Ty = MemOps[0].getTypeForEVT(C); 6845 Align NewAlign = DL.getABITypeAlign(Ty); 6846 if (NewAlign > Alignment) { 6847 // Give the stack frame object a larger alignment if needed. 6848 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6849 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6850 Alignment = NewAlign; 6851 } 6852 } 6853 6854 // Prepare AAInfo for loads/stores after lowering this memmove. 6855 AAMDNodes NewAAInfo = AAInfo; 6856 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6857 6858 MachineMemOperand::Flags MMOFlags = 6859 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6860 uint64_t SrcOff = 0, DstOff = 0; 6861 SmallVector<SDValue, 8> LoadValues; 6862 SmallVector<SDValue, 8> LoadChains; 6863 SmallVector<SDValue, 8> OutChains; 6864 unsigned NumMemOps = MemOps.size(); 6865 for (unsigned i = 0; i < NumMemOps; i++) { 6866 EVT VT = MemOps[i]; 6867 unsigned VTSize = VT.getSizeInBits() / 8; 6868 SDValue Value; 6869 6870 bool isDereferenceable = 6871 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6872 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6873 if (isDereferenceable) 6874 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6875 6876 Value = DAG.getLoad( 6877 VT, dl, Chain, 6878 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6879 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6880 LoadValues.push_back(Value); 6881 LoadChains.push_back(Value.getValue(1)); 6882 SrcOff += VTSize; 6883 } 6884 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6885 OutChains.clear(); 6886 for (unsigned i = 0; i < NumMemOps; i++) { 6887 EVT VT = MemOps[i]; 6888 unsigned VTSize = VT.getSizeInBits() / 8; 6889 SDValue Store; 6890 6891 Store = DAG.getStore( 6892 Chain, dl, LoadValues[i], 6893 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6894 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6895 OutChains.push_back(Store); 6896 DstOff += VTSize; 6897 } 6898 6899 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6900 } 6901 6902 /// Lower the call to 'memset' intrinsic function into a series of store 6903 /// operations. 6904 /// 6905 /// \param DAG Selection DAG where lowered code is placed. 6906 /// \param dl Link to corresponding IR location. 6907 /// \param Chain Control flow dependency. 6908 /// \param Dst Pointer to destination memory location. 6909 /// \param Src Value of byte to write into the memory. 6910 /// \param Size Number of bytes to write. 6911 /// \param Alignment Alignment of the destination in bytes. 6912 /// \param isVol True if destination is volatile. 6913 /// \param DstPtrInfo IR information on the memory pointer. 6914 /// \returns New head in the control flow, if lowering was successful, empty 6915 /// SDValue otherwise. 6916 /// 6917 /// The function tries to replace 'llvm.memset' intrinsic with several store 6918 /// operations and value calculation code. This is usually profitable for small 6919 /// memory size. 6920 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6921 SDValue Chain, SDValue Dst, SDValue Src, 6922 uint64_t Size, Align Alignment, bool isVol, 6923 MachinePointerInfo DstPtrInfo, 6924 const AAMDNodes &AAInfo) { 6925 // Turn a memset of undef to nop. 6926 // FIXME: We need to honor volatile even is Src is undef. 6927 if (Src.isUndef()) 6928 return Chain; 6929 6930 // Expand memset to a series of load/store ops if the size operand 6931 // falls below a certain threshold. 6932 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6933 std::vector<EVT> MemOps; 6934 bool DstAlignCanChange = false; 6935 MachineFunction &MF = DAG.getMachineFunction(); 6936 MachineFrameInfo &MFI = MF.getFrameInfo(); 6937 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6938 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6939 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6940 DstAlignCanChange = true; 6941 bool IsZeroVal = 6942 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6943 if (!TLI.findOptimalMemOpLowering( 6944 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6945 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6946 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6947 return SDValue(); 6948 6949 if (DstAlignCanChange) { 6950 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6951 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6952 if (NewAlign > Alignment) { 6953 // Give the stack frame object a larger alignment if needed. 6954 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6955 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6956 Alignment = NewAlign; 6957 } 6958 } 6959 6960 SmallVector<SDValue, 8> OutChains; 6961 uint64_t DstOff = 0; 6962 unsigned NumMemOps = MemOps.size(); 6963 6964 // Find the largest store and generate the bit pattern for it. 6965 EVT LargestVT = MemOps[0]; 6966 for (unsigned i = 1; i < NumMemOps; i++) 6967 if (MemOps[i].bitsGT(LargestVT)) 6968 LargestVT = MemOps[i]; 6969 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6970 6971 // Prepare AAInfo for loads/stores after lowering this memset. 6972 AAMDNodes NewAAInfo = AAInfo; 6973 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6974 6975 for (unsigned i = 0; i < NumMemOps; i++) { 6976 EVT VT = MemOps[i]; 6977 unsigned VTSize = VT.getSizeInBits() / 8; 6978 if (VTSize > Size) { 6979 // Issuing an unaligned load / store pair that overlaps with the previous 6980 // pair. Adjust the offset accordingly. 6981 assert(i == NumMemOps-1 && i != 0); 6982 DstOff -= VTSize - Size; 6983 } 6984 6985 // If this store is smaller than the largest store see whether we can get 6986 // the smaller value for free with a truncate. 6987 SDValue Value = MemSetValue; 6988 if (VT.bitsLT(LargestVT)) { 6989 if (!LargestVT.isVector() && !VT.isVector() && 6990 TLI.isTruncateFree(LargestVT, VT)) 6991 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6992 else 6993 Value = getMemsetValue(Src, VT, DAG, dl); 6994 } 6995 assert(Value.getValueType() == VT && "Value with wrong type."); 6996 SDValue Store = DAG.getStore( 6997 Chain, dl, Value, 6998 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6999 DstPtrInfo.getWithOffset(DstOff), Alignment, 7000 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7001 NewAAInfo); 7002 OutChains.push_back(Store); 7003 DstOff += VT.getSizeInBits() / 8; 7004 Size -= VTSize; 7005 } 7006 7007 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7008 } 7009 7010 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7011 unsigned AS) { 7012 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7013 // pointer operands can be losslessly bitcasted to pointers of address space 0 7014 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7015 report_fatal_error("cannot lower memory intrinsic in address space " + 7016 Twine(AS)); 7017 } 7018 } 7019 7020 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7021 SDValue Src, SDValue Size, Align Alignment, 7022 bool isVol, bool AlwaysInline, bool isTailCall, 7023 MachinePointerInfo DstPtrInfo, 7024 MachinePointerInfo SrcPtrInfo, 7025 const AAMDNodes &AAInfo) { 7026 // Check to see if we should lower the memcpy to loads and stores first. 7027 // For cases within the target-specified limits, this is the best choice. 7028 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7029 if (ConstantSize) { 7030 // Memcpy with size zero? Just return the original chain. 7031 if (ConstantSize->isZero()) 7032 return Chain; 7033 7034 SDValue Result = getMemcpyLoadsAndStores( 7035 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7036 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7037 if (Result.getNode()) 7038 return Result; 7039 } 7040 7041 // Then check to see if we should lower the memcpy with target-specific 7042 // code. If the target chooses to do this, this is the next best. 7043 if (TSI) { 7044 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7045 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7046 DstPtrInfo, SrcPtrInfo); 7047 if (Result.getNode()) 7048 return Result; 7049 } 7050 7051 // If we really need inline code and the target declined to provide it, 7052 // use a (potentially long) sequence of loads and stores. 7053 if (AlwaysInline) { 7054 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7055 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 7056 ConstantSize->getZExtValue(), Alignment, 7057 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 7058 } 7059 7060 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7061 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7062 7063 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7064 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7065 // respect volatile, so they may do things like read or write memory 7066 // beyond the given memory regions. But fixing this isn't easy, and most 7067 // people don't care. 7068 7069 // Emit a library call. 7070 TargetLowering::ArgListTy Args; 7071 TargetLowering::ArgListEntry Entry; 7072 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7073 Entry.Node = Dst; Args.push_back(Entry); 7074 Entry.Node = Src; Args.push_back(Entry); 7075 7076 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7077 Entry.Node = Size; Args.push_back(Entry); 7078 // FIXME: pass in SDLoc 7079 TargetLowering::CallLoweringInfo CLI(*this); 7080 CLI.setDebugLoc(dl) 7081 .setChain(Chain) 7082 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7083 Dst.getValueType().getTypeForEVT(*getContext()), 7084 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7085 TLI->getPointerTy(getDataLayout())), 7086 std::move(Args)) 7087 .setDiscardResult() 7088 .setTailCall(isTailCall); 7089 7090 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7091 return CallResult.second; 7092 } 7093 7094 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7095 SDValue Dst, unsigned DstAlign, 7096 SDValue Src, unsigned SrcAlign, 7097 SDValue Size, Type *SizeTy, 7098 unsigned ElemSz, bool isTailCall, 7099 MachinePointerInfo DstPtrInfo, 7100 MachinePointerInfo SrcPtrInfo) { 7101 // Emit a library call. 7102 TargetLowering::ArgListTy Args; 7103 TargetLowering::ArgListEntry Entry; 7104 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7105 Entry.Node = Dst; 7106 Args.push_back(Entry); 7107 7108 Entry.Node = Src; 7109 Args.push_back(Entry); 7110 7111 Entry.Ty = SizeTy; 7112 Entry.Node = Size; 7113 Args.push_back(Entry); 7114 7115 RTLIB::Libcall LibraryCall = 7116 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7117 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7118 report_fatal_error("Unsupported element size"); 7119 7120 TargetLowering::CallLoweringInfo CLI(*this); 7121 CLI.setDebugLoc(dl) 7122 .setChain(Chain) 7123 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7124 Type::getVoidTy(*getContext()), 7125 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7126 TLI->getPointerTy(getDataLayout())), 7127 std::move(Args)) 7128 .setDiscardResult() 7129 .setTailCall(isTailCall); 7130 7131 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7132 return CallResult.second; 7133 } 7134 7135 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7136 SDValue Src, SDValue Size, Align Alignment, 7137 bool isVol, bool isTailCall, 7138 MachinePointerInfo DstPtrInfo, 7139 MachinePointerInfo SrcPtrInfo, 7140 const AAMDNodes &AAInfo) { 7141 // Check to see if we should lower the memmove to loads and stores first. 7142 // For cases within the target-specified limits, this is the best choice. 7143 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7144 if (ConstantSize) { 7145 // Memmove with size zero? Just return the original chain. 7146 if (ConstantSize->isZero()) 7147 return Chain; 7148 7149 SDValue Result = getMemmoveLoadsAndStores( 7150 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7151 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7152 if (Result.getNode()) 7153 return Result; 7154 } 7155 7156 // Then check to see if we should lower the memmove with target-specific 7157 // code. If the target chooses to do this, this is the next best. 7158 if (TSI) { 7159 SDValue Result = 7160 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7161 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7162 if (Result.getNode()) 7163 return Result; 7164 } 7165 7166 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7167 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7168 7169 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7170 // not be safe. See memcpy above for more details. 7171 7172 // Emit a library call. 7173 TargetLowering::ArgListTy Args; 7174 TargetLowering::ArgListEntry Entry; 7175 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7176 Entry.Node = Dst; Args.push_back(Entry); 7177 Entry.Node = Src; Args.push_back(Entry); 7178 7179 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7180 Entry.Node = Size; Args.push_back(Entry); 7181 // FIXME: pass in SDLoc 7182 TargetLowering::CallLoweringInfo CLI(*this); 7183 CLI.setDebugLoc(dl) 7184 .setChain(Chain) 7185 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7186 Dst.getValueType().getTypeForEVT(*getContext()), 7187 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7188 TLI->getPointerTy(getDataLayout())), 7189 std::move(Args)) 7190 .setDiscardResult() 7191 .setTailCall(isTailCall); 7192 7193 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7194 return CallResult.second; 7195 } 7196 7197 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7198 SDValue Dst, unsigned DstAlign, 7199 SDValue Src, unsigned SrcAlign, 7200 SDValue Size, Type *SizeTy, 7201 unsigned ElemSz, bool isTailCall, 7202 MachinePointerInfo DstPtrInfo, 7203 MachinePointerInfo SrcPtrInfo) { 7204 // Emit a library call. 7205 TargetLowering::ArgListTy Args; 7206 TargetLowering::ArgListEntry Entry; 7207 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7208 Entry.Node = Dst; 7209 Args.push_back(Entry); 7210 7211 Entry.Node = Src; 7212 Args.push_back(Entry); 7213 7214 Entry.Ty = SizeTy; 7215 Entry.Node = Size; 7216 Args.push_back(Entry); 7217 7218 RTLIB::Libcall LibraryCall = 7219 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7220 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7221 report_fatal_error("Unsupported element size"); 7222 7223 TargetLowering::CallLoweringInfo CLI(*this); 7224 CLI.setDebugLoc(dl) 7225 .setChain(Chain) 7226 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7227 Type::getVoidTy(*getContext()), 7228 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7229 TLI->getPointerTy(getDataLayout())), 7230 std::move(Args)) 7231 .setDiscardResult() 7232 .setTailCall(isTailCall); 7233 7234 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7235 return CallResult.second; 7236 } 7237 7238 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7239 SDValue Src, SDValue Size, Align Alignment, 7240 bool isVol, bool isTailCall, 7241 MachinePointerInfo DstPtrInfo, 7242 const AAMDNodes &AAInfo) { 7243 // Check to see if we should lower the memset to stores first. 7244 // For cases within the target-specified limits, this is the best choice. 7245 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7246 if (ConstantSize) { 7247 // Memset with size zero? Just return the original chain. 7248 if (ConstantSize->isZero()) 7249 return Chain; 7250 7251 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7252 ConstantSize->getZExtValue(), Alignment, 7253 isVol, DstPtrInfo, AAInfo); 7254 7255 if (Result.getNode()) 7256 return Result; 7257 } 7258 7259 // Then check to see if we should lower the memset with target-specific 7260 // code. If the target chooses to do this, this is the next best. 7261 if (TSI) { 7262 SDValue Result = TSI->EmitTargetCodeForMemset( 7263 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7264 if (Result.getNode()) 7265 return Result; 7266 } 7267 7268 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7269 7270 // Emit a library call. 7271 TargetLowering::ArgListTy Args; 7272 TargetLowering::ArgListEntry Entry; 7273 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7274 Args.push_back(Entry); 7275 Entry.Node = Src; 7276 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7277 Args.push_back(Entry); 7278 Entry.Node = Size; 7279 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7280 Args.push_back(Entry); 7281 7282 // FIXME: pass in SDLoc 7283 TargetLowering::CallLoweringInfo CLI(*this); 7284 CLI.setDebugLoc(dl) 7285 .setChain(Chain) 7286 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7287 Dst.getValueType().getTypeForEVT(*getContext()), 7288 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7289 TLI->getPointerTy(getDataLayout())), 7290 std::move(Args)) 7291 .setDiscardResult() 7292 .setTailCall(isTailCall); 7293 7294 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7295 return CallResult.second; 7296 } 7297 7298 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7299 SDValue Dst, unsigned DstAlign, 7300 SDValue Value, SDValue Size, Type *SizeTy, 7301 unsigned ElemSz, bool isTailCall, 7302 MachinePointerInfo DstPtrInfo) { 7303 // Emit a library call. 7304 TargetLowering::ArgListTy Args; 7305 TargetLowering::ArgListEntry Entry; 7306 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7307 Entry.Node = Dst; 7308 Args.push_back(Entry); 7309 7310 Entry.Ty = Type::getInt8Ty(*getContext()); 7311 Entry.Node = Value; 7312 Args.push_back(Entry); 7313 7314 Entry.Ty = SizeTy; 7315 Entry.Node = Size; 7316 Args.push_back(Entry); 7317 7318 RTLIB::Libcall LibraryCall = 7319 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7320 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7321 report_fatal_error("Unsupported element size"); 7322 7323 TargetLowering::CallLoweringInfo CLI(*this); 7324 CLI.setDebugLoc(dl) 7325 .setChain(Chain) 7326 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7327 Type::getVoidTy(*getContext()), 7328 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7329 TLI->getPointerTy(getDataLayout())), 7330 std::move(Args)) 7331 .setDiscardResult() 7332 .setTailCall(isTailCall); 7333 7334 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7335 return CallResult.second; 7336 } 7337 7338 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7339 SDVTList VTList, ArrayRef<SDValue> Ops, 7340 MachineMemOperand *MMO) { 7341 FoldingSetNodeID ID; 7342 ID.AddInteger(MemVT.getRawBits()); 7343 AddNodeIDNode(ID, Opcode, VTList, Ops); 7344 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7345 ID.AddInteger(MMO->getFlags()); 7346 void* IP = nullptr; 7347 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7348 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7349 return SDValue(E, 0); 7350 } 7351 7352 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7353 VTList, MemVT, MMO); 7354 createOperands(N, Ops); 7355 7356 CSEMap.InsertNode(N, IP); 7357 InsertNode(N); 7358 return SDValue(N, 0); 7359 } 7360 7361 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7362 EVT MemVT, SDVTList VTs, SDValue Chain, 7363 SDValue Ptr, SDValue Cmp, SDValue Swp, 7364 MachineMemOperand *MMO) { 7365 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7366 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7367 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7368 7369 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7370 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7371 } 7372 7373 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7374 SDValue Chain, SDValue Ptr, SDValue Val, 7375 MachineMemOperand *MMO) { 7376 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7377 Opcode == ISD::ATOMIC_LOAD_SUB || 7378 Opcode == ISD::ATOMIC_LOAD_AND || 7379 Opcode == ISD::ATOMIC_LOAD_CLR || 7380 Opcode == ISD::ATOMIC_LOAD_OR || 7381 Opcode == ISD::ATOMIC_LOAD_XOR || 7382 Opcode == ISD::ATOMIC_LOAD_NAND || 7383 Opcode == ISD::ATOMIC_LOAD_MIN || 7384 Opcode == ISD::ATOMIC_LOAD_MAX || 7385 Opcode == ISD::ATOMIC_LOAD_UMIN || 7386 Opcode == ISD::ATOMIC_LOAD_UMAX || 7387 Opcode == ISD::ATOMIC_LOAD_FADD || 7388 Opcode == ISD::ATOMIC_LOAD_FSUB || 7389 Opcode == ISD::ATOMIC_SWAP || 7390 Opcode == ISD::ATOMIC_STORE) && 7391 "Invalid Atomic Op"); 7392 7393 EVT VT = Val.getValueType(); 7394 7395 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7396 getVTList(VT, MVT::Other); 7397 SDValue Ops[] = {Chain, Ptr, Val}; 7398 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7399 } 7400 7401 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7402 EVT VT, SDValue Chain, SDValue Ptr, 7403 MachineMemOperand *MMO) { 7404 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7405 7406 SDVTList VTs = getVTList(VT, MVT::Other); 7407 SDValue Ops[] = {Chain, Ptr}; 7408 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7409 } 7410 7411 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7412 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7413 if (Ops.size() == 1) 7414 return Ops[0]; 7415 7416 SmallVector<EVT, 4> VTs; 7417 VTs.reserve(Ops.size()); 7418 for (const SDValue &Op : Ops) 7419 VTs.push_back(Op.getValueType()); 7420 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7421 } 7422 7423 SDValue SelectionDAG::getMemIntrinsicNode( 7424 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7425 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7426 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7427 if (!Size && MemVT.isScalableVector()) 7428 Size = MemoryLocation::UnknownSize; 7429 else if (!Size) 7430 Size = MemVT.getStoreSize(); 7431 7432 MachineFunction &MF = getMachineFunction(); 7433 MachineMemOperand *MMO = 7434 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7435 7436 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7437 } 7438 7439 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7440 SDVTList VTList, 7441 ArrayRef<SDValue> Ops, EVT MemVT, 7442 MachineMemOperand *MMO) { 7443 assert((Opcode == ISD::INTRINSIC_VOID || 7444 Opcode == ISD::INTRINSIC_W_CHAIN || 7445 Opcode == ISD::PREFETCH || 7446 ((int)Opcode <= std::numeric_limits<int>::max() && 7447 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7448 "Opcode is not a memory-accessing opcode!"); 7449 7450 // Memoize the node unless it returns a flag. 7451 MemIntrinsicSDNode *N; 7452 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7453 FoldingSetNodeID ID; 7454 AddNodeIDNode(ID, Opcode, VTList, Ops); 7455 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7456 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7457 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7458 ID.AddInteger(MMO->getFlags()); 7459 void *IP = nullptr; 7460 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7461 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7462 return SDValue(E, 0); 7463 } 7464 7465 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7466 VTList, MemVT, MMO); 7467 createOperands(N, Ops); 7468 7469 CSEMap.InsertNode(N, IP); 7470 } else { 7471 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7472 VTList, MemVT, MMO); 7473 createOperands(N, Ops); 7474 } 7475 InsertNode(N); 7476 SDValue V(N, 0); 7477 NewSDValueDbgMsg(V, "Creating new node: ", this); 7478 return V; 7479 } 7480 7481 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7482 SDValue Chain, int FrameIndex, 7483 int64_t Size, int64_t Offset) { 7484 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7485 const auto VTs = getVTList(MVT::Other); 7486 SDValue Ops[2] = { 7487 Chain, 7488 getFrameIndex(FrameIndex, 7489 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7490 true)}; 7491 7492 FoldingSetNodeID ID; 7493 AddNodeIDNode(ID, Opcode, VTs, Ops); 7494 ID.AddInteger(FrameIndex); 7495 ID.AddInteger(Size); 7496 ID.AddInteger(Offset); 7497 void *IP = nullptr; 7498 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7499 return SDValue(E, 0); 7500 7501 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7502 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7503 createOperands(N, Ops); 7504 CSEMap.InsertNode(N, IP); 7505 InsertNode(N); 7506 SDValue V(N, 0); 7507 NewSDValueDbgMsg(V, "Creating new node: ", this); 7508 return V; 7509 } 7510 7511 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7512 uint64_t Guid, uint64_t Index, 7513 uint32_t Attr) { 7514 const unsigned Opcode = ISD::PSEUDO_PROBE; 7515 const auto VTs = getVTList(MVT::Other); 7516 SDValue Ops[] = {Chain}; 7517 FoldingSetNodeID ID; 7518 AddNodeIDNode(ID, Opcode, VTs, Ops); 7519 ID.AddInteger(Guid); 7520 ID.AddInteger(Index); 7521 void *IP = nullptr; 7522 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7523 return SDValue(E, 0); 7524 7525 auto *N = newSDNode<PseudoProbeSDNode>( 7526 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7527 createOperands(N, Ops); 7528 CSEMap.InsertNode(N, IP); 7529 InsertNode(N); 7530 SDValue V(N, 0); 7531 NewSDValueDbgMsg(V, "Creating new node: ", this); 7532 return V; 7533 } 7534 7535 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7536 /// MachinePointerInfo record from it. This is particularly useful because the 7537 /// code generator has many cases where it doesn't bother passing in a 7538 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7539 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7540 SelectionDAG &DAG, SDValue Ptr, 7541 int64_t Offset = 0) { 7542 // If this is FI+Offset, we can model it. 7543 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7544 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7545 FI->getIndex(), Offset); 7546 7547 // If this is (FI+Offset1)+Offset2, we can model it. 7548 if (Ptr.getOpcode() != ISD::ADD || 7549 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7550 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7551 return Info; 7552 7553 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7554 return MachinePointerInfo::getFixedStack( 7555 DAG.getMachineFunction(), FI, 7556 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7557 } 7558 7559 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7560 /// MachinePointerInfo record from it. This is particularly useful because the 7561 /// code generator has many cases where it doesn't bother passing in a 7562 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7563 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7564 SelectionDAG &DAG, SDValue Ptr, 7565 SDValue OffsetOp) { 7566 // If the 'Offset' value isn't a constant, we can't handle this. 7567 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7568 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7569 if (OffsetOp.isUndef()) 7570 return InferPointerInfo(Info, DAG, Ptr); 7571 return Info; 7572 } 7573 7574 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7575 EVT VT, const SDLoc &dl, SDValue Chain, 7576 SDValue Ptr, SDValue Offset, 7577 MachinePointerInfo PtrInfo, EVT MemVT, 7578 Align Alignment, 7579 MachineMemOperand::Flags MMOFlags, 7580 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7581 assert(Chain.getValueType() == MVT::Other && 7582 "Invalid chain type"); 7583 7584 MMOFlags |= MachineMemOperand::MOLoad; 7585 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7586 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7587 // clients. 7588 if (PtrInfo.V.isNull()) 7589 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7590 7591 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7592 MachineFunction &MF = getMachineFunction(); 7593 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7594 Alignment, AAInfo, Ranges); 7595 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7596 } 7597 7598 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7599 EVT VT, const SDLoc &dl, SDValue Chain, 7600 SDValue Ptr, SDValue Offset, EVT MemVT, 7601 MachineMemOperand *MMO) { 7602 if (VT == MemVT) { 7603 ExtType = ISD::NON_EXTLOAD; 7604 } else if (ExtType == ISD::NON_EXTLOAD) { 7605 assert(VT == MemVT && "Non-extending load from different memory type!"); 7606 } else { 7607 // Extending load. 7608 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7609 "Should only be an extending load, not truncating!"); 7610 assert(VT.isInteger() == MemVT.isInteger() && 7611 "Cannot convert from FP to Int or Int -> FP!"); 7612 assert(VT.isVector() == MemVT.isVector() && 7613 "Cannot use an ext load to convert to or from a vector!"); 7614 assert((!VT.isVector() || 7615 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7616 "Cannot use an ext load to change the number of vector elements!"); 7617 } 7618 7619 bool Indexed = AM != ISD::UNINDEXED; 7620 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7621 7622 SDVTList VTs = Indexed ? 7623 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7624 SDValue Ops[] = { Chain, Ptr, Offset }; 7625 FoldingSetNodeID ID; 7626 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7627 ID.AddInteger(MemVT.getRawBits()); 7628 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7629 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7630 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7631 ID.AddInteger(MMO->getFlags()); 7632 void *IP = nullptr; 7633 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7634 cast<LoadSDNode>(E)->refineAlignment(MMO); 7635 return SDValue(E, 0); 7636 } 7637 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7638 ExtType, MemVT, MMO); 7639 createOperands(N, Ops); 7640 7641 CSEMap.InsertNode(N, IP); 7642 InsertNode(N); 7643 SDValue V(N, 0); 7644 NewSDValueDbgMsg(V, "Creating new node: ", this); 7645 return V; 7646 } 7647 7648 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7649 SDValue Ptr, MachinePointerInfo PtrInfo, 7650 MaybeAlign Alignment, 7651 MachineMemOperand::Flags MMOFlags, 7652 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7653 SDValue Undef = getUNDEF(Ptr.getValueType()); 7654 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7655 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7656 } 7657 7658 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7659 SDValue Ptr, MachineMemOperand *MMO) { 7660 SDValue Undef = getUNDEF(Ptr.getValueType()); 7661 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7662 VT, MMO); 7663 } 7664 7665 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7666 EVT VT, SDValue Chain, SDValue Ptr, 7667 MachinePointerInfo PtrInfo, EVT MemVT, 7668 MaybeAlign Alignment, 7669 MachineMemOperand::Flags MMOFlags, 7670 const AAMDNodes &AAInfo) { 7671 SDValue Undef = getUNDEF(Ptr.getValueType()); 7672 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7673 MemVT, Alignment, MMOFlags, AAInfo); 7674 } 7675 7676 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7677 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7678 MachineMemOperand *MMO) { 7679 SDValue Undef = getUNDEF(Ptr.getValueType()); 7680 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7681 MemVT, MMO); 7682 } 7683 7684 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7685 SDValue Base, SDValue Offset, 7686 ISD::MemIndexedMode AM) { 7687 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7688 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7689 // Don't propagate the invariant or dereferenceable flags. 7690 auto MMOFlags = 7691 LD->getMemOperand()->getFlags() & 7692 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7693 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7694 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7695 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7696 } 7697 7698 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7699 SDValue Ptr, MachinePointerInfo PtrInfo, 7700 Align Alignment, 7701 MachineMemOperand::Flags MMOFlags, 7702 const AAMDNodes &AAInfo) { 7703 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7704 7705 MMOFlags |= MachineMemOperand::MOStore; 7706 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7707 7708 if (PtrInfo.V.isNull()) 7709 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7710 7711 MachineFunction &MF = getMachineFunction(); 7712 uint64_t Size = 7713 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7714 MachineMemOperand *MMO = 7715 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7716 return getStore(Chain, dl, Val, Ptr, MMO); 7717 } 7718 7719 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7720 SDValue Ptr, MachineMemOperand *MMO) { 7721 assert(Chain.getValueType() == MVT::Other && 7722 "Invalid chain type"); 7723 EVT VT = Val.getValueType(); 7724 SDVTList VTs = getVTList(MVT::Other); 7725 SDValue Undef = getUNDEF(Ptr.getValueType()); 7726 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7727 FoldingSetNodeID ID; 7728 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7729 ID.AddInteger(VT.getRawBits()); 7730 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7731 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7732 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7733 ID.AddInteger(MMO->getFlags()); 7734 void *IP = nullptr; 7735 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7736 cast<StoreSDNode>(E)->refineAlignment(MMO); 7737 return SDValue(E, 0); 7738 } 7739 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7740 ISD::UNINDEXED, false, VT, MMO); 7741 createOperands(N, Ops); 7742 7743 CSEMap.InsertNode(N, IP); 7744 InsertNode(N); 7745 SDValue V(N, 0); 7746 NewSDValueDbgMsg(V, "Creating new node: ", this); 7747 return V; 7748 } 7749 7750 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7751 SDValue Ptr, MachinePointerInfo PtrInfo, 7752 EVT SVT, Align Alignment, 7753 MachineMemOperand::Flags MMOFlags, 7754 const AAMDNodes &AAInfo) { 7755 assert(Chain.getValueType() == MVT::Other && 7756 "Invalid chain type"); 7757 7758 MMOFlags |= MachineMemOperand::MOStore; 7759 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7760 7761 if (PtrInfo.V.isNull()) 7762 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7763 7764 MachineFunction &MF = getMachineFunction(); 7765 MachineMemOperand *MMO = MF.getMachineMemOperand( 7766 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7767 Alignment, AAInfo); 7768 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7769 } 7770 7771 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7772 SDValue Ptr, EVT SVT, 7773 MachineMemOperand *MMO) { 7774 EVT VT = Val.getValueType(); 7775 7776 assert(Chain.getValueType() == MVT::Other && 7777 "Invalid chain type"); 7778 if (VT == SVT) 7779 return getStore(Chain, dl, Val, Ptr, MMO); 7780 7781 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7782 "Should only be a truncating store, not extending!"); 7783 assert(VT.isInteger() == SVT.isInteger() && 7784 "Can't do FP-INT conversion!"); 7785 assert(VT.isVector() == SVT.isVector() && 7786 "Cannot use trunc store to convert to or from a vector!"); 7787 assert((!VT.isVector() || 7788 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7789 "Cannot use trunc store to change the number of vector elements!"); 7790 7791 SDVTList VTs = getVTList(MVT::Other); 7792 SDValue Undef = getUNDEF(Ptr.getValueType()); 7793 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7794 FoldingSetNodeID ID; 7795 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7796 ID.AddInteger(SVT.getRawBits()); 7797 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7798 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7799 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7800 ID.AddInteger(MMO->getFlags()); 7801 void *IP = nullptr; 7802 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7803 cast<StoreSDNode>(E)->refineAlignment(MMO); 7804 return SDValue(E, 0); 7805 } 7806 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7807 ISD::UNINDEXED, true, SVT, MMO); 7808 createOperands(N, Ops); 7809 7810 CSEMap.InsertNode(N, IP); 7811 InsertNode(N); 7812 SDValue V(N, 0); 7813 NewSDValueDbgMsg(V, "Creating new node: ", this); 7814 return V; 7815 } 7816 7817 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7818 SDValue Base, SDValue Offset, 7819 ISD::MemIndexedMode AM) { 7820 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7821 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7822 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7823 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7824 FoldingSetNodeID ID; 7825 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7826 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7827 ID.AddInteger(ST->getRawSubclassData()); 7828 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7829 ID.AddInteger(ST->getMemOperand()->getFlags()); 7830 void *IP = nullptr; 7831 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7832 return SDValue(E, 0); 7833 7834 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7835 ST->isTruncatingStore(), ST->getMemoryVT(), 7836 ST->getMemOperand()); 7837 createOperands(N, Ops); 7838 7839 CSEMap.InsertNode(N, IP); 7840 InsertNode(N); 7841 SDValue V(N, 0); 7842 NewSDValueDbgMsg(V, "Creating new node: ", this); 7843 return V; 7844 } 7845 7846 SDValue SelectionDAG::getLoadVP( 7847 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7848 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7849 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7850 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7851 const MDNode *Ranges, bool IsExpanding) { 7852 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7853 7854 MMOFlags |= MachineMemOperand::MOLoad; 7855 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7856 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7857 // clients. 7858 if (PtrInfo.V.isNull()) 7859 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7860 7861 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7862 MachineFunction &MF = getMachineFunction(); 7863 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7864 Alignment, AAInfo, Ranges); 7865 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7866 MMO, IsExpanding); 7867 } 7868 7869 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7870 ISD::LoadExtType ExtType, EVT VT, 7871 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7872 SDValue Offset, SDValue Mask, SDValue EVL, 7873 EVT MemVT, MachineMemOperand *MMO, 7874 bool IsExpanding) { 7875 bool Indexed = AM != ISD::UNINDEXED; 7876 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7877 7878 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7879 : getVTList(VT, MVT::Other); 7880 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7881 FoldingSetNodeID ID; 7882 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7883 ID.AddInteger(VT.getRawBits()); 7884 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7885 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7886 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7887 ID.AddInteger(MMO->getFlags()); 7888 void *IP = nullptr; 7889 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7890 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7891 return SDValue(E, 0); 7892 } 7893 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7894 ExtType, IsExpanding, MemVT, MMO); 7895 createOperands(N, Ops); 7896 7897 CSEMap.InsertNode(N, IP); 7898 InsertNode(N); 7899 SDValue V(N, 0); 7900 NewSDValueDbgMsg(V, "Creating new node: ", this); 7901 return V; 7902 } 7903 7904 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7905 SDValue Ptr, SDValue Mask, SDValue EVL, 7906 MachinePointerInfo PtrInfo, 7907 MaybeAlign Alignment, 7908 MachineMemOperand::Flags MMOFlags, 7909 const AAMDNodes &AAInfo, const MDNode *Ranges, 7910 bool IsExpanding) { 7911 SDValue Undef = getUNDEF(Ptr.getValueType()); 7912 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7913 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7914 IsExpanding); 7915 } 7916 7917 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7918 SDValue Ptr, SDValue Mask, SDValue EVL, 7919 MachineMemOperand *MMO, bool IsExpanding) { 7920 SDValue Undef = getUNDEF(Ptr.getValueType()); 7921 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7922 Mask, EVL, VT, MMO, IsExpanding); 7923 } 7924 7925 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7926 EVT VT, SDValue Chain, SDValue Ptr, 7927 SDValue Mask, SDValue EVL, 7928 MachinePointerInfo PtrInfo, EVT MemVT, 7929 MaybeAlign Alignment, 7930 MachineMemOperand::Flags MMOFlags, 7931 const AAMDNodes &AAInfo, bool IsExpanding) { 7932 SDValue Undef = getUNDEF(Ptr.getValueType()); 7933 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7934 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7935 IsExpanding); 7936 } 7937 7938 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7939 EVT VT, SDValue Chain, SDValue Ptr, 7940 SDValue Mask, SDValue EVL, EVT MemVT, 7941 MachineMemOperand *MMO, bool IsExpanding) { 7942 SDValue Undef = getUNDEF(Ptr.getValueType()); 7943 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7944 EVL, MemVT, MMO, IsExpanding); 7945 } 7946 7947 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7948 SDValue Base, SDValue Offset, 7949 ISD::MemIndexedMode AM) { 7950 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7951 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7952 // Don't propagate the invariant or dereferenceable flags. 7953 auto MMOFlags = 7954 LD->getMemOperand()->getFlags() & 7955 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7956 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7957 LD->getChain(), Base, Offset, LD->getMask(), 7958 LD->getVectorLength(), LD->getPointerInfo(), 7959 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7960 nullptr, LD->isExpandingLoad()); 7961 } 7962 7963 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7964 SDValue Ptr, SDValue Offset, SDValue Mask, 7965 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 7966 ISD::MemIndexedMode AM, bool IsTruncating, 7967 bool IsCompressing) { 7968 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7969 bool Indexed = AM != ISD::UNINDEXED; 7970 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 7971 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 7972 : getVTList(MVT::Other); 7973 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 7974 FoldingSetNodeID ID; 7975 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7976 ID.AddInteger(MemVT.getRawBits()); 7977 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7978 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7979 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7980 ID.AddInteger(MMO->getFlags()); 7981 void *IP = nullptr; 7982 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7983 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7984 return SDValue(E, 0); 7985 } 7986 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7987 IsTruncating, IsCompressing, MemVT, MMO); 7988 createOperands(N, Ops); 7989 7990 CSEMap.InsertNode(N, IP); 7991 InsertNode(N); 7992 SDValue V(N, 0); 7993 NewSDValueDbgMsg(V, "Creating new node: ", this); 7994 return V; 7995 } 7996 7997 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7998 SDValue Val, SDValue Ptr, SDValue Mask, 7999 SDValue EVL, MachinePointerInfo PtrInfo, 8000 EVT SVT, Align Alignment, 8001 MachineMemOperand::Flags MMOFlags, 8002 const AAMDNodes &AAInfo, 8003 bool IsCompressing) { 8004 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8005 8006 MMOFlags |= MachineMemOperand::MOStore; 8007 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8008 8009 if (PtrInfo.V.isNull()) 8010 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8011 8012 MachineFunction &MF = getMachineFunction(); 8013 MachineMemOperand *MMO = MF.getMachineMemOperand( 8014 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8015 Alignment, AAInfo); 8016 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8017 IsCompressing); 8018 } 8019 8020 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8021 SDValue Val, SDValue Ptr, SDValue Mask, 8022 SDValue EVL, EVT SVT, 8023 MachineMemOperand *MMO, 8024 bool IsCompressing) { 8025 EVT VT = Val.getValueType(); 8026 8027 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8028 if (VT == SVT) 8029 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8030 EVL, VT, MMO, ISD::UNINDEXED, 8031 /*IsTruncating*/ false, IsCompressing); 8032 8033 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8034 "Should only be a truncating store, not extending!"); 8035 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8036 assert(VT.isVector() == SVT.isVector() && 8037 "Cannot use trunc store to convert to or from a vector!"); 8038 assert((!VT.isVector() || 8039 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8040 "Cannot use trunc store to change the number of vector elements!"); 8041 8042 SDVTList VTs = getVTList(MVT::Other); 8043 SDValue Undef = getUNDEF(Ptr.getValueType()); 8044 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8045 FoldingSetNodeID ID; 8046 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8047 ID.AddInteger(SVT.getRawBits()); 8048 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8049 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8050 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8051 ID.AddInteger(MMO->getFlags()); 8052 void *IP = nullptr; 8053 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8054 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8055 return SDValue(E, 0); 8056 } 8057 auto *N = 8058 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8059 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8060 createOperands(N, Ops); 8061 8062 CSEMap.InsertNode(N, IP); 8063 InsertNode(N); 8064 SDValue V(N, 0); 8065 NewSDValueDbgMsg(V, "Creating new node: ", this); 8066 return V; 8067 } 8068 8069 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8070 SDValue Base, SDValue Offset, 8071 ISD::MemIndexedMode AM) { 8072 auto *ST = cast<VPStoreSDNode>(OrigStore); 8073 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8074 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8075 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8076 Offset, ST->getMask(), ST->getVectorLength()}; 8077 FoldingSetNodeID ID; 8078 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8079 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8080 ID.AddInteger(ST->getRawSubclassData()); 8081 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8082 ID.AddInteger(ST->getMemOperand()->getFlags()); 8083 void *IP = nullptr; 8084 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8085 return SDValue(E, 0); 8086 8087 auto *N = newSDNode<VPStoreSDNode>( 8088 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8089 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8090 createOperands(N, Ops); 8091 8092 CSEMap.InsertNode(N, IP); 8093 InsertNode(N); 8094 SDValue V(N, 0); 8095 NewSDValueDbgMsg(V, "Creating new node: ", this); 8096 return V; 8097 } 8098 8099 SDValue SelectionDAG::getStridedLoadVP( 8100 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8101 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8102 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8103 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8104 const MDNode *Ranges, bool IsExpanding) { 8105 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8106 8107 MMOFlags |= MachineMemOperand::MOLoad; 8108 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8109 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8110 // clients. 8111 if (PtrInfo.V.isNull()) 8112 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8113 8114 uint64_t Size = MemoryLocation::UnknownSize; 8115 MachineFunction &MF = getMachineFunction(); 8116 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8117 Alignment, AAInfo, Ranges); 8118 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8119 EVL, MemVT, MMO, IsExpanding); 8120 } 8121 8122 SDValue SelectionDAG::getStridedLoadVP( 8123 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8124 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8125 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8126 bool Indexed = AM != ISD::UNINDEXED; 8127 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8128 8129 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8130 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8131 : getVTList(VT, MVT::Other); 8132 FoldingSetNodeID ID; 8133 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8134 ID.AddInteger(VT.getRawBits()); 8135 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8136 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8137 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8138 8139 void *IP = nullptr; 8140 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8141 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8142 return SDValue(E, 0); 8143 } 8144 8145 auto *N = 8146 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8147 ExtType, IsExpanding, MemVT, MMO); 8148 createOperands(N, Ops); 8149 CSEMap.InsertNode(N, IP); 8150 InsertNode(N); 8151 SDValue V(N, 0); 8152 NewSDValueDbgMsg(V, "Creating new node: ", this); 8153 return V; 8154 } 8155 8156 SDValue SelectionDAG::getStridedLoadVP( 8157 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8158 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8159 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8160 const MDNode *Ranges, bool IsExpanding) { 8161 SDValue Undef = getUNDEF(Ptr.getValueType()); 8162 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8163 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8164 MMOFlags, AAInfo, Ranges, IsExpanding); 8165 } 8166 8167 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8168 SDValue Ptr, SDValue Stride, 8169 SDValue Mask, SDValue EVL, 8170 MachineMemOperand *MMO, 8171 bool IsExpanding) { 8172 SDValue Undef = getUNDEF(Ptr.getValueType()); 8173 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8174 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8175 } 8176 8177 SDValue SelectionDAG::getExtStridedLoadVP( 8178 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8179 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8180 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8181 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8182 bool IsExpanding) { 8183 SDValue Undef = getUNDEF(Ptr.getValueType()); 8184 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8185 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8186 MMOFlags, AAInfo, nullptr, IsExpanding); 8187 } 8188 8189 SDValue SelectionDAG::getExtStridedLoadVP( 8190 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8191 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8192 MachineMemOperand *MMO, bool IsExpanding) { 8193 SDValue Undef = getUNDEF(Ptr.getValueType()); 8194 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8195 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8196 } 8197 8198 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8199 SDValue Base, SDValue Offset, 8200 ISD::MemIndexedMode AM) { 8201 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8202 assert(SLD->getOffset().isUndef() && 8203 "Strided load is already a indexed load!"); 8204 // Don't propagate the invariant or dereferenceable flags. 8205 auto MMOFlags = 8206 SLD->getMemOperand()->getFlags() & 8207 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8208 return getStridedLoadVP( 8209 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8210 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8211 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8212 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8213 } 8214 8215 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8216 SDValue Val, SDValue Ptr, 8217 SDValue Offset, SDValue Stride, 8218 SDValue Mask, SDValue EVL, EVT MemVT, 8219 MachineMemOperand *MMO, 8220 ISD::MemIndexedMode AM, 8221 bool IsTruncating, bool IsCompressing) { 8222 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8223 bool Indexed = AM != ISD::UNINDEXED; 8224 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8225 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8226 : getVTList(MVT::Other); 8227 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8228 FoldingSetNodeID ID; 8229 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8230 ID.AddInteger(MemVT.getRawBits()); 8231 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8232 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8233 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8234 void *IP = nullptr; 8235 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8236 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8237 return SDValue(E, 0); 8238 } 8239 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8240 VTs, AM, IsTruncating, 8241 IsCompressing, MemVT, MMO); 8242 createOperands(N, Ops); 8243 8244 CSEMap.InsertNode(N, IP); 8245 InsertNode(N); 8246 SDValue V(N, 0); 8247 NewSDValueDbgMsg(V, "Creating new node: ", this); 8248 return V; 8249 } 8250 8251 SDValue SelectionDAG::getTruncStridedStoreVP( 8252 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8253 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8254 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8255 bool IsCompressing) { 8256 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8257 8258 MMOFlags |= MachineMemOperand::MOStore; 8259 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8260 8261 if (PtrInfo.V.isNull()) 8262 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8263 8264 MachineFunction &MF = getMachineFunction(); 8265 MachineMemOperand *MMO = MF.getMachineMemOperand( 8266 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8267 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8268 MMO, IsCompressing); 8269 } 8270 8271 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8272 SDValue Val, SDValue Ptr, 8273 SDValue Stride, SDValue Mask, 8274 SDValue EVL, EVT SVT, 8275 MachineMemOperand *MMO, 8276 bool IsCompressing) { 8277 EVT VT = Val.getValueType(); 8278 8279 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8280 if (VT == SVT) 8281 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8282 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8283 /*IsTruncating*/ false, IsCompressing); 8284 8285 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8286 "Should only be a truncating store, not extending!"); 8287 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8288 assert(VT.isVector() == SVT.isVector() && 8289 "Cannot use trunc store to convert to or from a vector!"); 8290 assert((!VT.isVector() || 8291 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8292 "Cannot use trunc store to change the number of vector elements!"); 8293 8294 SDVTList VTs = getVTList(MVT::Other); 8295 SDValue Undef = getUNDEF(Ptr.getValueType()); 8296 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8297 FoldingSetNodeID ID; 8298 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8299 ID.AddInteger(SVT.getRawBits()); 8300 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8301 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8302 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8303 void *IP = nullptr; 8304 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8305 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8306 return SDValue(E, 0); 8307 } 8308 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8309 VTs, ISD::UNINDEXED, true, 8310 IsCompressing, SVT, MMO); 8311 createOperands(N, Ops); 8312 8313 CSEMap.InsertNode(N, IP); 8314 InsertNode(N); 8315 SDValue V(N, 0); 8316 NewSDValueDbgMsg(V, "Creating new node: ", this); 8317 return V; 8318 } 8319 8320 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 8321 const SDLoc &DL, SDValue Base, 8322 SDValue Offset, 8323 ISD::MemIndexedMode AM) { 8324 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 8325 assert(SST->getOffset().isUndef() && 8326 "Strided store is already an indexed store!"); 8327 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8328 SDValue Ops[] = { 8329 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 8330 SST->getMask(), SST->getVectorLength()}; 8331 FoldingSetNodeID ID; 8332 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8333 ID.AddInteger(SST->getMemoryVT().getRawBits()); 8334 ID.AddInteger(SST->getRawSubclassData()); 8335 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 8336 void *IP = nullptr; 8337 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8338 return SDValue(E, 0); 8339 8340 auto *N = newSDNode<VPStridedStoreSDNode>( 8341 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 8342 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 8343 createOperands(N, Ops); 8344 8345 CSEMap.InsertNode(N, IP); 8346 InsertNode(N); 8347 SDValue V(N, 0); 8348 NewSDValueDbgMsg(V, "Creating new node: ", this); 8349 return V; 8350 } 8351 8352 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8353 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8354 ISD::MemIndexType IndexType) { 8355 assert(Ops.size() == 6 && "Incompatible number of operands"); 8356 8357 FoldingSetNodeID ID; 8358 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8359 ID.AddInteger(VT.getRawBits()); 8360 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8361 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8362 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8363 ID.AddInteger(MMO->getFlags()); 8364 void *IP = nullptr; 8365 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8366 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8367 return SDValue(E, 0); 8368 } 8369 8370 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8371 VT, MMO, IndexType); 8372 createOperands(N, Ops); 8373 8374 assert(N->getMask().getValueType().getVectorElementCount() == 8375 N->getValueType(0).getVectorElementCount() && 8376 "Vector width mismatch between mask and data"); 8377 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8378 N->getValueType(0).getVectorElementCount().isScalable() && 8379 "Scalable flags of index and data do not match"); 8380 assert(ElementCount::isKnownGE( 8381 N->getIndex().getValueType().getVectorElementCount(), 8382 N->getValueType(0).getVectorElementCount()) && 8383 "Vector width mismatch between index and data"); 8384 assert(isa<ConstantSDNode>(N->getScale()) && 8385 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8386 "Scale should be a constant power of 2"); 8387 8388 CSEMap.InsertNode(N, IP); 8389 InsertNode(N); 8390 SDValue V(N, 0); 8391 NewSDValueDbgMsg(V, "Creating new node: ", this); 8392 return V; 8393 } 8394 8395 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8396 ArrayRef<SDValue> Ops, 8397 MachineMemOperand *MMO, 8398 ISD::MemIndexType IndexType) { 8399 assert(Ops.size() == 7 && "Incompatible number of operands"); 8400 8401 FoldingSetNodeID ID; 8402 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8403 ID.AddInteger(VT.getRawBits()); 8404 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8405 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8406 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8407 ID.AddInteger(MMO->getFlags()); 8408 void *IP = nullptr; 8409 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8410 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8411 return SDValue(E, 0); 8412 } 8413 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8414 VT, MMO, IndexType); 8415 createOperands(N, Ops); 8416 8417 assert(N->getMask().getValueType().getVectorElementCount() == 8418 N->getValue().getValueType().getVectorElementCount() && 8419 "Vector width mismatch between mask and data"); 8420 assert( 8421 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8422 N->getValue().getValueType().getVectorElementCount().isScalable() && 8423 "Scalable flags of index and data do not match"); 8424 assert(ElementCount::isKnownGE( 8425 N->getIndex().getValueType().getVectorElementCount(), 8426 N->getValue().getValueType().getVectorElementCount()) && 8427 "Vector width mismatch between index and data"); 8428 assert(isa<ConstantSDNode>(N->getScale()) && 8429 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8430 "Scale should be a constant power of 2"); 8431 8432 CSEMap.InsertNode(N, IP); 8433 InsertNode(N); 8434 SDValue V(N, 0); 8435 NewSDValueDbgMsg(V, "Creating new node: ", this); 8436 return V; 8437 } 8438 8439 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8440 SDValue Base, SDValue Offset, SDValue Mask, 8441 SDValue PassThru, EVT MemVT, 8442 MachineMemOperand *MMO, 8443 ISD::MemIndexedMode AM, 8444 ISD::LoadExtType ExtTy, bool isExpanding) { 8445 bool Indexed = AM != ISD::UNINDEXED; 8446 assert((Indexed || Offset.isUndef()) && 8447 "Unindexed masked load with an offset!"); 8448 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8449 : getVTList(VT, MVT::Other); 8450 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8451 FoldingSetNodeID ID; 8452 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8453 ID.AddInteger(MemVT.getRawBits()); 8454 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8455 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8456 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8457 ID.AddInteger(MMO->getFlags()); 8458 void *IP = nullptr; 8459 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8460 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8461 return SDValue(E, 0); 8462 } 8463 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8464 AM, ExtTy, isExpanding, MemVT, MMO); 8465 createOperands(N, Ops); 8466 8467 CSEMap.InsertNode(N, IP); 8468 InsertNode(N); 8469 SDValue V(N, 0); 8470 NewSDValueDbgMsg(V, "Creating new node: ", this); 8471 return V; 8472 } 8473 8474 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8475 SDValue Base, SDValue Offset, 8476 ISD::MemIndexedMode AM) { 8477 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8478 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8479 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8480 Offset, LD->getMask(), LD->getPassThru(), 8481 LD->getMemoryVT(), LD->getMemOperand(), AM, 8482 LD->getExtensionType(), LD->isExpandingLoad()); 8483 } 8484 8485 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8486 SDValue Val, SDValue Base, SDValue Offset, 8487 SDValue Mask, EVT MemVT, 8488 MachineMemOperand *MMO, 8489 ISD::MemIndexedMode AM, bool IsTruncating, 8490 bool IsCompressing) { 8491 assert(Chain.getValueType() == MVT::Other && 8492 "Invalid chain type"); 8493 bool Indexed = AM != ISD::UNINDEXED; 8494 assert((Indexed || Offset.isUndef()) && 8495 "Unindexed masked store with an offset!"); 8496 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8497 : getVTList(MVT::Other); 8498 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8499 FoldingSetNodeID ID; 8500 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8501 ID.AddInteger(MemVT.getRawBits()); 8502 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8503 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8504 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8505 ID.AddInteger(MMO->getFlags()); 8506 void *IP = nullptr; 8507 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8508 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8509 return SDValue(E, 0); 8510 } 8511 auto *N = 8512 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8513 IsTruncating, IsCompressing, MemVT, MMO); 8514 createOperands(N, Ops); 8515 8516 CSEMap.InsertNode(N, IP); 8517 InsertNode(N); 8518 SDValue V(N, 0); 8519 NewSDValueDbgMsg(V, "Creating new node: ", this); 8520 return V; 8521 } 8522 8523 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8524 SDValue Base, SDValue Offset, 8525 ISD::MemIndexedMode AM) { 8526 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8527 assert(ST->getOffset().isUndef() && 8528 "Masked store is already a indexed store!"); 8529 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8530 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8531 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8532 } 8533 8534 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8535 ArrayRef<SDValue> Ops, 8536 MachineMemOperand *MMO, 8537 ISD::MemIndexType IndexType, 8538 ISD::LoadExtType ExtTy) { 8539 assert(Ops.size() == 6 && "Incompatible number of operands"); 8540 8541 FoldingSetNodeID ID; 8542 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8543 ID.AddInteger(MemVT.getRawBits()); 8544 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8545 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8546 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8547 ID.AddInteger(MMO->getFlags()); 8548 void *IP = nullptr; 8549 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8550 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8551 return SDValue(E, 0); 8552 } 8553 8554 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8555 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8556 VTs, MemVT, MMO, IndexType, ExtTy); 8557 createOperands(N, Ops); 8558 8559 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8560 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8561 assert(N->getMask().getValueType().getVectorElementCount() == 8562 N->getValueType(0).getVectorElementCount() && 8563 "Vector width mismatch between mask and data"); 8564 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8565 N->getValueType(0).getVectorElementCount().isScalable() && 8566 "Scalable flags of index and data do not match"); 8567 assert(ElementCount::isKnownGE( 8568 N->getIndex().getValueType().getVectorElementCount(), 8569 N->getValueType(0).getVectorElementCount()) && 8570 "Vector width mismatch between index and data"); 8571 assert(isa<ConstantSDNode>(N->getScale()) && 8572 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8573 "Scale should be a constant power of 2"); 8574 8575 CSEMap.InsertNode(N, IP); 8576 InsertNode(N); 8577 SDValue V(N, 0); 8578 NewSDValueDbgMsg(V, "Creating new node: ", this); 8579 return V; 8580 } 8581 8582 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8583 ArrayRef<SDValue> Ops, 8584 MachineMemOperand *MMO, 8585 ISD::MemIndexType IndexType, 8586 bool IsTrunc) { 8587 assert(Ops.size() == 6 && "Incompatible number of operands"); 8588 8589 FoldingSetNodeID ID; 8590 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8591 ID.AddInteger(MemVT.getRawBits()); 8592 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8593 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8594 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8595 ID.AddInteger(MMO->getFlags()); 8596 void *IP = nullptr; 8597 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8598 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8599 return SDValue(E, 0); 8600 } 8601 8602 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8603 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8604 VTs, MemVT, MMO, IndexType, IsTrunc); 8605 createOperands(N, Ops); 8606 8607 assert(N->getMask().getValueType().getVectorElementCount() == 8608 N->getValue().getValueType().getVectorElementCount() && 8609 "Vector width mismatch between mask and data"); 8610 assert( 8611 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8612 N->getValue().getValueType().getVectorElementCount().isScalable() && 8613 "Scalable flags of index and data do not match"); 8614 assert(ElementCount::isKnownGE( 8615 N->getIndex().getValueType().getVectorElementCount(), 8616 N->getValue().getValueType().getVectorElementCount()) && 8617 "Vector width mismatch between index and data"); 8618 assert(isa<ConstantSDNode>(N->getScale()) && 8619 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8620 "Scale should be a constant power of 2"); 8621 8622 CSEMap.InsertNode(N, IP); 8623 InsertNode(N); 8624 SDValue V(N, 0); 8625 NewSDValueDbgMsg(V, "Creating new node: ", this); 8626 return V; 8627 } 8628 8629 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8630 // select undef, T, F --> T (if T is a constant), otherwise F 8631 // select, ?, undef, F --> F 8632 // select, ?, T, undef --> T 8633 if (Cond.isUndef()) 8634 return isConstantValueOfAnyType(T) ? T : F; 8635 if (T.isUndef()) 8636 return F; 8637 if (F.isUndef()) 8638 return T; 8639 8640 // select true, T, F --> T 8641 // select false, T, F --> F 8642 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8643 return CondC->isZero() ? F : T; 8644 8645 // TODO: This should simplify VSELECT with constant condition using something 8646 // like this (but check boolean contents to be complete?): 8647 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8648 // return T; 8649 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8650 // return F; 8651 8652 // select ?, T, T --> T 8653 if (T == F) 8654 return T; 8655 8656 return SDValue(); 8657 } 8658 8659 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8660 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8661 if (X.isUndef()) 8662 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8663 // shift X, undef --> undef (because it may shift by the bitwidth) 8664 if (Y.isUndef()) 8665 return getUNDEF(X.getValueType()); 8666 8667 // shift 0, Y --> 0 8668 // shift X, 0 --> X 8669 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8670 return X; 8671 8672 // shift X, C >= bitwidth(X) --> undef 8673 // All vector elements must be too big (or undef) to avoid partial undefs. 8674 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8675 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8676 }; 8677 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8678 return getUNDEF(X.getValueType()); 8679 8680 return SDValue(); 8681 } 8682 8683 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8684 SDNodeFlags Flags) { 8685 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8686 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8687 // operation is poison. That result can be relaxed to undef. 8688 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8689 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8690 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8691 (YC && YC->getValueAPF().isNaN()); 8692 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8693 (YC && YC->getValueAPF().isInfinity()); 8694 8695 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8696 return getUNDEF(X.getValueType()); 8697 8698 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8699 return getUNDEF(X.getValueType()); 8700 8701 if (!YC) 8702 return SDValue(); 8703 8704 // X + -0.0 --> X 8705 if (Opcode == ISD::FADD) 8706 if (YC->getValueAPF().isNegZero()) 8707 return X; 8708 8709 // X - +0.0 --> X 8710 if (Opcode == ISD::FSUB) 8711 if (YC->getValueAPF().isPosZero()) 8712 return X; 8713 8714 // X * 1.0 --> X 8715 // X / 1.0 --> X 8716 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8717 if (YC->getValueAPF().isExactlyValue(1.0)) 8718 return X; 8719 8720 // X * 0.0 --> 0.0 8721 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8722 if (YC->getValueAPF().isZero()) 8723 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8724 8725 return SDValue(); 8726 } 8727 8728 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8729 SDValue Ptr, SDValue SV, unsigned Align) { 8730 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8731 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8732 } 8733 8734 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8735 ArrayRef<SDUse> Ops) { 8736 switch (Ops.size()) { 8737 case 0: return getNode(Opcode, DL, VT); 8738 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8739 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8740 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8741 default: break; 8742 } 8743 8744 // Copy from an SDUse array into an SDValue array for use with 8745 // the regular getNode logic. 8746 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8747 return getNode(Opcode, DL, VT, NewOps); 8748 } 8749 8750 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8751 ArrayRef<SDValue> Ops) { 8752 SDNodeFlags Flags; 8753 if (Inserter) 8754 Flags = Inserter->getFlags(); 8755 return getNode(Opcode, DL, VT, Ops, Flags); 8756 } 8757 8758 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8759 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8760 unsigned NumOps = Ops.size(); 8761 switch (NumOps) { 8762 case 0: return getNode(Opcode, DL, VT); 8763 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8764 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8765 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8766 default: break; 8767 } 8768 8769 #ifndef NDEBUG 8770 for (auto &Op : Ops) 8771 assert(Op.getOpcode() != ISD::DELETED_NODE && 8772 "Operand is DELETED_NODE!"); 8773 #endif 8774 8775 switch (Opcode) { 8776 default: break; 8777 case ISD::BUILD_VECTOR: 8778 // Attempt to simplify BUILD_VECTOR. 8779 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8780 return V; 8781 break; 8782 case ISD::CONCAT_VECTORS: 8783 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8784 return V; 8785 break; 8786 case ISD::SELECT_CC: 8787 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8788 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8789 "LHS and RHS of condition must have same type!"); 8790 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8791 "True and False arms of SelectCC must have same type!"); 8792 assert(Ops[2].getValueType() == VT && 8793 "select_cc node must be of same type as true and false value!"); 8794 break; 8795 case ISD::BR_CC: 8796 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8797 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8798 "LHS/RHS of comparison should match types!"); 8799 break; 8800 } 8801 8802 // Memoize nodes. 8803 SDNode *N; 8804 SDVTList VTs = getVTList(VT); 8805 8806 if (VT != MVT::Glue) { 8807 FoldingSetNodeID ID; 8808 AddNodeIDNode(ID, Opcode, VTs, Ops); 8809 void *IP = nullptr; 8810 8811 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8812 return SDValue(E, 0); 8813 8814 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8815 createOperands(N, Ops); 8816 8817 CSEMap.InsertNode(N, IP); 8818 } else { 8819 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8820 createOperands(N, Ops); 8821 } 8822 8823 N->setFlags(Flags); 8824 InsertNode(N); 8825 SDValue V(N, 0); 8826 NewSDValueDbgMsg(V, "Creating new node: ", this); 8827 return V; 8828 } 8829 8830 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8831 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8832 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8833 } 8834 8835 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8836 ArrayRef<SDValue> Ops) { 8837 SDNodeFlags Flags; 8838 if (Inserter) 8839 Flags = Inserter->getFlags(); 8840 return getNode(Opcode, DL, VTList, Ops, Flags); 8841 } 8842 8843 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8844 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8845 if (VTList.NumVTs == 1) 8846 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8847 8848 #ifndef NDEBUG 8849 for (auto &Op : Ops) 8850 assert(Op.getOpcode() != ISD::DELETED_NODE && 8851 "Operand is DELETED_NODE!"); 8852 #endif 8853 8854 switch (Opcode) { 8855 case ISD::STRICT_FP_EXTEND: 8856 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8857 "Invalid STRICT_FP_EXTEND!"); 8858 assert(VTList.VTs[0].isFloatingPoint() && 8859 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8860 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8861 "STRICT_FP_EXTEND result type should be vector iff the operand " 8862 "type is vector!"); 8863 assert((!VTList.VTs[0].isVector() || 8864 VTList.VTs[0].getVectorNumElements() == 8865 Ops[1].getValueType().getVectorNumElements()) && 8866 "Vector element count mismatch!"); 8867 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8868 "Invalid fpext node, dst <= src!"); 8869 break; 8870 case ISD::STRICT_FP_ROUND: 8871 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8872 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8873 "STRICT_FP_ROUND result type should be vector iff the operand " 8874 "type is vector!"); 8875 assert((!VTList.VTs[0].isVector() || 8876 VTList.VTs[0].getVectorNumElements() == 8877 Ops[1].getValueType().getVectorNumElements()) && 8878 "Vector element count mismatch!"); 8879 assert(VTList.VTs[0].isFloatingPoint() && 8880 Ops[1].getValueType().isFloatingPoint() && 8881 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8882 isa<ConstantSDNode>(Ops[2]) && 8883 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8884 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8885 "Invalid STRICT_FP_ROUND!"); 8886 break; 8887 #if 0 8888 // FIXME: figure out how to safely handle things like 8889 // int foo(int x) { return 1 << (x & 255); } 8890 // int bar() { return foo(256); } 8891 case ISD::SRA_PARTS: 8892 case ISD::SRL_PARTS: 8893 case ISD::SHL_PARTS: 8894 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8895 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8896 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8897 else if (N3.getOpcode() == ISD::AND) 8898 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8899 // If the and is only masking out bits that cannot effect the shift, 8900 // eliminate the and. 8901 unsigned NumBits = VT.getScalarSizeInBits()*2; 8902 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8903 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8904 } 8905 break; 8906 #endif 8907 } 8908 8909 // Memoize the node unless it returns a flag. 8910 SDNode *N; 8911 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8912 FoldingSetNodeID ID; 8913 AddNodeIDNode(ID, Opcode, VTList, Ops); 8914 void *IP = nullptr; 8915 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8916 return SDValue(E, 0); 8917 8918 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8919 createOperands(N, Ops); 8920 CSEMap.InsertNode(N, IP); 8921 } else { 8922 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8923 createOperands(N, Ops); 8924 } 8925 8926 N->setFlags(Flags); 8927 InsertNode(N); 8928 SDValue V(N, 0); 8929 NewSDValueDbgMsg(V, "Creating new node: ", this); 8930 return V; 8931 } 8932 8933 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8934 SDVTList VTList) { 8935 return getNode(Opcode, DL, VTList, None); 8936 } 8937 8938 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8939 SDValue N1) { 8940 SDValue Ops[] = { N1 }; 8941 return getNode(Opcode, DL, VTList, Ops); 8942 } 8943 8944 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8945 SDValue N1, SDValue N2) { 8946 SDValue Ops[] = { N1, N2 }; 8947 return getNode(Opcode, DL, VTList, Ops); 8948 } 8949 8950 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8951 SDValue N1, SDValue N2, SDValue N3) { 8952 SDValue Ops[] = { N1, N2, N3 }; 8953 return getNode(Opcode, DL, VTList, Ops); 8954 } 8955 8956 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8957 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8958 SDValue Ops[] = { N1, N2, N3, N4 }; 8959 return getNode(Opcode, DL, VTList, Ops); 8960 } 8961 8962 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8963 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8964 SDValue N5) { 8965 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8966 return getNode(Opcode, DL, VTList, Ops); 8967 } 8968 8969 SDVTList SelectionDAG::getVTList(EVT VT) { 8970 return makeVTList(SDNode::getValueTypeList(VT), 1); 8971 } 8972 8973 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8974 FoldingSetNodeID ID; 8975 ID.AddInteger(2U); 8976 ID.AddInteger(VT1.getRawBits()); 8977 ID.AddInteger(VT2.getRawBits()); 8978 8979 void *IP = nullptr; 8980 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8981 if (!Result) { 8982 EVT *Array = Allocator.Allocate<EVT>(2); 8983 Array[0] = VT1; 8984 Array[1] = VT2; 8985 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8986 VTListMap.InsertNode(Result, IP); 8987 } 8988 return Result->getSDVTList(); 8989 } 8990 8991 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 8992 FoldingSetNodeID ID; 8993 ID.AddInteger(3U); 8994 ID.AddInteger(VT1.getRawBits()); 8995 ID.AddInteger(VT2.getRawBits()); 8996 ID.AddInteger(VT3.getRawBits()); 8997 8998 void *IP = nullptr; 8999 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9000 if (!Result) { 9001 EVT *Array = Allocator.Allocate<EVT>(3); 9002 Array[0] = VT1; 9003 Array[1] = VT2; 9004 Array[2] = VT3; 9005 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9006 VTListMap.InsertNode(Result, IP); 9007 } 9008 return Result->getSDVTList(); 9009 } 9010 9011 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9012 FoldingSetNodeID ID; 9013 ID.AddInteger(4U); 9014 ID.AddInteger(VT1.getRawBits()); 9015 ID.AddInteger(VT2.getRawBits()); 9016 ID.AddInteger(VT3.getRawBits()); 9017 ID.AddInteger(VT4.getRawBits()); 9018 9019 void *IP = nullptr; 9020 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9021 if (!Result) { 9022 EVT *Array = Allocator.Allocate<EVT>(4); 9023 Array[0] = VT1; 9024 Array[1] = VT2; 9025 Array[2] = VT3; 9026 Array[3] = VT4; 9027 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9028 VTListMap.InsertNode(Result, IP); 9029 } 9030 return Result->getSDVTList(); 9031 } 9032 9033 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9034 unsigned NumVTs = VTs.size(); 9035 FoldingSetNodeID ID; 9036 ID.AddInteger(NumVTs); 9037 for (unsigned index = 0; index < NumVTs; index++) { 9038 ID.AddInteger(VTs[index].getRawBits()); 9039 } 9040 9041 void *IP = nullptr; 9042 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9043 if (!Result) { 9044 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9045 llvm::copy(VTs, Array); 9046 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9047 VTListMap.InsertNode(Result, IP); 9048 } 9049 return Result->getSDVTList(); 9050 } 9051 9052 9053 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9054 /// specified operands. If the resultant node already exists in the DAG, 9055 /// this does not modify the specified node, instead it returns the node that 9056 /// already exists. If the resultant node does not exist in the DAG, the 9057 /// input node is returned. As a degenerate case, if you specify the same 9058 /// input operands as the node already has, the input node is returned. 9059 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9060 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9061 9062 // Check to see if there is no change. 9063 if (Op == N->getOperand(0)) return N; 9064 9065 // See if the modified node already exists. 9066 void *InsertPos = nullptr; 9067 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9068 return Existing; 9069 9070 // Nope it doesn't. Remove the node from its current place in the maps. 9071 if (InsertPos) 9072 if (!RemoveNodeFromCSEMaps(N)) 9073 InsertPos = nullptr; 9074 9075 // Now we update the operands. 9076 N->OperandList[0].set(Op); 9077 9078 updateDivergence(N); 9079 // If this gets put into a CSE map, add it. 9080 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9081 return N; 9082 } 9083 9084 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9085 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9086 9087 // Check to see if there is no change. 9088 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9089 return N; // No operands changed, just return the input node. 9090 9091 // See if the modified node already exists. 9092 void *InsertPos = nullptr; 9093 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9094 return Existing; 9095 9096 // Nope it doesn't. Remove the node from its current place in the maps. 9097 if (InsertPos) 9098 if (!RemoveNodeFromCSEMaps(N)) 9099 InsertPos = nullptr; 9100 9101 // Now we update the operands. 9102 if (N->OperandList[0] != Op1) 9103 N->OperandList[0].set(Op1); 9104 if (N->OperandList[1] != Op2) 9105 N->OperandList[1].set(Op2); 9106 9107 updateDivergence(N); 9108 // If this gets put into a CSE map, add it. 9109 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9110 return N; 9111 } 9112 9113 SDNode *SelectionDAG:: 9114 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9115 SDValue Ops[] = { Op1, Op2, Op3 }; 9116 return UpdateNodeOperands(N, Ops); 9117 } 9118 9119 SDNode *SelectionDAG:: 9120 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9121 SDValue Op3, SDValue Op4) { 9122 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9123 return UpdateNodeOperands(N, Ops); 9124 } 9125 9126 SDNode *SelectionDAG:: 9127 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9128 SDValue Op3, SDValue Op4, SDValue Op5) { 9129 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9130 return UpdateNodeOperands(N, Ops); 9131 } 9132 9133 SDNode *SelectionDAG:: 9134 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9135 unsigned NumOps = Ops.size(); 9136 assert(N->getNumOperands() == NumOps && 9137 "Update with wrong number of operands"); 9138 9139 // If no operands changed just return the input node. 9140 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9141 return N; 9142 9143 // See if the modified node already exists. 9144 void *InsertPos = nullptr; 9145 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9146 return Existing; 9147 9148 // Nope it doesn't. Remove the node from its current place in the maps. 9149 if (InsertPos) 9150 if (!RemoveNodeFromCSEMaps(N)) 9151 InsertPos = nullptr; 9152 9153 // Now we update the operands. 9154 for (unsigned i = 0; i != NumOps; ++i) 9155 if (N->OperandList[i] != Ops[i]) 9156 N->OperandList[i].set(Ops[i]); 9157 9158 updateDivergence(N); 9159 // If this gets put into a CSE map, add it. 9160 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9161 return N; 9162 } 9163 9164 /// DropOperands - Release the operands and set this node to have 9165 /// zero operands. 9166 void SDNode::DropOperands() { 9167 // Unlike the code in MorphNodeTo that does this, we don't need to 9168 // watch for dead nodes here. 9169 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9170 SDUse &Use = *I++; 9171 Use.set(SDValue()); 9172 } 9173 } 9174 9175 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9176 ArrayRef<MachineMemOperand *> NewMemRefs) { 9177 if (NewMemRefs.empty()) { 9178 N->clearMemRefs(); 9179 return; 9180 } 9181 9182 // Check if we can avoid allocating by storing a single reference directly. 9183 if (NewMemRefs.size() == 1) { 9184 N->MemRefs = NewMemRefs[0]; 9185 N->NumMemRefs = 1; 9186 return; 9187 } 9188 9189 MachineMemOperand **MemRefsBuffer = 9190 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 9191 llvm::copy(NewMemRefs, MemRefsBuffer); 9192 N->MemRefs = MemRefsBuffer; 9193 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 9194 } 9195 9196 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 9197 /// machine opcode. 9198 /// 9199 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9200 EVT VT) { 9201 SDVTList VTs = getVTList(VT); 9202 return SelectNodeTo(N, MachineOpc, VTs, None); 9203 } 9204 9205 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9206 EVT VT, SDValue Op1) { 9207 SDVTList VTs = getVTList(VT); 9208 SDValue Ops[] = { Op1 }; 9209 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9210 } 9211 9212 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9213 EVT VT, SDValue Op1, 9214 SDValue Op2) { 9215 SDVTList VTs = getVTList(VT); 9216 SDValue Ops[] = { Op1, Op2 }; 9217 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9218 } 9219 9220 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9221 EVT VT, SDValue Op1, 9222 SDValue Op2, SDValue Op3) { 9223 SDVTList VTs = getVTList(VT); 9224 SDValue Ops[] = { Op1, Op2, Op3 }; 9225 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9226 } 9227 9228 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9229 EVT VT, ArrayRef<SDValue> Ops) { 9230 SDVTList VTs = getVTList(VT); 9231 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9232 } 9233 9234 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9235 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 9236 SDVTList VTs = getVTList(VT1, VT2); 9237 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9238 } 9239 9240 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9241 EVT VT1, EVT VT2) { 9242 SDVTList VTs = getVTList(VT1, VT2); 9243 return SelectNodeTo(N, MachineOpc, VTs, None); 9244 } 9245 9246 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9247 EVT VT1, EVT VT2, EVT VT3, 9248 ArrayRef<SDValue> Ops) { 9249 SDVTList VTs = getVTList(VT1, VT2, VT3); 9250 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9251 } 9252 9253 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9254 EVT VT1, EVT VT2, 9255 SDValue Op1, SDValue Op2) { 9256 SDVTList VTs = getVTList(VT1, VT2); 9257 SDValue Ops[] = { Op1, Op2 }; 9258 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9259 } 9260 9261 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9262 SDVTList VTs,ArrayRef<SDValue> Ops) { 9263 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 9264 // Reset the NodeID to -1. 9265 New->setNodeId(-1); 9266 if (New != N) { 9267 ReplaceAllUsesWith(N, New); 9268 RemoveDeadNode(N); 9269 } 9270 return New; 9271 } 9272 9273 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 9274 /// the line number information on the merged node since it is not possible to 9275 /// preserve the information that operation is associated with multiple lines. 9276 /// This will make the debugger working better at -O0, were there is a higher 9277 /// probability having other instructions associated with that line. 9278 /// 9279 /// For IROrder, we keep the smaller of the two 9280 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 9281 DebugLoc NLoc = N->getDebugLoc(); 9282 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 9283 N->setDebugLoc(DebugLoc()); 9284 } 9285 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 9286 N->setIROrder(Order); 9287 return N; 9288 } 9289 9290 /// MorphNodeTo - This *mutates* the specified node to have the specified 9291 /// return type, opcode, and operands. 9292 /// 9293 /// Note that MorphNodeTo returns the resultant node. If there is already a 9294 /// node of the specified opcode and operands, it returns that node instead of 9295 /// the current one. Note that the SDLoc need not be the same. 9296 /// 9297 /// Using MorphNodeTo is faster than creating a new node and swapping it in 9298 /// with ReplaceAllUsesWith both because it often avoids allocating a new 9299 /// node, and because it doesn't require CSE recalculation for any of 9300 /// the node's users. 9301 /// 9302 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 9303 /// As a consequence it isn't appropriate to use from within the DAG combiner or 9304 /// the legalizer which maintain worklists that would need to be updated when 9305 /// deleting things. 9306 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 9307 SDVTList VTs, ArrayRef<SDValue> Ops) { 9308 // If an identical node already exists, use it. 9309 void *IP = nullptr; 9310 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 9311 FoldingSetNodeID ID; 9312 AddNodeIDNode(ID, Opc, VTs, Ops); 9313 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 9314 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 9315 } 9316 9317 if (!RemoveNodeFromCSEMaps(N)) 9318 IP = nullptr; 9319 9320 // Start the morphing. 9321 N->NodeType = Opc; 9322 N->ValueList = VTs.VTs; 9323 N->NumValues = VTs.NumVTs; 9324 9325 // Clear the operands list, updating used nodes to remove this from their 9326 // use list. Keep track of any operands that become dead as a result. 9327 SmallPtrSet<SDNode*, 16> DeadNodeSet; 9328 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 9329 SDUse &Use = *I++; 9330 SDNode *Used = Use.getNode(); 9331 Use.set(SDValue()); 9332 if (Used->use_empty()) 9333 DeadNodeSet.insert(Used); 9334 } 9335 9336 // For MachineNode, initialize the memory references information. 9337 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 9338 MN->clearMemRefs(); 9339 9340 // Swap for an appropriately sized array from the recycler. 9341 removeOperands(N); 9342 createOperands(N, Ops); 9343 9344 // Delete any nodes that are still dead after adding the uses for the 9345 // new operands. 9346 if (!DeadNodeSet.empty()) { 9347 SmallVector<SDNode *, 16> DeadNodes; 9348 for (SDNode *N : DeadNodeSet) 9349 if (N->use_empty()) 9350 DeadNodes.push_back(N); 9351 RemoveDeadNodes(DeadNodes); 9352 } 9353 9354 if (IP) 9355 CSEMap.InsertNode(N, IP); // Memoize the new node. 9356 return N; 9357 } 9358 9359 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9360 unsigned OrigOpc = Node->getOpcode(); 9361 unsigned NewOpc; 9362 switch (OrigOpc) { 9363 default: 9364 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9365 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9366 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9367 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9368 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9369 #include "llvm/IR/ConstrainedOps.def" 9370 } 9371 9372 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9373 9374 // We're taking this node out of the chain, so we need to re-link things. 9375 SDValue InputChain = Node->getOperand(0); 9376 SDValue OutputChain = SDValue(Node, 1); 9377 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9378 9379 SmallVector<SDValue, 3> Ops; 9380 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9381 Ops.push_back(Node->getOperand(i)); 9382 9383 SDVTList VTs = getVTList(Node->getValueType(0)); 9384 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9385 9386 // MorphNodeTo can operate in two ways: if an existing node with the 9387 // specified operands exists, it can just return it. Otherwise, it 9388 // updates the node in place to have the requested operands. 9389 if (Res == Node) { 9390 // If we updated the node in place, reset the node ID. To the isel, 9391 // this should be just like a newly allocated machine node. 9392 Res->setNodeId(-1); 9393 } else { 9394 ReplaceAllUsesWith(Node, Res); 9395 RemoveDeadNode(Node); 9396 } 9397 9398 return Res; 9399 } 9400 9401 /// getMachineNode - These are used for target selectors to create a new node 9402 /// with specified return type(s), MachineInstr opcode, and operands. 9403 /// 9404 /// Note that getMachineNode returns the resultant node. If there is already a 9405 /// node of the specified opcode and operands, it returns that node instead of 9406 /// the current one. 9407 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9408 EVT VT) { 9409 SDVTList VTs = getVTList(VT); 9410 return getMachineNode(Opcode, dl, VTs, None); 9411 } 9412 9413 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9414 EVT VT, SDValue Op1) { 9415 SDVTList VTs = getVTList(VT); 9416 SDValue Ops[] = { Op1 }; 9417 return getMachineNode(Opcode, dl, VTs, Ops); 9418 } 9419 9420 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9421 EVT VT, SDValue Op1, SDValue Op2) { 9422 SDVTList VTs = getVTList(VT); 9423 SDValue Ops[] = { Op1, Op2 }; 9424 return getMachineNode(Opcode, dl, VTs, Ops); 9425 } 9426 9427 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9428 EVT VT, SDValue Op1, SDValue Op2, 9429 SDValue Op3) { 9430 SDVTList VTs = getVTList(VT); 9431 SDValue Ops[] = { Op1, Op2, Op3 }; 9432 return getMachineNode(Opcode, dl, VTs, Ops); 9433 } 9434 9435 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9436 EVT VT, ArrayRef<SDValue> Ops) { 9437 SDVTList VTs = getVTList(VT); 9438 return getMachineNode(Opcode, dl, VTs, Ops); 9439 } 9440 9441 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9442 EVT VT1, EVT VT2, SDValue Op1, 9443 SDValue Op2) { 9444 SDVTList VTs = getVTList(VT1, VT2); 9445 SDValue Ops[] = { Op1, Op2 }; 9446 return getMachineNode(Opcode, dl, VTs, Ops); 9447 } 9448 9449 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9450 EVT VT1, EVT VT2, SDValue Op1, 9451 SDValue Op2, SDValue Op3) { 9452 SDVTList VTs = getVTList(VT1, VT2); 9453 SDValue Ops[] = { Op1, Op2, Op3 }; 9454 return getMachineNode(Opcode, dl, VTs, Ops); 9455 } 9456 9457 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9458 EVT VT1, EVT VT2, 9459 ArrayRef<SDValue> Ops) { 9460 SDVTList VTs = getVTList(VT1, VT2); 9461 return getMachineNode(Opcode, dl, VTs, Ops); 9462 } 9463 9464 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9465 EVT VT1, EVT VT2, EVT VT3, 9466 SDValue Op1, SDValue Op2) { 9467 SDVTList VTs = getVTList(VT1, VT2, VT3); 9468 SDValue Ops[] = { Op1, Op2 }; 9469 return getMachineNode(Opcode, dl, VTs, Ops); 9470 } 9471 9472 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9473 EVT VT1, EVT VT2, EVT VT3, 9474 SDValue Op1, SDValue Op2, 9475 SDValue Op3) { 9476 SDVTList VTs = getVTList(VT1, VT2, VT3); 9477 SDValue Ops[] = { Op1, Op2, Op3 }; 9478 return getMachineNode(Opcode, dl, VTs, Ops); 9479 } 9480 9481 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9482 EVT VT1, EVT VT2, EVT VT3, 9483 ArrayRef<SDValue> Ops) { 9484 SDVTList VTs = getVTList(VT1, VT2, VT3); 9485 return getMachineNode(Opcode, dl, VTs, Ops); 9486 } 9487 9488 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9489 ArrayRef<EVT> ResultTys, 9490 ArrayRef<SDValue> Ops) { 9491 SDVTList VTs = getVTList(ResultTys); 9492 return getMachineNode(Opcode, dl, VTs, Ops); 9493 } 9494 9495 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9496 SDVTList VTs, 9497 ArrayRef<SDValue> Ops) { 9498 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9499 MachineSDNode *N; 9500 void *IP = nullptr; 9501 9502 if (DoCSE) { 9503 FoldingSetNodeID ID; 9504 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9505 IP = nullptr; 9506 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9507 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9508 } 9509 } 9510 9511 // Allocate a new MachineSDNode. 9512 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9513 createOperands(N, Ops); 9514 9515 if (DoCSE) 9516 CSEMap.InsertNode(N, IP); 9517 9518 InsertNode(N); 9519 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9520 return N; 9521 } 9522 9523 /// getTargetExtractSubreg - A convenience function for creating 9524 /// TargetOpcode::EXTRACT_SUBREG nodes. 9525 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9526 SDValue Operand) { 9527 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9528 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9529 VT, Operand, SRIdxVal); 9530 return SDValue(Subreg, 0); 9531 } 9532 9533 /// getTargetInsertSubreg - A convenience function for creating 9534 /// TargetOpcode::INSERT_SUBREG nodes. 9535 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9536 SDValue Operand, SDValue Subreg) { 9537 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9538 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9539 VT, Operand, Subreg, SRIdxVal); 9540 return SDValue(Result, 0); 9541 } 9542 9543 /// getNodeIfExists - Get the specified node if it's already available, or 9544 /// else return NULL. 9545 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9546 ArrayRef<SDValue> Ops) { 9547 SDNodeFlags Flags; 9548 if (Inserter) 9549 Flags = Inserter->getFlags(); 9550 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9551 } 9552 9553 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9554 ArrayRef<SDValue> Ops, 9555 const SDNodeFlags Flags) { 9556 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9557 FoldingSetNodeID ID; 9558 AddNodeIDNode(ID, Opcode, VTList, Ops); 9559 void *IP = nullptr; 9560 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9561 E->intersectFlagsWith(Flags); 9562 return E; 9563 } 9564 } 9565 return nullptr; 9566 } 9567 9568 /// doesNodeExist - Check if a node exists without modifying its flags. 9569 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9570 ArrayRef<SDValue> Ops) { 9571 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9572 FoldingSetNodeID ID; 9573 AddNodeIDNode(ID, Opcode, VTList, Ops); 9574 void *IP = nullptr; 9575 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9576 return true; 9577 } 9578 return false; 9579 } 9580 9581 /// getDbgValue - Creates a SDDbgValue node. 9582 /// 9583 /// SDNode 9584 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9585 SDNode *N, unsigned R, bool IsIndirect, 9586 const DebugLoc &DL, unsigned O) { 9587 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9588 "Expected inlined-at fields to agree"); 9589 return new (DbgInfo->getAlloc()) 9590 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9591 {}, IsIndirect, DL, O, 9592 /*IsVariadic=*/false); 9593 } 9594 9595 /// Constant 9596 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9597 DIExpression *Expr, 9598 const Value *C, 9599 const DebugLoc &DL, unsigned O) { 9600 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9601 "Expected inlined-at fields to agree"); 9602 return new (DbgInfo->getAlloc()) 9603 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9604 /*IsIndirect=*/false, DL, O, 9605 /*IsVariadic=*/false); 9606 } 9607 9608 /// FrameIndex 9609 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9610 DIExpression *Expr, unsigned FI, 9611 bool IsIndirect, 9612 const DebugLoc &DL, 9613 unsigned O) { 9614 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9615 "Expected inlined-at fields to agree"); 9616 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9617 } 9618 9619 /// FrameIndex with dependencies 9620 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9621 DIExpression *Expr, unsigned FI, 9622 ArrayRef<SDNode *> Dependencies, 9623 bool IsIndirect, 9624 const DebugLoc &DL, 9625 unsigned O) { 9626 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9627 "Expected inlined-at fields to agree"); 9628 return new (DbgInfo->getAlloc()) 9629 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9630 Dependencies, IsIndirect, DL, O, 9631 /*IsVariadic=*/false); 9632 } 9633 9634 /// VReg 9635 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9636 unsigned VReg, bool IsIndirect, 9637 const DebugLoc &DL, unsigned O) { 9638 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9639 "Expected inlined-at fields to agree"); 9640 return new (DbgInfo->getAlloc()) 9641 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9642 {}, IsIndirect, DL, O, 9643 /*IsVariadic=*/false); 9644 } 9645 9646 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9647 ArrayRef<SDDbgOperand> Locs, 9648 ArrayRef<SDNode *> Dependencies, 9649 bool IsIndirect, const DebugLoc &DL, 9650 unsigned O, bool IsVariadic) { 9651 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9652 "Expected inlined-at fields to agree"); 9653 return new (DbgInfo->getAlloc()) 9654 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9655 DL, O, IsVariadic); 9656 } 9657 9658 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9659 unsigned OffsetInBits, unsigned SizeInBits, 9660 bool InvalidateDbg) { 9661 SDNode *FromNode = From.getNode(); 9662 SDNode *ToNode = To.getNode(); 9663 assert(FromNode && ToNode && "Can't modify dbg values"); 9664 9665 // PR35338 9666 // TODO: assert(From != To && "Redundant dbg value transfer"); 9667 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9668 if (From == To || FromNode == ToNode) 9669 return; 9670 9671 if (!FromNode->getHasDebugValue()) 9672 return; 9673 9674 SDDbgOperand FromLocOp = 9675 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9676 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9677 9678 SmallVector<SDDbgValue *, 2> ClonedDVs; 9679 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9680 if (Dbg->isInvalidated()) 9681 continue; 9682 9683 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9684 9685 // Create a new location ops vector that is equal to the old vector, but 9686 // with each instance of FromLocOp replaced with ToLocOp. 9687 bool Changed = false; 9688 auto NewLocOps = Dbg->copyLocationOps(); 9689 std::replace_if( 9690 NewLocOps.begin(), NewLocOps.end(), 9691 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9692 bool Match = Op == FromLocOp; 9693 Changed |= Match; 9694 return Match; 9695 }, 9696 ToLocOp); 9697 // Ignore this SDDbgValue if we didn't find a matching location. 9698 if (!Changed) 9699 continue; 9700 9701 DIVariable *Var = Dbg->getVariable(); 9702 auto *Expr = Dbg->getExpression(); 9703 // If a fragment is requested, update the expression. 9704 if (SizeInBits) { 9705 // When splitting a larger (e.g., sign-extended) value whose 9706 // lower bits are described with an SDDbgValue, do not attempt 9707 // to transfer the SDDbgValue to the upper bits. 9708 if (auto FI = Expr->getFragmentInfo()) 9709 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9710 continue; 9711 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9712 SizeInBits); 9713 if (!Fragment) 9714 continue; 9715 Expr = *Fragment; 9716 } 9717 9718 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9719 // Clone the SDDbgValue and move it to To. 9720 SDDbgValue *Clone = getDbgValueList( 9721 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9722 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9723 Dbg->isVariadic()); 9724 ClonedDVs.push_back(Clone); 9725 9726 if (InvalidateDbg) { 9727 // Invalidate value and indicate the SDDbgValue should not be emitted. 9728 Dbg->setIsInvalidated(); 9729 Dbg->setIsEmitted(); 9730 } 9731 } 9732 9733 for (SDDbgValue *Dbg : ClonedDVs) { 9734 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9735 "Transferred DbgValues should depend on the new SDNode"); 9736 AddDbgValue(Dbg, false); 9737 } 9738 } 9739 9740 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9741 if (!N.getHasDebugValue()) 9742 return; 9743 9744 SmallVector<SDDbgValue *, 2> ClonedDVs; 9745 for (auto DV : GetDbgValues(&N)) { 9746 if (DV->isInvalidated()) 9747 continue; 9748 switch (N.getOpcode()) { 9749 default: 9750 break; 9751 case ISD::ADD: 9752 SDValue N0 = N.getOperand(0); 9753 SDValue N1 = N.getOperand(1); 9754 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9755 isConstantIntBuildVectorOrConstantInt(N1)) { 9756 uint64_t Offset = N.getConstantOperandVal(1); 9757 9758 // Rewrite an ADD constant node into a DIExpression. Since we are 9759 // performing arithmetic to compute the variable's *value* in the 9760 // DIExpression, we need to mark the expression with a 9761 // DW_OP_stack_value. 9762 auto *DIExpr = DV->getExpression(); 9763 auto NewLocOps = DV->copyLocationOps(); 9764 bool Changed = false; 9765 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9766 // We're not given a ResNo to compare against because the whole 9767 // node is going away. We know that any ISD::ADD only has one 9768 // result, so we can assume any node match is using the result. 9769 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9770 NewLocOps[i].getSDNode() != &N) 9771 continue; 9772 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9773 SmallVector<uint64_t, 3> ExprOps; 9774 DIExpression::appendOffset(ExprOps, Offset); 9775 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9776 Changed = true; 9777 } 9778 (void)Changed; 9779 assert(Changed && "Salvage target doesn't use N"); 9780 9781 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9782 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9783 NewLocOps, AdditionalDependencies, 9784 DV->isIndirect(), DV->getDebugLoc(), 9785 DV->getOrder(), DV->isVariadic()); 9786 ClonedDVs.push_back(Clone); 9787 DV->setIsInvalidated(); 9788 DV->setIsEmitted(); 9789 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9790 N0.getNode()->dumprFull(this); 9791 dbgs() << " into " << *DIExpr << '\n'); 9792 } 9793 } 9794 } 9795 9796 for (SDDbgValue *Dbg : ClonedDVs) { 9797 assert(!Dbg->getSDNodes().empty() && 9798 "Salvaged DbgValue should depend on a new SDNode"); 9799 AddDbgValue(Dbg, false); 9800 } 9801 } 9802 9803 /// Creates a SDDbgLabel node. 9804 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9805 const DebugLoc &DL, unsigned O) { 9806 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9807 "Expected inlined-at fields to agree"); 9808 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9809 } 9810 9811 namespace { 9812 9813 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9814 /// pointed to by a use iterator is deleted, increment the use iterator 9815 /// so that it doesn't dangle. 9816 /// 9817 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9818 SDNode::use_iterator &UI; 9819 SDNode::use_iterator &UE; 9820 9821 void NodeDeleted(SDNode *N, SDNode *E) override { 9822 // Increment the iterator as needed. 9823 while (UI != UE && N == *UI) 9824 ++UI; 9825 } 9826 9827 public: 9828 RAUWUpdateListener(SelectionDAG &d, 9829 SDNode::use_iterator &ui, 9830 SDNode::use_iterator &ue) 9831 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9832 }; 9833 9834 } // end anonymous namespace 9835 9836 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9837 /// This can cause recursive merging of nodes in the DAG. 9838 /// 9839 /// This version assumes From has a single result value. 9840 /// 9841 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9842 SDNode *From = FromN.getNode(); 9843 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9844 "Cannot replace with this method!"); 9845 assert(From != To.getNode() && "Cannot replace uses of with self"); 9846 9847 // Preserve Debug Values 9848 transferDbgValues(FromN, To); 9849 9850 // Iterate over all the existing uses of From. New uses will be added 9851 // to the beginning of the use list, which we avoid visiting. 9852 // This specifically avoids visiting uses of From that arise while the 9853 // replacement is happening, because any such uses would be the result 9854 // of CSE: If an existing node looks like From after one of its operands 9855 // is replaced by To, we don't want to replace of all its users with To 9856 // too. See PR3018 for more info. 9857 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9858 RAUWUpdateListener Listener(*this, UI, UE); 9859 while (UI != UE) { 9860 SDNode *User = *UI; 9861 9862 // This node is about to morph, remove its old self from the CSE maps. 9863 RemoveNodeFromCSEMaps(User); 9864 9865 // A user can appear in a use list multiple times, and when this 9866 // happens the uses are usually next to each other in the list. 9867 // To help reduce the number of CSE recomputations, process all 9868 // the uses of this user that we can find this way. 9869 do { 9870 SDUse &Use = UI.getUse(); 9871 ++UI; 9872 Use.set(To); 9873 if (To->isDivergent() != From->isDivergent()) 9874 updateDivergence(User); 9875 } while (UI != UE && *UI == User); 9876 // Now that we have modified User, add it back to the CSE maps. If it 9877 // already exists there, recursively merge the results together. 9878 AddModifiedNodeToCSEMaps(User); 9879 } 9880 9881 // If we just RAUW'd the root, take note. 9882 if (FromN == getRoot()) 9883 setRoot(To); 9884 } 9885 9886 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9887 /// This can cause recursive merging of nodes in the DAG. 9888 /// 9889 /// This version assumes that for each value of From, there is a 9890 /// corresponding value in To in the same position with the same type. 9891 /// 9892 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9893 #ifndef NDEBUG 9894 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9895 assert((!From->hasAnyUseOfValue(i) || 9896 From->getValueType(i) == To->getValueType(i)) && 9897 "Cannot use this version of ReplaceAllUsesWith!"); 9898 #endif 9899 9900 // Handle the trivial case. 9901 if (From == To) 9902 return; 9903 9904 // Preserve Debug Info. Only do this if there's a use. 9905 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9906 if (From->hasAnyUseOfValue(i)) { 9907 assert((i < To->getNumValues()) && "Invalid To location"); 9908 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9909 } 9910 9911 // Iterate over just the existing users of From. See the comments in 9912 // the ReplaceAllUsesWith above. 9913 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9914 RAUWUpdateListener Listener(*this, UI, UE); 9915 while (UI != UE) { 9916 SDNode *User = *UI; 9917 9918 // This node is about to morph, remove its old self from the CSE maps. 9919 RemoveNodeFromCSEMaps(User); 9920 9921 // A user can appear in a use list multiple times, and when this 9922 // happens the uses are usually next to each other in the list. 9923 // To help reduce the number of CSE recomputations, process all 9924 // the uses of this user that we can find this way. 9925 do { 9926 SDUse &Use = UI.getUse(); 9927 ++UI; 9928 Use.setNode(To); 9929 if (To->isDivergent() != From->isDivergent()) 9930 updateDivergence(User); 9931 } while (UI != UE && *UI == User); 9932 9933 // Now that we have modified User, add it back to the CSE maps. If it 9934 // already exists there, recursively merge the results together. 9935 AddModifiedNodeToCSEMaps(User); 9936 } 9937 9938 // If we just RAUW'd the root, take note. 9939 if (From == getRoot().getNode()) 9940 setRoot(SDValue(To, getRoot().getResNo())); 9941 } 9942 9943 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9944 /// This can cause recursive merging of nodes in the DAG. 9945 /// 9946 /// This version can replace From with any result values. To must match the 9947 /// number and types of values returned by From. 9948 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9949 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9950 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9951 9952 // Preserve Debug Info. 9953 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9954 transferDbgValues(SDValue(From, i), To[i]); 9955 9956 // Iterate over just the existing users of From. See the comments in 9957 // the ReplaceAllUsesWith above. 9958 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9959 RAUWUpdateListener Listener(*this, UI, UE); 9960 while (UI != UE) { 9961 SDNode *User = *UI; 9962 9963 // This node is about to morph, remove its old self from the CSE maps. 9964 RemoveNodeFromCSEMaps(User); 9965 9966 // A user can appear in a use list multiple times, and when this happens the 9967 // uses are usually next to each other in the list. To help reduce the 9968 // number of CSE and divergence recomputations, process all the uses of this 9969 // user that we can find this way. 9970 bool To_IsDivergent = false; 9971 do { 9972 SDUse &Use = UI.getUse(); 9973 const SDValue &ToOp = To[Use.getResNo()]; 9974 ++UI; 9975 Use.set(ToOp); 9976 To_IsDivergent |= ToOp->isDivergent(); 9977 } while (UI != UE && *UI == User); 9978 9979 if (To_IsDivergent != From->isDivergent()) 9980 updateDivergence(User); 9981 9982 // Now that we have modified User, add it back to the CSE maps. If it 9983 // already exists there, recursively merge the results together. 9984 AddModifiedNodeToCSEMaps(User); 9985 } 9986 9987 // If we just RAUW'd the root, take note. 9988 if (From == getRoot().getNode()) 9989 setRoot(SDValue(To[getRoot().getResNo()])); 9990 } 9991 9992 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 9993 /// uses of other values produced by From.getNode() alone. The Deleted 9994 /// vector is handled the same way as for ReplaceAllUsesWith. 9995 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 9996 // Handle the really simple, really trivial case efficiently. 9997 if (From == To) return; 9998 9999 // Handle the simple, trivial, case efficiently. 10000 if (From.getNode()->getNumValues() == 1) { 10001 ReplaceAllUsesWith(From, To); 10002 return; 10003 } 10004 10005 // Preserve Debug Info. 10006 transferDbgValues(From, To); 10007 10008 // Iterate over just the existing users of From. See the comments in 10009 // the ReplaceAllUsesWith above. 10010 SDNode::use_iterator UI = From.getNode()->use_begin(), 10011 UE = From.getNode()->use_end(); 10012 RAUWUpdateListener Listener(*this, UI, UE); 10013 while (UI != UE) { 10014 SDNode *User = *UI; 10015 bool UserRemovedFromCSEMaps = false; 10016 10017 // A user can appear in a use list multiple times, and when this 10018 // happens the uses are usually next to each other in the list. 10019 // To help reduce the number of CSE recomputations, process all 10020 // the uses of this user that we can find this way. 10021 do { 10022 SDUse &Use = UI.getUse(); 10023 10024 // Skip uses of different values from the same node. 10025 if (Use.getResNo() != From.getResNo()) { 10026 ++UI; 10027 continue; 10028 } 10029 10030 // If this node hasn't been modified yet, it's still in the CSE maps, 10031 // so remove its old self from the CSE maps. 10032 if (!UserRemovedFromCSEMaps) { 10033 RemoveNodeFromCSEMaps(User); 10034 UserRemovedFromCSEMaps = true; 10035 } 10036 10037 ++UI; 10038 Use.set(To); 10039 if (To->isDivergent() != From->isDivergent()) 10040 updateDivergence(User); 10041 } while (UI != UE && *UI == User); 10042 // We are iterating over all uses of the From node, so if a use 10043 // doesn't use the specific value, no changes are made. 10044 if (!UserRemovedFromCSEMaps) 10045 continue; 10046 10047 // Now that we have modified User, add it back to the CSE maps. If it 10048 // already exists there, recursively merge the results together. 10049 AddModifiedNodeToCSEMaps(User); 10050 } 10051 10052 // If we just RAUW'd the root, take note. 10053 if (From == getRoot()) 10054 setRoot(To); 10055 } 10056 10057 namespace { 10058 10059 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10060 /// to record information about a use. 10061 struct UseMemo { 10062 SDNode *User; 10063 unsigned Index; 10064 SDUse *Use; 10065 }; 10066 10067 /// operator< - Sort Memos by User. 10068 bool operator<(const UseMemo &L, const UseMemo &R) { 10069 return (intptr_t)L.User < (intptr_t)R.User; 10070 } 10071 10072 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10073 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10074 /// the node already has been taken care of recursively. 10075 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10076 SmallVector<UseMemo, 4> &Uses; 10077 10078 void NodeDeleted(SDNode *N, SDNode *E) override { 10079 for (UseMemo &Memo : Uses) 10080 if (Memo.User == N) 10081 Memo.User = nullptr; 10082 } 10083 10084 public: 10085 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10086 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10087 }; 10088 10089 } // end anonymous namespace 10090 10091 bool SelectionDAG::calculateDivergence(SDNode *N) { 10092 if (TLI->isSDNodeAlwaysUniform(N)) { 10093 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 10094 "Conflicting divergence information!"); 10095 return false; 10096 } 10097 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 10098 return true; 10099 for (auto &Op : N->ops()) { 10100 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10101 return true; 10102 } 10103 return false; 10104 } 10105 10106 void SelectionDAG::updateDivergence(SDNode *N) { 10107 SmallVector<SDNode *, 16> Worklist(1, N); 10108 do { 10109 N = Worklist.pop_back_val(); 10110 bool IsDivergent = calculateDivergence(N); 10111 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10112 N->SDNodeBits.IsDivergent = IsDivergent; 10113 llvm::append_range(Worklist, N->uses()); 10114 } 10115 } while (!Worklist.empty()); 10116 } 10117 10118 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10119 DenseMap<SDNode *, unsigned> Degree; 10120 Order.reserve(AllNodes.size()); 10121 for (auto &N : allnodes()) { 10122 unsigned NOps = N.getNumOperands(); 10123 Degree[&N] = NOps; 10124 if (0 == NOps) 10125 Order.push_back(&N); 10126 } 10127 for (size_t I = 0; I != Order.size(); ++I) { 10128 SDNode *N = Order[I]; 10129 for (auto U : N->uses()) { 10130 unsigned &UnsortedOps = Degree[U]; 10131 if (0 == --UnsortedOps) 10132 Order.push_back(U); 10133 } 10134 } 10135 } 10136 10137 #ifndef NDEBUG 10138 void SelectionDAG::VerifyDAGDivergence() { 10139 std::vector<SDNode *> TopoOrder; 10140 CreateTopologicalOrder(TopoOrder); 10141 for (auto *N : TopoOrder) { 10142 assert(calculateDivergence(N) == N->isDivergent() && 10143 "Divergence bit inconsistency detected"); 10144 } 10145 } 10146 #endif 10147 10148 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10149 /// uses of other values produced by From.getNode() alone. The same value 10150 /// may appear in both the From and To list. The Deleted vector is 10151 /// handled the same way as for ReplaceAllUsesWith. 10152 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10153 const SDValue *To, 10154 unsigned Num){ 10155 // Handle the simple, trivial case efficiently. 10156 if (Num == 1) 10157 return ReplaceAllUsesOfValueWith(*From, *To); 10158 10159 transferDbgValues(*From, *To); 10160 10161 // Read up all the uses and make records of them. This helps 10162 // processing new uses that are introduced during the 10163 // replacement process. 10164 SmallVector<UseMemo, 4> Uses; 10165 for (unsigned i = 0; i != Num; ++i) { 10166 unsigned FromResNo = From[i].getResNo(); 10167 SDNode *FromNode = From[i].getNode(); 10168 for (SDNode::use_iterator UI = FromNode->use_begin(), 10169 E = FromNode->use_end(); UI != E; ++UI) { 10170 SDUse &Use = UI.getUse(); 10171 if (Use.getResNo() == FromResNo) { 10172 UseMemo Memo = { *UI, i, &Use }; 10173 Uses.push_back(Memo); 10174 } 10175 } 10176 } 10177 10178 // Sort the uses, so that all the uses from a given User are together. 10179 llvm::sort(Uses); 10180 RAUOVWUpdateListener Listener(*this, Uses); 10181 10182 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 10183 UseIndex != UseIndexEnd; ) { 10184 // We know that this user uses some value of From. If it is the right 10185 // value, update it. 10186 SDNode *User = Uses[UseIndex].User; 10187 // If the node has been deleted by recursive CSE updates when updating 10188 // another node, then just skip this entry. 10189 if (User == nullptr) { 10190 ++UseIndex; 10191 continue; 10192 } 10193 10194 // This node is about to morph, remove its old self from the CSE maps. 10195 RemoveNodeFromCSEMaps(User); 10196 10197 // The Uses array is sorted, so all the uses for a given User 10198 // are next to each other in the list. 10199 // To help reduce the number of CSE recomputations, process all 10200 // the uses of this user that we can find this way. 10201 do { 10202 unsigned i = Uses[UseIndex].Index; 10203 SDUse &Use = *Uses[UseIndex].Use; 10204 ++UseIndex; 10205 10206 Use.set(To[i]); 10207 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 10208 10209 // Now that we have modified User, add it back to the CSE maps. If it 10210 // already exists there, recursively merge the results together. 10211 AddModifiedNodeToCSEMaps(User); 10212 } 10213 } 10214 10215 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 10216 /// based on their topological order. It returns the maximum id and a vector 10217 /// of the SDNodes* in assigned order by reference. 10218 unsigned SelectionDAG::AssignTopologicalOrder() { 10219 unsigned DAGSize = 0; 10220 10221 // SortedPos tracks the progress of the algorithm. Nodes before it are 10222 // sorted, nodes after it are unsorted. When the algorithm completes 10223 // it is at the end of the list. 10224 allnodes_iterator SortedPos = allnodes_begin(); 10225 10226 // Visit all the nodes. Move nodes with no operands to the front of 10227 // the list immediately. Annotate nodes that do have operands with their 10228 // operand count. Before we do this, the Node Id fields of the nodes 10229 // may contain arbitrary values. After, the Node Id fields for nodes 10230 // before SortedPos will contain the topological sort index, and the 10231 // Node Id fields for nodes At SortedPos and after will contain the 10232 // count of outstanding operands. 10233 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 10234 checkForCycles(&N, this); 10235 unsigned Degree = N.getNumOperands(); 10236 if (Degree == 0) { 10237 // A node with no uses, add it to the result array immediately. 10238 N.setNodeId(DAGSize++); 10239 allnodes_iterator Q(&N); 10240 if (Q != SortedPos) 10241 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 10242 assert(SortedPos != AllNodes.end() && "Overran node list"); 10243 ++SortedPos; 10244 } else { 10245 // Temporarily use the Node Id as scratch space for the degree count. 10246 N.setNodeId(Degree); 10247 } 10248 } 10249 10250 // Visit all the nodes. As we iterate, move nodes into sorted order, 10251 // such that by the time the end is reached all nodes will be sorted. 10252 for (SDNode &Node : allnodes()) { 10253 SDNode *N = &Node; 10254 checkForCycles(N, this); 10255 // N is in sorted position, so all its uses have one less operand 10256 // that needs to be sorted. 10257 for (SDNode *P : N->uses()) { 10258 unsigned Degree = P->getNodeId(); 10259 assert(Degree != 0 && "Invalid node degree"); 10260 --Degree; 10261 if (Degree == 0) { 10262 // All of P's operands are sorted, so P may sorted now. 10263 P->setNodeId(DAGSize++); 10264 if (P->getIterator() != SortedPos) 10265 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 10266 assert(SortedPos != AllNodes.end() && "Overran node list"); 10267 ++SortedPos; 10268 } else { 10269 // Update P's outstanding operand count. 10270 P->setNodeId(Degree); 10271 } 10272 } 10273 if (Node.getIterator() == SortedPos) { 10274 #ifndef NDEBUG 10275 allnodes_iterator I(N); 10276 SDNode *S = &*++I; 10277 dbgs() << "Overran sorted position:\n"; 10278 S->dumprFull(this); dbgs() << "\n"; 10279 dbgs() << "Checking if this is due to cycles\n"; 10280 checkForCycles(this, true); 10281 #endif 10282 llvm_unreachable(nullptr); 10283 } 10284 } 10285 10286 assert(SortedPos == AllNodes.end() && 10287 "Topological sort incomplete!"); 10288 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 10289 "First node in topological sort is not the entry token!"); 10290 assert(AllNodes.front().getNodeId() == 0 && 10291 "First node in topological sort has non-zero id!"); 10292 assert(AllNodes.front().getNumOperands() == 0 && 10293 "First node in topological sort has operands!"); 10294 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 10295 "Last node in topologic sort has unexpected id!"); 10296 assert(AllNodes.back().use_empty() && 10297 "Last node in topologic sort has users!"); 10298 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 10299 return DAGSize; 10300 } 10301 10302 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 10303 /// value is produced by SD. 10304 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 10305 for (SDNode *SD : DB->getSDNodes()) { 10306 if (!SD) 10307 continue; 10308 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 10309 SD->setHasDebugValue(true); 10310 } 10311 DbgInfo->add(DB, isParameter); 10312 } 10313 10314 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 10315 10316 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 10317 SDValue NewMemOpChain) { 10318 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 10319 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 10320 // The new memory operation must have the same position as the old load in 10321 // terms of memory dependency. Create a TokenFactor for the old load and new 10322 // memory operation and update uses of the old load's output chain to use that 10323 // TokenFactor. 10324 if (OldChain == NewMemOpChain || OldChain.use_empty()) 10325 return NewMemOpChain; 10326 10327 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 10328 OldChain, NewMemOpChain); 10329 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 10330 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 10331 return TokenFactor; 10332 } 10333 10334 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 10335 SDValue NewMemOp) { 10336 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 10337 SDValue OldChain = SDValue(OldLoad, 1); 10338 SDValue NewMemOpChain = NewMemOp.getValue(1); 10339 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 10340 } 10341 10342 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 10343 Function **OutFunction) { 10344 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 10345 10346 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 10347 auto *Module = MF->getFunction().getParent(); 10348 auto *Function = Module->getFunction(Symbol); 10349 10350 if (OutFunction != nullptr) 10351 *OutFunction = Function; 10352 10353 if (Function != nullptr) { 10354 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 10355 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 10356 } 10357 10358 std::string ErrorStr; 10359 raw_string_ostream ErrorFormatter(ErrorStr); 10360 ErrorFormatter << "Undefined external symbol "; 10361 ErrorFormatter << '"' << Symbol << '"'; 10362 report_fatal_error(Twine(ErrorFormatter.str())); 10363 } 10364 10365 //===----------------------------------------------------------------------===// 10366 // SDNode Class 10367 //===----------------------------------------------------------------------===// 10368 10369 bool llvm::isNullConstant(SDValue V) { 10370 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10371 return Const != nullptr && Const->isZero(); 10372 } 10373 10374 bool llvm::isNullFPConstant(SDValue V) { 10375 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10376 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10377 } 10378 10379 bool llvm::isAllOnesConstant(SDValue V) { 10380 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10381 return Const != nullptr && Const->isAllOnes(); 10382 } 10383 10384 bool llvm::isOneConstant(SDValue V) { 10385 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10386 return Const != nullptr && Const->isOne(); 10387 } 10388 10389 SDValue llvm::peekThroughBitcasts(SDValue V) { 10390 while (V.getOpcode() == ISD::BITCAST) 10391 V = V.getOperand(0); 10392 return V; 10393 } 10394 10395 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10396 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10397 V = V.getOperand(0); 10398 return V; 10399 } 10400 10401 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10402 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10403 V = V.getOperand(0); 10404 return V; 10405 } 10406 10407 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10408 if (V.getOpcode() != ISD::XOR) 10409 return false; 10410 V = peekThroughBitcasts(V.getOperand(1)); 10411 unsigned NumBits = V.getScalarValueSizeInBits(); 10412 ConstantSDNode *C = 10413 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10414 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10415 } 10416 10417 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10418 bool AllowTruncation) { 10419 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10420 return CN; 10421 10422 // SplatVectors can truncate their operands. Ignore that case here unless 10423 // AllowTruncation is set. 10424 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10425 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10426 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10427 EVT CVT = CN->getValueType(0); 10428 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10429 if (AllowTruncation || CVT == VecEltVT) 10430 return CN; 10431 } 10432 } 10433 10434 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10435 BitVector UndefElements; 10436 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10437 10438 // BuildVectors can truncate their operands. Ignore that case here unless 10439 // AllowTruncation is set. 10440 if (CN && (UndefElements.none() || AllowUndefs)) { 10441 EVT CVT = CN->getValueType(0); 10442 EVT NSVT = N.getValueType().getScalarType(); 10443 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10444 if (AllowTruncation || (CVT == NSVT)) 10445 return CN; 10446 } 10447 } 10448 10449 return nullptr; 10450 } 10451 10452 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10453 bool AllowUndefs, 10454 bool AllowTruncation) { 10455 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10456 return CN; 10457 10458 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10459 BitVector UndefElements; 10460 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10461 10462 // BuildVectors can truncate their operands. Ignore that case here unless 10463 // AllowTruncation is set. 10464 if (CN && (UndefElements.none() || AllowUndefs)) { 10465 EVT CVT = CN->getValueType(0); 10466 EVT NSVT = N.getValueType().getScalarType(); 10467 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10468 if (AllowTruncation || (CVT == NSVT)) 10469 return CN; 10470 } 10471 } 10472 10473 return nullptr; 10474 } 10475 10476 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10477 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10478 return CN; 10479 10480 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10481 BitVector UndefElements; 10482 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10483 if (CN && (UndefElements.none() || AllowUndefs)) 10484 return CN; 10485 } 10486 10487 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10488 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10489 return CN; 10490 10491 return nullptr; 10492 } 10493 10494 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10495 const APInt &DemandedElts, 10496 bool AllowUndefs) { 10497 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10498 return CN; 10499 10500 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10501 BitVector UndefElements; 10502 ConstantFPSDNode *CN = 10503 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10504 if (CN && (UndefElements.none() || AllowUndefs)) 10505 return CN; 10506 } 10507 10508 return nullptr; 10509 } 10510 10511 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10512 // TODO: may want to use peekThroughBitcast() here. 10513 ConstantSDNode *C = 10514 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10515 return C && C->isZero(); 10516 } 10517 10518 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10519 // TODO: may want to use peekThroughBitcast() here. 10520 unsigned BitWidth = N.getScalarValueSizeInBits(); 10521 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10522 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10523 } 10524 10525 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10526 N = peekThroughBitcasts(N); 10527 unsigned BitWidth = N.getScalarValueSizeInBits(); 10528 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10529 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10530 } 10531 10532 HandleSDNode::~HandleSDNode() { 10533 DropOperands(); 10534 } 10535 10536 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10537 const DebugLoc &DL, 10538 const GlobalValue *GA, EVT VT, 10539 int64_t o, unsigned TF) 10540 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10541 TheGlobal = GA; 10542 } 10543 10544 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10545 EVT VT, unsigned SrcAS, 10546 unsigned DestAS) 10547 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10548 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10549 10550 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10551 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10552 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10553 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10554 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10555 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10556 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10557 10558 // We check here that the size of the memory operand fits within the size of 10559 // the MMO. This is because the MMO might indicate only a possible address 10560 // range instead of specifying the affected memory addresses precisely. 10561 // TODO: Make MachineMemOperands aware of scalable vectors. 10562 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10563 "Size mismatch!"); 10564 } 10565 10566 /// Profile - Gather unique data for the node. 10567 /// 10568 void SDNode::Profile(FoldingSetNodeID &ID) const { 10569 AddNodeIDNode(ID, this); 10570 } 10571 10572 namespace { 10573 10574 struct EVTArray { 10575 std::vector<EVT> VTs; 10576 10577 EVTArray() { 10578 VTs.reserve(MVT::VALUETYPE_SIZE); 10579 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10580 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10581 } 10582 }; 10583 10584 } // end anonymous namespace 10585 10586 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10587 static ManagedStatic<EVTArray> SimpleVTArray; 10588 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10589 10590 /// getValueTypeList - Return a pointer to the specified value type. 10591 /// 10592 const EVT *SDNode::getValueTypeList(EVT VT) { 10593 if (VT.isExtended()) { 10594 sys::SmartScopedLock<true> Lock(*VTMutex); 10595 return &(*EVTs->insert(VT).first); 10596 } 10597 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10598 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10599 } 10600 10601 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10602 /// indicated value. This method ignores uses of other values defined by this 10603 /// operation. 10604 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10605 assert(Value < getNumValues() && "Bad value!"); 10606 10607 // TODO: Only iterate over uses of a given value of the node 10608 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10609 if (UI.getUse().getResNo() == Value) { 10610 if (NUses == 0) 10611 return false; 10612 --NUses; 10613 } 10614 } 10615 10616 // Found exactly the right number of uses? 10617 return NUses == 0; 10618 } 10619 10620 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10621 /// value. This method ignores uses of other values defined by this operation. 10622 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10623 assert(Value < getNumValues() && "Bad value!"); 10624 10625 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10626 if (UI.getUse().getResNo() == Value) 10627 return true; 10628 10629 return false; 10630 } 10631 10632 /// isOnlyUserOf - Return true if this node is the only use of N. 10633 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10634 bool Seen = false; 10635 for (const SDNode *User : N->uses()) { 10636 if (User == this) 10637 Seen = true; 10638 else 10639 return false; 10640 } 10641 10642 return Seen; 10643 } 10644 10645 /// Return true if the only users of N are contained in Nodes. 10646 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10647 bool Seen = false; 10648 for (const SDNode *User : N->uses()) { 10649 if (llvm::is_contained(Nodes, User)) 10650 Seen = true; 10651 else 10652 return false; 10653 } 10654 10655 return Seen; 10656 } 10657 10658 /// isOperand - Return true if this node is an operand of N. 10659 bool SDValue::isOperandOf(const SDNode *N) const { 10660 return is_contained(N->op_values(), *this); 10661 } 10662 10663 bool SDNode::isOperandOf(const SDNode *N) const { 10664 return any_of(N->op_values(), 10665 [this](SDValue Op) { return this == Op.getNode(); }); 10666 } 10667 10668 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10669 /// be a chain) reaches the specified operand without crossing any 10670 /// side-effecting instructions on any chain path. In practice, this looks 10671 /// through token factors and non-volatile loads. In order to remain efficient, 10672 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10673 /// 10674 /// Note that we only need to examine chains when we're searching for 10675 /// side-effects; SelectionDAG requires that all side-effects are represented 10676 /// by chains, even if another operand would force a specific ordering. This 10677 /// constraint is necessary to allow transformations like splitting loads. 10678 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10679 unsigned Depth) const { 10680 if (*this == Dest) return true; 10681 10682 // Don't search too deeply, we just want to be able to see through 10683 // TokenFactor's etc. 10684 if (Depth == 0) return false; 10685 10686 // If this is a token factor, all inputs to the TF happen in parallel. 10687 if (getOpcode() == ISD::TokenFactor) { 10688 // First, try a shallow search. 10689 if (is_contained((*this)->ops(), Dest)) { 10690 // We found the chain we want as an operand of this TokenFactor. 10691 // Essentially, we reach the chain without side-effects if we could 10692 // serialize the TokenFactor into a simple chain of operations with 10693 // Dest as the last operation. This is automatically true if the 10694 // chain has one use: there are no other ordering constraints. 10695 // If the chain has more than one use, we give up: some other 10696 // use of Dest might force a side-effect between Dest and the current 10697 // node. 10698 if (Dest.hasOneUse()) 10699 return true; 10700 } 10701 // Next, try a deep search: check whether every operand of the TokenFactor 10702 // reaches Dest. 10703 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10704 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10705 }); 10706 } 10707 10708 // Loads don't have side effects, look through them. 10709 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10710 if (Ld->isUnordered()) 10711 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10712 } 10713 return false; 10714 } 10715 10716 bool SDNode::hasPredecessor(const SDNode *N) const { 10717 SmallPtrSet<const SDNode *, 32> Visited; 10718 SmallVector<const SDNode *, 16> Worklist; 10719 Worklist.push_back(this); 10720 return hasPredecessorHelper(N, Visited, Worklist); 10721 } 10722 10723 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10724 this->Flags.intersectWith(Flags); 10725 } 10726 10727 SDValue 10728 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10729 ArrayRef<ISD::NodeType> CandidateBinOps, 10730 bool AllowPartials) { 10731 // The pattern must end in an extract from index 0. 10732 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10733 !isNullConstant(Extract->getOperand(1))) 10734 return SDValue(); 10735 10736 // Match against one of the candidate binary ops. 10737 SDValue Op = Extract->getOperand(0); 10738 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10739 return Op.getOpcode() == unsigned(BinOp); 10740 })) 10741 return SDValue(); 10742 10743 // Floating-point reductions may require relaxed constraints on the final step 10744 // of the reduction because they may reorder intermediate operations. 10745 unsigned CandidateBinOp = Op.getOpcode(); 10746 if (Op.getValueType().isFloatingPoint()) { 10747 SDNodeFlags Flags = Op->getFlags(); 10748 switch (CandidateBinOp) { 10749 case ISD::FADD: 10750 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10751 return SDValue(); 10752 break; 10753 default: 10754 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10755 } 10756 } 10757 10758 // Matching failed - attempt to see if we did enough stages that a partial 10759 // reduction from a subvector is possible. 10760 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10761 if (!AllowPartials || !Op) 10762 return SDValue(); 10763 EVT OpVT = Op.getValueType(); 10764 EVT OpSVT = OpVT.getScalarType(); 10765 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10766 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10767 return SDValue(); 10768 BinOp = (ISD::NodeType)CandidateBinOp; 10769 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10770 getVectorIdxConstant(0, SDLoc(Op))); 10771 }; 10772 10773 // At each stage, we're looking for something that looks like: 10774 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10775 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10776 // i32 undef, i32 undef, i32 undef, i32 undef> 10777 // %a = binop <8 x i32> %op, %s 10778 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10779 // we expect something like: 10780 // <4,5,6,7,u,u,u,u> 10781 // <2,3,u,u,u,u,u,u> 10782 // <1,u,u,u,u,u,u,u> 10783 // While a partial reduction match would be: 10784 // <2,3,u,u,u,u,u,u> 10785 // <1,u,u,u,u,u,u,u> 10786 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10787 SDValue PrevOp; 10788 for (unsigned i = 0; i < Stages; ++i) { 10789 unsigned MaskEnd = (1 << i); 10790 10791 if (Op.getOpcode() != CandidateBinOp) 10792 return PartialReduction(PrevOp, MaskEnd); 10793 10794 SDValue Op0 = Op.getOperand(0); 10795 SDValue Op1 = Op.getOperand(1); 10796 10797 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10798 if (Shuffle) { 10799 Op = Op1; 10800 } else { 10801 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10802 Op = Op0; 10803 } 10804 10805 // The first operand of the shuffle should be the same as the other operand 10806 // of the binop. 10807 if (!Shuffle || Shuffle->getOperand(0) != Op) 10808 return PartialReduction(PrevOp, MaskEnd); 10809 10810 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10811 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10812 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10813 return PartialReduction(PrevOp, MaskEnd); 10814 10815 PrevOp = Op; 10816 } 10817 10818 // Handle subvector reductions, which tend to appear after the shuffle 10819 // reduction stages. 10820 while (Op.getOpcode() == CandidateBinOp) { 10821 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10822 SDValue Op0 = Op.getOperand(0); 10823 SDValue Op1 = Op.getOperand(1); 10824 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10825 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10826 Op0.getOperand(0) != Op1.getOperand(0)) 10827 break; 10828 SDValue Src = Op0.getOperand(0); 10829 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10830 if (NumSrcElts != (2 * NumElts)) 10831 break; 10832 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10833 Op1.getConstantOperandAPInt(1) == NumElts) && 10834 !(Op1.getConstantOperandAPInt(1) == 0 && 10835 Op0.getConstantOperandAPInt(1) == NumElts)) 10836 break; 10837 Op = Src; 10838 } 10839 10840 BinOp = (ISD::NodeType)CandidateBinOp; 10841 return Op; 10842 } 10843 10844 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10845 assert(N->getNumValues() == 1 && 10846 "Can't unroll a vector with multiple results!"); 10847 10848 EVT VT = N->getValueType(0); 10849 unsigned NE = VT.getVectorNumElements(); 10850 EVT EltVT = VT.getVectorElementType(); 10851 SDLoc dl(N); 10852 10853 SmallVector<SDValue, 8> Scalars; 10854 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10855 10856 // If ResNE is 0, fully unroll the vector op. 10857 if (ResNE == 0) 10858 ResNE = NE; 10859 else if (NE > ResNE) 10860 NE = ResNE; 10861 10862 unsigned i; 10863 for (i= 0; i != NE; ++i) { 10864 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10865 SDValue Operand = N->getOperand(j); 10866 EVT OperandVT = Operand.getValueType(); 10867 if (OperandVT.isVector()) { 10868 // A vector operand; extract a single element. 10869 EVT OperandEltVT = OperandVT.getVectorElementType(); 10870 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10871 Operand, getVectorIdxConstant(i, dl)); 10872 } else { 10873 // A scalar operand; just use it as is. 10874 Operands[j] = Operand; 10875 } 10876 } 10877 10878 switch (N->getOpcode()) { 10879 default: { 10880 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10881 N->getFlags())); 10882 break; 10883 } 10884 case ISD::VSELECT: 10885 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10886 break; 10887 case ISD::SHL: 10888 case ISD::SRA: 10889 case ISD::SRL: 10890 case ISD::ROTL: 10891 case ISD::ROTR: 10892 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10893 getShiftAmountOperand(Operands[0].getValueType(), 10894 Operands[1]))); 10895 break; 10896 case ISD::SIGN_EXTEND_INREG: { 10897 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10898 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10899 Operands[0], 10900 getValueType(ExtVT))); 10901 } 10902 } 10903 } 10904 10905 for (; i < ResNE; ++i) 10906 Scalars.push_back(getUNDEF(EltVT)); 10907 10908 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10909 return getBuildVector(VecVT, dl, Scalars); 10910 } 10911 10912 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10913 SDNode *N, unsigned ResNE) { 10914 unsigned Opcode = N->getOpcode(); 10915 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10916 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10917 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10918 "Expected an overflow opcode"); 10919 10920 EVT ResVT = N->getValueType(0); 10921 EVT OvVT = N->getValueType(1); 10922 EVT ResEltVT = ResVT.getVectorElementType(); 10923 EVT OvEltVT = OvVT.getVectorElementType(); 10924 SDLoc dl(N); 10925 10926 // If ResNE is 0, fully unroll the vector op. 10927 unsigned NE = ResVT.getVectorNumElements(); 10928 if (ResNE == 0) 10929 ResNE = NE; 10930 else if (NE > ResNE) 10931 NE = ResNE; 10932 10933 SmallVector<SDValue, 8> LHSScalars; 10934 SmallVector<SDValue, 8> RHSScalars; 10935 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10936 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10937 10938 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10939 SDVTList VTs = getVTList(ResEltVT, SVT); 10940 SmallVector<SDValue, 8> ResScalars; 10941 SmallVector<SDValue, 8> OvScalars; 10942 for (unsigned i = 0; i < NE; ++i) { 10943 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10944 SDValue Ov = 10945 getSelect(dl, OvEltVT, Res.getValue(1), 10946 getBoolConstant(true, dl, OvEltVT, ResVT), 10947 getConstant(0, dl, OvEltVT)); 10948 10949 ResScalars.push_back(Res); 10950 OvScalars.push_back(Ov); 10951 } 10952 10953 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10954 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10955 10956 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10957 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10958 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10959 getBuildVector(NewOvVT, dl, OvScalars)); 10960 } 10961 10962 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10963 LoadSDNode *Base, 10964 unsigned Bytes, 10965 int Dist) const { 10966 if (LD->isVolatile() || Base->isVolatile()) 10967 return false; 10968 // TODO: probably too restrictive for atomics, revisit 10969 if (!LD->isSimple()) 10970 return false; 10971 if (LD->isIndexed() || Base->isIndexed()) 10972 return false; 10973 if (LD->getChain() != Base->getChain()) 10974 return false; 10975 EVT VT = LD->getValueType(0); 10976 if (VT.getSizeInBits() / 8 != Bytes) 10977 return false; 10978 10979 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10980 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10981 10982 int64_t Offset = 0; 10983 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 10984 return (Dist * Bytes == Offset); 10985 return false; 10986 } 10987 10988 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 10989 /// if it cannot be inferred. 10990 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 10991 // If this is a GlobalAddress + cst, return the alignment. 10992 const GlobalValue *GV = nullptr; 10993 int64_t GVOffset = 0; 10994 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 10995 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 10996 KnownBits Known(PtrWidth); 10997 llvm::computeKnownBits(GV, Known, getDataLayout()); 10998 unsigned AlignBits = Known.countMinTrailingZeros(); 10999 if (AlignBits) 11000 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11001 } 11002 11003 // If this is a direct reference to a stack slot, use information about the 11004 // stack slot's alignment. 11005 int FrameIdx = INT_MIN; 11006 int64_t FrameOffset = 0; 11007 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11008 FrameIdx = FI->getIndex(); 11009 } else if (isBaseWithConstantOffset(Ptr) && 11010 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11011 // Handle FI+Cst 11012 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11013 FrameOffset = Ptr.getConstantOperandVal(1); 11014 } 11015 11016 if (FrameIdx != INT_MIN) { 11017 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11018 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11019 } 11020 11021 return None; 11022 } 11023 11024 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11025 /// which is split (or expanded) into two not necessarily identical pieces. 11026 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11027 // Currently all types are split in half. 11028 EVT LoVT, HiVT; 11029 if (!VT.isVector()) 11030 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11031 else 11032 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11033 11034 return std::make_pair(LoVT, HiVT); 11035 } 11036 11037 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11038 /// type, dependent on an enveloping VT that has been split into two identical 11039 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11040 std::pair<EVT, EVT> 11041 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11042 bool *HiIsEmpty) const { 11043 EVT EltTp = VT.getVectorElementType(); 11044 // Examples: 11045 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11046 // custom VL=9 with enveloping VL=8/8 yields 8/1 11047 // custom VL=10 with enveloping VL=8/8 yields 8/2 11048 // etc. 11049 ElementCount VTNumElts = VT.getVectorElementCount(); 11050 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11051 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11052 "Mixing fixed width and scalable vectors when enveloping a type"); 11053 EVT LoVT, HiVT; 11054 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11055 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11056 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11057 *HiIsEmpty = false; 11058 } else { 11059 // Flag that hi type has zero storage size, but return split envelop type 11060 // (this would be easier if vector types with zero elements were allowed). 11061 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11062 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11063 *HiIsEmpty = true; 11064 } 11065 return std::make_pair(LoVT, HiVT); 11066 } 11067 11068 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11069 /// low/high part. 11070 std::pair<SDValue, SDValue> 11071 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11072 const EVT &HiVT) { 11073 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 11074 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 11075 "Splitting vector with an invalid mixture of fixed and scalable " 11076 "vector types"); 11077 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 11078 N.getValueType().getVectorMinNumElements() && 11079 "More vector elements requested than available!"); 11080 SDValue Lo, Hi; 11081 Lo = 11082 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 11083 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 11084 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 11085 // IDX with the runtime scaling factor of the result vector type. For 11086 // fixed-width result vectors, that runtime scaling factor is 1. 11087 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 11088 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 11089 return std::make_pair(Lo, Hi); 11090 } 11091 11092 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 11093 const SDLoc &DL) { 11094 // Split the vector length parameter. 11095 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 11096 EVT VT = N.getValueType(); 11097 assert(VecVT.getVectorElementCount().isKnownEven() && 11098 "Expecting the mask to be an evenly-sized vector"); 11099 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 11100 SDValue HalfNumElts = 11101 VecVT.isFixedLengthVector() 11102 ? getConstant(HalfMinNumElts, DL, VT) 11103 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 11104 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 11105 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 11106 return std::make_pair(Lo, Hi); 11107 } 11108 11109 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 11110 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 11111 EVT VT = N.getValueType(); 11112 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 11113 NextPowerOf2(VT.getVectorNumElements())); 11114 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 11115 getVectorIdxConstant(0, DL)); 11116 } 11117 11118 void SelectionDAG::ExtractVectorElements(SDValue Op, 11119 SmallVectorImpl<SDValue> &Args, 11120 unsigned Start, unsigned Count, 11121 EVT EltVT) { 11122 EVT VT = Op.getValueType(); 11123 if (Count == 0) 11124 Count = VT.getVectorNumElements(); 11125 if (EltVT == EVT()) 11126 EltVT = VT.getVectorElementType(); 11127 SDLoc SL(Op); 11128 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 11129 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 11130 getVectorIdxConstant(i, SL))); 11131 } 11132 } 11133 11134 // getAddressSpace - Return the address space this GlobalAddress belongs to. 11135 unsigned GlobalAddressSDNode::getAddressSpace() const { 11136 return getGlobal()->getType()->getAddressSpace(); 11137 } 11138 11139 Type *ConstantPoolSDNode::getType() const { 11140 if (isMachineConstantPoolEntry()) 11141 return Val.MachineCPVal->getType(); 11142 return Val.ConstVal->getType(); 11143 } 11144 11145 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 11146 unsigned &SplatBitSize, 11147 bool &HasAnyUndefs, 11148 unsigned MinSplatBits, 11149 bool IsBigEndian) const { 11150 EVT VT = getValueType(0); 11151 assert(VT.isVector() && "Expected a vector type"); 11152 unsigned VecWidth = VT.getSizeInBits(); 11153 if (MinSplatBits > VecWidth) 11154 return false; 11155 11156 // FIXME: The widths are based on this node's type, but build vectors can 11157 // truncate their operands. 11158 SplatValue = APInt(VecWidth, 0); 11159 SplatUndef = APInt(VecWidth, 0); 11160 11161 // Get the bits. Bits with undefined values (when the corresponding element 11162 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 11163 // in SplatValue. If any of the values are not constant, give up and return 11164 // false. 11165 unsigned int NumOps = getNumOperands(); 11166 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 11167 unsigned EltWidth = VT.getScalarSizeInBits(); 11168 11169 for (unsigned j = 0; j < NumOps; ++j) { 11170 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 11171 SDValue OpVal = getOperand(i); 11172 unsigned BitPos = j * EltWidth; 11173 11174 if (OpVal.isUndef()) 11175 SplatUndef.setBits(BitPos, BitPos + EltWidth); 11176 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 11177 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 11178 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 11179 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 11180 else 11181 return false; 11182 } 11183 11184 // The build_vector is all constants or undefs. Find the smallest element 11185 // size that splats the vector. 11186 HasAnyUndefs = (SplatUndef != 0); 11187 11188 // FIXME: This does not work for vectors with elements less than 8 bits. 11189 while (VecWidth > 8) { 11190 unsigned HalfSize = VecWidth / 2; 11191 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 11192 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 11193 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 11194 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 11195 11196 // If the two halves do not match (ignoring undef bits), stop here. 11197 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 11198 MinSplatBits > HalfSize) 11199 break; 11200 11201 SplatValue = HighValue | LowValue; 11202 SplatUndef = HighUndef & LowUndef; 11203 11204 VecWidth = HalfSize; 11205 } 11206 11207 SplatBitSize = VecWidth; 11208 return true; 11209 } 11210 11211 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 11212 BitVector *UndefElements) const { 11213 unsigned NumOps = getNumOperands(); 11214 if (UndefElements) { 11215 UndefElements->clear(); 11216 UndefElements->resize(NumOps); 11217 } 11218 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11219 if (!DemandedElts) 11220 return SDValue(); 11221 SDValue Splatted; 11222 for (unsigned i = 0; i != NumOps; ++i) { 11223 if (!DemandedElts[i]) 11224 continue; 11225 SDValue Op = getOperand(i); 11226 if (Op.isUndef()) { 11227 if (UndefElements) 11228 (*UndefElements)[i] = true; 11229 } else if (!Splatted) { 11230 Splatted = Op; 11231 } else if (Splatted != Op) { 11232 return SDValue(); 11233 } 11234 } 11235 11236 if (!Splatted) { 11237 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 11238 assert(getOperand(FirstDemandedIdx).isUndef() && 11239 "Can only have a splat without a constant for all undefs."); 11240 return getOperand(FirstDemandedIdx); 11241 } 11242 11243 return Splatted; 11244 } 11245 11246 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 11247 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11248 return getSplatValue(DemandedElts, UndefElements); 11249 } 11250 11251 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 11252 SmallVectorImpl<SDValue> &Sequence, 11253 BitVector *UndefElements) const { 11254 unsigned NumOps = getNumOperands(); 11255 Sequence.clear(); 11256 if (UndefElements) { 11257 UndefElements->clear(); 11258 UndefElements->resize(NumOps); 11259 } 11260 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11261 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 11262 return false; 11263 11264 // Set the undefs even if we don't find a sequence (like getSplatValue). 11265 if (UndefElements) 11266 for (unsigned I = 0; I != NumOps; ++I) 11267 if (DemandedElts[I] && getOperand(I).isUndef()) 11268 (*UndefElements)[I] = true; 11269 11270 // Iteratively widen the sequence length looking for repetitions. 11271 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 11272 Sequence.append(SeqLen, SDValue()); 11273 for (unsigned I = 0; I != NumOps; ++I) { 11274 if (!DemandedElts[I]) 11275 continue; 11276 SDValue &SeqOp = Sequence[I % SeqLen]; 11277 SDValue Op = getOperand(I); 11278 if (Op.isUndef()) { 11279 if (!SeqOp) 11280 SeqOp = Op; 11281 continue; 11282 } 11283 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 11284 Sequence.clear(); 11285 break; 11286 } 11287 SeqOp = Op; 11288 } 11289 if (!Sequence.empty()) 11290 return true; 11291 } 11292 11293 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 11294 return false; 11295 } 11296 11297 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 11298 BitVector *UndefElements) const { 11299 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11300 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 11301 } 11302 11303 ConstantSDNode * 11304 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 11305 BitVector *UndefElements) const { 11306 return dyn_cast_or_null<ConstantSDNode>( 11307 getSplatValue(DemandedElts, UndefElements)); 11308 } 11309 11310 ConstantSDNode * 11311 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 11312 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 11313 } 11314 11315 ConstantFPSDNode * 11316 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 11317 BitVector *UndefElements) const { 11318 return dyn_cast_or_null<ConstantFPSDNode>( 11319 getSplatValue(DemandedElts, UndefElements)); 11320 } 11321 11322 ConstantFPSDNode * 11323 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 11324 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 11325 } 11326 11327 int32_t 11328 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 11329 uint32_t BitWidth) const { 11330 if (ConstantFPSDNode *CN = 11331 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 11332 bool IsExact; 11333 APSInt IntVal(BitWidth); 11334 const APFloat &APF = CN->getValueAPF(); 11335 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 11336 APFloat::opOK || 11337 !IsExact) 11338 return -1; 11339 11340 return IntVal.exactLogBase2(); 11341 } 11342 return -1; 11343 } 11344 11345 bool BuildVectorSDNode::getConstantRawBits( 11346 bool IsLittleEndian, unsigned DstEltSizeInBits, 11347 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 11348 // Early-out if this contains anything but Undef/Constant/ConstantFP. 11349 if (!isConstant()) 11350 return false; 11351 11352 unsigned NumSrcOps = getNumOperands(); 11353 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 11354 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11355 "Invalid bitcast scale"); 11356 11357 // Extract raw src bits. 11358 SmallVector<APInt> SrcBitElements(NumSrcOps, 11359 APInt::getNullValue(SrcEltSizeInBits)); 11360 BitVector SrcUndeElements(NumSrcOps, false); 11361 11362 for (unsigned I = 0; I != NumSrcOps; ++I) { 11363 SDValue Op = getOperand(I); 11364 if (Op.isUndef()) { 11365 SrcUndeElements.set(I); 11366 continue; 11367 } 11368 auto *CInt = dyn_cast<ConstantSDNode>(Op); 11369 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 11370 assert((CInt || CFP) && "Unknown constant"); 11371 SrcBitElements[I] = 11372 CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits) 11373 : CFP->getValueAPF().bitcastToAPInt(); 11374 } 11375 11376 // Recast to dst width. 11377 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11378 SrcBitElements, UndefElements, SrcUndeElements); 11379 return true; 11380 } 11381 11382 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11383 unsigned DstEltSizeInBits, 11384 SmallVectorImpl<APInt> &DstBitElements, 11385 ArrayRef<APInt> SrcBitElements, 11386 BitVector &DstUndefElements, 11387 const BitVector &SrcUndefElements) { 11388 unsigned NumSrcOps = SrcBitElements.size(); 11389 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11390 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11391 "Invalid bitcast scale"); 11392 assert(NumSrcOps == SrcUndefElements.size() && 11393 "Vector size mismatch"); 11394 11395 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11396 DstUndefElements.clear(); 11397 DstUndefElements.resize(NumDstOps, false); 11398 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11399 11400 // Concatenate src elements constant bits together into dst element. 11401 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11402 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11403 for (unsigned I = 0; I != NumDstOps; ++I) { 11404 DstUndefElements.set(I); 11405 APInt &DstBits = DstBitElements[I]; 11406 for (unsigned J = 0; J != Scale; ++J) { 11407 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11408 if (SrcUndefElements[Idx]) 11409 continue; 11410 DstUndefElements.reset(I); 11411 const APInt &SrcBits = SrcBitElements[Idx]; 11412 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11413 "Illegal constant bitwidths"); 11414 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11415 } 11416 } 11417 return; 11418 } 11419 11420 // Split src element constant bits into dst elements. 11421 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11422 for (unsigned I = 0; I != NumSrcOps; ++I) { 11423 if (SrcUndefElements[I]) { 11424 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11425 continue; 11426 } 11427 const APInt &SrcBits = SrcBitElements[I]; 11428 for (unsigned J = 0; J != Scale; ++J) { 11429 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11430 APInt &DstBits = DstBitElements[Idx]; 11431 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11432 } 11433 } 11434 } 11435 11436 bool BuildVectorSDNode::isConstant() const { 11437 for (const SDValue &Op : op_values()) { 11438 unsigned Opc = Op.getOpcode(); 11439 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11440 return false; 11441 } 11442 return true; 11443 } 11444 11445 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11446 // Find the first non-undef value in the shuffle mask. 11447 unsigned i, e; 11448 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11449 /* search */; 11450 11451 // If all elements are undefined, this shuffle can be considered a splat 11452 // (although it should eventually get simplified away completely). 11453 if (i == e) 11454 return true; 11455 11456 // Make sure all remaining elements are either undef or the same as the first 11457 // non-undef value. 11458 for (int Idx = Mask[i]; i != e; ++i) 11459 if (Mask[i] >= 0 && Mask[i] != Idx) 11460 return false; 11461 return true; 11462 } 11463 11464 // Returns the SDNode if it is a constant integer BuildVector 11465 // or constant integer. 11466 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11467 if (isa<ConstantSDNode>(N)) 11468 return N.getNode(); 11469 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11470 return N.getNode(); 11471 // Treat a GlobalAddress supporting constant offset folding as a 11472 // constant integer. 11473 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11474 if (GA->getOpcode() == ISD::GlobalAddress && 11475 TLI->isOffsetFoldingLegal(GA)) 11476 return GA; 11477 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11478 isa<ConstantSDNode>(N.getOperand(0))) 11479 return N.getNode(); 11480 return nullptr; 11481 } 11482 11483 // Returns the SDNode if it is a constant float BuildVector 11484 // or constant float. 11485 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11486 if (isa<ConstantFPSDNode>(N)) 11487 return N.getNode(); 11488 11489 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11490 return N.getNode(); 11491 11492 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11493 isa<ConstantFPSDNode>(N.getOperand(0))) 11494 return N.getNode(); 11495 11496 return nullptr; 11497 } 11498 11499 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11500 assert(!Node->OperandList && "Node already has operands"); 11501 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11502 "too many operands to fit into SDNode"); 11503 SDUse *Ops = OperandRecycler.allocate( 11504 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11505 11506 bool IsDivergent = false; 11507 for (unsigned I = 0; I != Vals.size(); ++I) { 11508 Ops[I].setUser(Node); 11509 Ops[I].setInitial(Vals[I]); 11510 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11511 IsDivergent |= Ops[I].getNode()->isDivergent(); 11512 } 11513 Node->NumOperands = Vals.size(); 11514 Node->OperandList = Ops; 11515 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11516 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11517 Node->SDNodeBits.IsDivergent = IsDivergent; 11518 } 11519 checkForCycles(Node); 11520 } 11521 11522 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11523 SmallVectorImpl<SDValue> &Vals) { 11524 size_t Limit = SDNode::getMaxNumOperands(); 11525 while (Vals.size() > Limit) { 11526 unsigned SliceIdx = Vals.size() - Limit; 11527 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11528 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11529 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11530 Vals.emplace_back(NewTF); 11531 } 11532 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11533 } 11534 11535 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11536 EVT VT, SDNodeFlags Flags) { 11537 switch (Opcode) { 11538 default: 11539 return SDValue(); 11540 case ISD::ADD: 11541 case ISD::OR: 11542 case ISD::XOR: 11543 case ISD::UMAX: 11544 return getConstant(0, DL, VT); 11545 case ISD::MUL: 11546 return getConstant(1, DL, VT); 11547 case ISD::AND: 11548 case ISD::UMIN: 11549 return getAllOnesConstant(DL, VT); 11550 case ISD::SMAX: 11551 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11552 case ISD::SMIN: 11553 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11554 case ISD::FADD: 11555 return getConstantFP(-0.0, DL, VT); 11556 case ISD::FMUL: 11557 return getConstantFP(1.0, DL, VT); 11558 case ISD::FMINNUM: 11559 case ISD::FMAXNUM: { 11560 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11561 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11562 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11563 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11564 APFloat::getLargest(Semantics); 11565 if (Opcode == ISD::FMAXNUM) 11566 NeutralAF.changeSign(); 11567 11568 return getConstantFP(NeutralAF, DL, VT); 11569 } 11570 } 11571 } 11572 11573 #ifndef NDEBUG 11574 static void checkForCyclesHelper(const SDNode *N, 11575 SmallPtrSetImpl<const SDNode*> &Visited, 11576 SmallPtrSetImpl<const SDNode*> &Checked, 11577 const llvm::SelectionDAG *DAG) { 11578 // If this node has already been checked, don't check it again. 11579 if (Checked.count(N)) 11580 return; 11581 11582 // If a node has already been visited on this depth-first walk, reject it as 11583 // a cycle. 11584 if (!Visited.insert(N).second) { 11585 errs() << "Detected cycle in SelectionDAG\n"; 11586 dbgs() << "Offending node:\n"; 11587 N->dumprFull(DAG); dbgs() << "\n"; 11588 abort(); 11589 } 11590 11591 for (const SDValue &Op : N->op_values()) 11592 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11593 11594 Checked.insert(N); 11595 Visited.erase(N); 11596 } 11597 #endif 11598 11599 void llvm::checkForCycles(const llvm::SDNode *N, 11600 const llvm::SelectionDAG *DAG, 11601 bool force) { 11602 #ifndef NDEBUG 11603 bool check = force; 11604 #ifdef EXPENSIVE_CHECKS 11605 check = true; 11606 #endif // EXPENSIVE_CHECKS 11607 if (check) { 11608 assert(N && "Checking nonexistent SDNode"); 11609 SmallPtrSet<const SDNode*, 32> visited; 11610 SmallPtrSet<const SDNode*, 32> checked; 11611 checkForCyclesHelper(N, visited, checked, DAG); 11612 } 11613 #endif // !NDEBUG 11614 } 11615 11616 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11617 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11618 } 11619