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/AliasAnalysis.h" 28 #include "llvm/Analysis/MemoryLocation.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/CodeGen/Analysis.h" 31 #include "llvm/CodeGen/FunctionLoweringInfo.h" 32 #include "llvm/CodeGen/ISDOpcodes.h" 33 #include "llvm/CodeGen/MachineBasicBlock.h" 34 #include "llvm/CodeGen/MachineConstantPool.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineMemOperand.h" 38 #include "llvm/CodeGen/RuntimeLibcalls.h" 39 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 40 #include "llvm/CodeGen/SelectionDAGNodes.h" 41 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 42 #include "llvm/CodeGen/TargetFrameLowering.h" 43 #include "llvm/CodeGen/TargetLowering.h" 44 #include "llvm/CodeGen/TargetRegisterInfo.h" 45 #include "llvm/CodeGen/TargetSubtargetInfo.h" 46 #include "llvm/CodeGen/ValueTypes.h" 47 #include "llvm/IR/Constant.h" 48 #include "llvm/IR/Constants.h" 49 #include "llvm/IR/DataLayout.h" 50 #include "llvm/IR/DebugInfoMetadata.h" 51 #include "llvm/IR/DebugLoc.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/GlobalValue.h" 55 #include "llvm/IR/Metadata.h" 56 #include "llvm/IR/Type.h" 57 #include "llvm/Support/Casting.h" 58 #include "llvm/Support/CodeGen.h" 59 #include "llvm/Support/Compiler.h" 60 #include "llvm/Support/Debug.h" 61 #include "llvm/Support/ErrorHandling.h" 62 #include "llvm/Support/KnownBits.h" 63 #include "llvm/Support/MachineValueType.h" 64 #include "llvm/Support/MathExtras.h" 65 #include "llvm/Support/Mutex.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include "llvm/Target/TargetOptions.h" 69 #include "llvm/Transforms/Utils/SizeOpts.h" 70 #include <algorithm> 71 #include <cassert> 72 #include <cstdint> 73 #include <cstdlib> 74 #include <limits> 75 #include <set> 76 #include <string> 77 #include <utility> 78 #include <vector> 79 80 using namespace llvm; 81 82 /// makeVTList - Return an instance of the SDVTList struct initialized with the 83 /// specified members. 84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 85 SDVTList Res = {VTs, NumVTs}; 86 return Res; 87 } 88 89 // Default null implementations of the callbacks. 90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 93 94 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 95 96 #define DEBUG_TYPE "selectiondag" 97 98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 99 cl::Hidden, cl::init(true), 100 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 101 102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 103 cl::desc("Number limit for gluing ld/st of memcpy."), 104 cl::Hidden, cl::init(0)); 105 106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 107 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 108 } 109 110 //===----------------------------------------------------------------------===// 111 // ConstantFPSDNode Class 112 //===----------------------------------------------------------------------===// 113 114 /// isExactlyValue - We don't rely on operator== working on double values, as 115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 116 /// As such, this method can be used to do an exact bit-for-bit comparison of 117 /// two floating point values. 118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 119 return getValueAPF().bitwiseIsEqual(V); 120 } 121 122 bool ConstantFPSDNode::isValueValidForType(EVT VT, 123 const APFloat& Val) { 124 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 125 126 // convert modifies in place, so make a copy. 127 APFloat Val2 = APFloat(Val); 128 bool losesInfo; 129 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 130 APFloat::rmNearestTiesToEven, 131 &losesInfo); 132 return !losesInfo; 133 } 134 135 //===----------------------------------------------------------------------===// 136 // ISD Namespace 137 //===----------------------------------------------------------------------===// 138 139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 140 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 141 unsigned EltSize = 142 N->getValueType(0).getVectorElementType().getSizeInBits(); 143 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 144 SplatVal = Op0->getAPIntValue().trunc(EltSize); 145 return true; 146 } 147 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 148 SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize); 149 return true; 150 } 151 } 152 153 auto *BV = dyn_cast<BuildVectorSDNode>(N); 154 if (!BV) 155 return false; 156 157 APInt SplatUndef; 158 unsigned SplatBitSize; 159 bool HasUndefs; 160 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 161 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 162 EltSize) && 163 EltSize == SplatBitSize; 164 } 165 166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 167 // specializations of the more general isConstantSplatVector()? 168 169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 170 // Look through a bit convert. 171 while (N->getOpcode() == ISD::BITCAST) 172 N = N->getOperand(0).getNode(); 173 174 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 175 APInt SplatVal; 176 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 177 } 178 179 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 180 181 unsigned i = 0, e = N->getNumOperands(); 182 183 // Skip over all of the undef values. 184 while (i != e && N->getOperand(i).isUndef()) 185 ++i; 186 187 // Do not accept an all-undef vector. 188 if (i == e) return false; 189 190 // Do not accept build_vectors that aren't all constants or which have non-~0 191 // elements. We have to be a bit careful here, as the type of the constant 192 // may not be the same as the type of the vector elements due to type 193 // legalization (the elements are promoted to a legal type for the target and 194 // a vector of a type may be legal when the base element type is not). 195 // We only want to check enough bits to cover the vector elements, because 196 // we care if the resultant vector is all ones, not whether the individual 197 // constants are. 198 SDValue NotZero = N->getOperand(i); 199 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 200 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 201 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 202 return false; 203 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 204 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 205 return false; 206 } else 207 return false; 208 209 // Okay, we have at least one ~0 value, check to see if the rest match or are 210 // undefs. Even with the above element type twiddling, this should be OK, as 211 // the same type legalization should have applied to all the elements. 212 for (++i; i != e; ++i) 213 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 214 return false; 215 return true; 216 } 217 218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 219 // Look through a bit convert. 220 while (N->getOpcode() == ISD::BITCAST) 221 N = N->getOperand(0).getNode(); 222 223 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 224 APInt SplatVal; 225 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 226 } 227 228 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 229 230 bool IsAllUndef = true; 231 for (const SDValue &Op : N->op_values()) { 232 if (Op.isUndef()) 233 continue; 234 IsAllUndef = false; 235 // Do not accept build_vectors that aren't all constants or which have non-0 236 // elements. We have to be a bit careful here, as the type of the constant 237 // may not be the same as the type of the vector elements due to type 238 // legalization (the elements are promoted to a legal type for the target 239 // and a vector of a type may be legal when the base element type is not). 240 // We only want to check enough bits to cover the vector elements, because 241 // we care if the resultant vector is all zeros, not whether the individual 242 // constants are. 243 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 244 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 245 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 246 return false; 247 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 248 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 249 return false; 250 } else 251 return false; 252 } 253 254 // Do not accept an all-undef vector. 255 if (IsAllUndef) 256 return false; 257 return true; 258 } 259 260 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 261 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 262 } 263 264 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 265 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 266 } 267 268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 269 if (N->getOpcode() != ISD::BUILD_VECTOR) 270 return false; 271 272 for (const SDValue &Op : N->op_values()) { 273 if (Op.isUndef()) 274 continue; 275 if (!isa<ConstantSDNode>(Op)) 276 return false; 277 } 278 return true; 279 } 280 281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 282 if (N->getOpcode() != ISD::BUILD_VECTOR) 283 return false; 284 285 for (const SDValue &Op : N->op_values()) { 286 if (Op.isUndef()) 287 continue; 288 if (!isa<ConstantFPSDNode>(Op)) 289 return false; 290 } 291 return true; 292 } 293 294 bool ISD::allOperandsUndef(const SDNode *N) { 295 // Return false if the node has no operands. 296 // This is "logically inconsistent" with the definition of "all" but 297 // is probably the desired behavior. 298 if (N->getNumOperands() == 0) 299 return false; 300 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 301 } 302 303 bool ISD::matchUnaryPredicate(SDValue Op, 304 std::function<bool(ConstantSDNode *)> Match, 305 bool AllowUndefs) { 306 // FIXME: Add support for scalar UNDEF cases? 307 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 308 return Match(Cst); 309 310 // FIXME: Add support for vector UNDEF cases? 311 if (ISD::BUILD_VECTOR != Op.getOpcode() && 312 ISD::SPLAT_VECTOR != Op.getOpcode()) 313 return false; 314 315 EVT SVT = Op.getValueType().getScalarType(); 316 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 317 if (AllowUndefs && Op.getOperand(i).isUndef()) { 318 if (!Match(nullptr)) 319 return false; 320 continue; 321 } 322 323 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 324 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 325 return false; 326 } 327 return true; 328 } 329 330 bool ISD::matchBinaryPredicate( 331 SDValue LHS, SDValue RHS, 332 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 333 bool AllowUndefs, bool AllowTypeMismatch) { 334 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 335 return false; 336 337 // TODO: Add support for scalar UNDEF cases? 338 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 339 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 340 return Match(LHSCst, RHSCst); 341 342 // TODO: Add support for vector UNDEF cases? 343 if (LHS.getOpcode() != RHS.getOpcode() || 344 (LHS.getOpcode() != ISD::BUILD_VECTOR && 345 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 346 return false; 347 348 EVT SVT = LHS.getValueType().getScalarType(); 349 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 350 SDValue LHSOp = LHS.getOperand(i); 351 SDValue RHSOp = RHS.getOperand(i); 352 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 353 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 354 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 355 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 356 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 357 return false; 358 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 359 LHSOp.getValueType() != RHSOp.getValueType())) 360 return false; 361 if (!Match(LHSCst, RHSCst)) 362 return false; 363 } 364 return true; 365 } 366 367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 368 switch (VecReduceOpcode) { 369 default: 370 llvm_unreachable("Expected VECREDUCE opcode"); 371 case ISD::VECREDUCE_FADD: 372 case ISD::VECREDUCE_SEQ_FADD: 373 case ISD::VP_REDUCE_FADD: 374 case ISD::VP_REDUCE_SEQ_FADD: 375 return ISD::FADD; 376 case ISD::VECREDUCE_FMUL: 377 case ISD::VECREDUCE_SEQ_FMUL: 378 case ISD::VP_REDUCE_FMUL: 379 case ISD::VP_REDUCE_SEQ_FMUL: 380 return ISD::FMUL; 381 case ISD::VECREDUCE_ADD: 382 case ISD::VP_REDUCE_ADD: 383 return ISD::ADD; 384 case ISD::VECREDUCE_MUL: 385 case ISD::VP_REDUCE_MUL: 386 return ISD::MUL; 387 case ISD::VECREDUCE_AND: 388 case ISD::VP_REDUCE_AND: 389 return ISD::AND; 390 case ISD::VECREDUCE_OR: 391 case ISD::VP_REDUCE_OR: 392 return ISD::OR; 393 case ISD::VECREDUCE_XOR: 394 case ISD::VP_REDUCE_XOR: 395 return ISD::XOR; 396 case ISD::VECREDUCE_SMAX: 397 case ISD::VP_REDUCE_SMAX: 398 return ISD::SMAX; 399 case ISD::VECREDUCE_SMIN: 400 case ISD::VP_REDUCE_SMIN: 401 return ISD::SMIN; 402 case ISD::VECREDUCE_UMAX: 403 case ISD::VP_REDUCE_UMAX: 404 return ISD::UMAX; 405 case ISD::VECREDUCE_UMIN: 406 case ISD::VP_REDUCE_UMIN: 407 return ISD::UMIN; 408 case ISD::VECREDUCE_FMAX: 409 case ISD::VP_REDUCE_FMAX: 410 return ISD::FMAXNUM; 411 case ISD::VECREDUCE_FMIN: 412 case ISD::VP_REDUCE_FMIN: 413 return ISD::FMINNUM; 414 } 415 } 416 417 bool ISD::isVPOpcode(unsigned Opcode) { 418 switch (Opcode) { 419 default: 420 return false; 421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 422 case ISD::VPSD: \ 423 return true; 424 #include "llvm/IR/VPIntrinsics.def" 425 } 426 } 427 428 bool ISD::isVPBinaryOp(unsigned Opcode) { 429 switch (Opcode) { 430 default: 431 break; 432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 433 #define VP_PROPERTY_BINARYOP return true; 434 #define END_REGISTER_VP_SDNODE(VPSD) break; 435 #include "llvm/IR/VPIntrinsics.def" 436 } 437 return false; 438 } 439 440 bool ISD::isVPReduction(unsigned Opcode) { 441 switch (Opcode) { 442 default: 443 break; 444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 446 #define END_REGISTER_VP_SDNODE(VPSD) break; 447 #include "llvm/IR/VPIntrinsics.def" 448 } 449 return false; 450 } 451 452 /// The operand position of the vector mask. 453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 454 switch (Opcode) { 455 default: 456 return None; 457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 458 case ISD::VPSD: \ 459 return MASKPOS; 460 #include "llvm/IR/VPIntrinsics.def" 461 } 462 } 463 464 /// The operand position of the explicit vector length parameter. 465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 466 switch (Opcode) { 467 default: 468 return None; 469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 470 case ISD::VPSD: \ 471 return EVLPOS; 472 #include "llvm/IR/VPIntrinsics.def" 473 } 474 } 475 476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 477 switch (ExtType) { 478 case ISD::EXTLOAD: 479 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 480 case ISD::SEXTLOAD: 481 return ISD::SIGN_EXTEND; 482 case ISD::ZEXTLOAD: 483 return ISD::ZERO_EXTEND; 484 default: 485 break; 486 } 487 488 llvm_unreachable("Invalid LoadExtType"); 489 } 490 491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 492 // To perform this operation, we just need to swap the L and G bits of the 493 // operation. 494 unsigned OldL = (Operation >> 2) & 1; 495 unsigned OldG = (Operation >> 1) & 1; 496 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 497 (OldL << 1) | // New G bit 498 (OldG << 2)); // New L bit. 499 } 500 501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 502 unsigned Operation = Op; 503 if (isIntegerLike) 504 Operation ^= 7; // Flip L, G, E bits, but not U. 505 else 506 Operation ^= 15; // Flip all of the condition bits. 507 508 if (Operation > ISD::SETTRUE2) 509 Operation &= ~8; // Don't let N and U bits get set. 510 511 return ISD::CondCode(Operation); 512 } 513 514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 515 return getSetCCInverseImpl(Op, Type.isInteger()); 516 } 517 518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 519 bool isIntegerLike) { 520 return getSetCCInverseImpl(Op, isIntegerLike); 521 } 522 523 /// For an integer comparison, return 1 if the comparison is a signed operation 524 /// and 2 if the result is an unsigned comparison. Return zero if the operation 525 /// does not depend on the sign of the input (setne and seteq). 526 static int isSignedOp(ISD::CondCode Opcode) { 527 switch (Opcode) { 528 default: llvm_unreachable("Illegal integer setcc operation!"); 529 case ISD::SETEQ: 530 case ISD::SETNE: return 0; 531 case ISD::SETLT: 532 case ISD::SETLE: 533 case ISD::SETGT: 534 case ISD::SETGE: return 1; 535 case ISD::SETULT: 536 case ISD::SETULE: 537 case ISD::SETUGT: 538 case ISD::SETUGE: return 2; 539 } 540 } 541 542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 543 EVT Type) { 544 bool IsInteger = Type.isInteger(); 545 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 546 // Cannot fold a signed integer setcc with an unsigned integer setcc. 547 return ISD::SETCC_INVALID; 548 549 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 550 551 // If the N and U bits get set, then the resultant comparison DOES suddenly 552 // care about orderedness, and it is true when ordered. 553 if (Op > ISD::SETTRUE2) 554 Op &= ~16; // Clear the U bit if the N bit is set. 555 556 // Canonicalize illegal integer setcc's. 557 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 558 Op = ISD::SETNE; 559 560 return ISD::CondCode(Op); 561 } 562 563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 564 EVT Type) { 565 bool IsInteger = Type.isInteger(); 566 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 567 // Cannot fold a signed setcc with an unsigned setcc. 568 return ISD::SETCC_INVALID; 569 570 // Combine all of the condition bits. 571 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 572 573 // Canonicalize illegal integer setcc's. 574 if (IsInteger) { 575 switch (Result) { 576 default: break; 577 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 578 case ISD::SETOEQ: // SETEQ & SETU[LG]E 579 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 580 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 581 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 582 } 583 } 584 585 return Result; 586 } 587 588 //===----------------------------------------------------------------------===// 589 // SDNode Profile Support 590 //===----------------------------------------------------------------------===// 591 592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 594 ID.AddInteger(OpC); 595 } 596 597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 598 /// solely with their pointer. 599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 600 ID.AddPointer(VTList.VTs); 601 } 602 603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 604 static void AddNodeIDOperands(FoldingSetNodeID &ID, 605 ArrayRef<SDValue> Ops) { 606 for (const 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 (const auto &Op : Ops) { 616 ID.AddPointer(Op.getNode()); 617 ID.AddInteger(Op.getResNo()); 618 } 619 } 620 621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 622 SDVTList VTList, ArrayRef<SDValue> OpList) { 623 AddNodeIDOpcode(ID, OpC); 624 AddNodeIDValueTypes(ID, VTList); 625 AddNodeIDOperands(ID, OpList); 626 } 627 628 /// If this is an SDNode with special info, add this info to the NodeID data. 629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 630 switch (N->getOpcode()) { 631 case ISD::TargetExternalSymbol: 632 case ISD::ExternalSymbol: 633 case ISD::MCSymbol: 634 llvm_unreachable("Should only be used on nodes with operands"); 635 default: break; // Normal nodes don't need extra info. 636 case ISD::TargetConstant: 637 case ISD::Constant: { 638 const ConstantSDNode *C = cast<ConstantSDNode>(N); 639 ID.AddPointer(C->getConstantIntValue()); 640 ID.AddBoolean(C->isOpaque()); 641 break; 642 } 643 case ISD::TargetConstantFP: 644 case ISD::ConstantFP: 645 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 646 break; 647 case ISD::TargetGlobalAddress: 648 case ISD::GlobalAddress: 649 case ISD::TargetGlobalTLSAddress: 650 case ISD::GlobalTLSAddress: { 651 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 652 ID.AddPointer(GA->getGlobal()); 653 ID.AddInteger(GA->getOffset()); 654 ID.AddInteger(GA->getTargetFlags()); 655 break; 656 } 657 case ISD::BasicBlock: 658 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 659 break; 660 case ISD::Register: 661 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 662 break; 663 case ISD::RegisterMask: 664 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 665 break; 666 case ISD::SRCVALUE: 667 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 668 break; 669 case ISD::FrameIndex: 670 case ISD::TargetFrameIndex: 671 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 672 break; 673 case ISD::LIFETIME_START: 674 case ISD::LIFETIME_END: 675 if (cast<LifetimeSDNode>(N)->hasOffset()) { 676 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 677 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 678 } 679 break; 680 case ISD::PSEUDO_PROBE: 681 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 682 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 683 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 684 break; 685 case ISD::JumpTable: 686 case ISD::TargetJumpTable: 687 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 688 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 689 break; 690 case ISD::ConstantPool: 691 case ISD::TargetConstantPool: { 692 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 693 ID.AddInteger(CP->getAlign().value()); 694 ID.AddInteger(CP->getOffset()); 695 if (CP->isMachineConstantPoolEntry()) 696 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 697 else 698 ID.AddPointer(CP->getConstVal()); 699 ID.AddInteger(CP->getTargetFlags()); 700 break; 701 } 702 case ISD::TargetIndex: { 703 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 704 ID.AddInteger(TI->getIndex()); 705 ID.AddInteger(TI->getOffset()); 706 ID.AddInteger(TI->getTargetFlags()); 707 break; 708 } 709 case ISD::LOAD: { 710 const LoadSDNode *LD = cast<LoadSDNode>(N); 711 ID.AddInteger(LD->getMemoryVT().getRawBits()); 712 ID.AddInteger(LD->getRawSubclassData()); 713 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 714 ID.AddInteger(LD->getMemOperand()->getFlags()); 715 break; 716 } 717 case ISD::STORE: { 718 const StoreSDNode *ST = cast<StoreSDNode>(N); 719 ID.AddInteger(ST->getMemoryVT().getRawBits()); 720 ID.AddInteger(ST->getRawSubclassData()); 721 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 722 ID.AddInteger(ST->getMemOperand()->getFlags()); 723 break; 724 } 725 case ISD::VP_LOAD: { 726 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 727 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 728 ID.AddInteger(ELD->getRawSubclassData()); 729 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 730 ID.AddInteger(ELD->getMemOperand()->getFlags()); 731 break; 732 } 733 case ISD::VP_STORE: { 734 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 735 ID.AddInteger(EST->getMemoryVT().getRawBits()); 736 ID.AddInteger(EST->getRawSubclassData()); 737 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 738 ID.AddInteger(EST->getMemOperand()->getFlags()); 739 break; 740 } 741 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: { 742 const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N); 743 ID.AddInteger(SLD->getMemoryVT().getRawBits()); 744 ID.AddInteger(SLD->getRawSubclassData()); 745 ID.AddInteger(SLD->getPointerInfo().getAddrSpace()); 746 break; 747 } 748 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: { 749 const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N); 750 ID.AddInteger(SST->getMemoryVT().getRawBits()); 751 ID.AddInteger(SST->getRawSubclassData()); 752 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 753 break; 754 } 755 case ISD::VP_GATHER: { 756 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 757 ID.AddInteger(EG->getMemoryVT().getRawBits()); 758 ID.AddInteger(EG->getRawSubclassData()); 759 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 760 ID.AddInteger(EG->getMemOperand()->getFlags()); 761 break; 762 } 763 case ISD::VP_SCATTER: { 764 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 765 ID.AddInteger(ES->getMemoryVT().getRawBits()); 766 ID.AddInteger(ES->getRawSubclassData()); 767 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 768 ID.AddInteger(ES->getMemOperand()->getFlags()); 769 break; 770 } 771 case ISD::MLOAD: { 772 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 773 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 774 ID.AddInteger(MLD->getRawSubclassData()); 775 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 776 ID.AddInteger(MLD->getMemOperand()->getFlags()); 777 break; 778 } 779 case ISD::MSTORE: { 780 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 781 ID.AddInteger(MST->getMemoryVT().getRawBits()); 782 ID.AddInteger(MST->getRawSubclassData()); 783 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 784 ID.AddInteger(MST->getMemOperand()->getFlags()); 785 break; 786 } 787 case ISD::MGATHER: { 788 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 789 ID.AddInteger(MG->getMemoryVT().getRawBits()); 790 ID.AddInteger(MG->getRawSubclassData()); 791 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 792 ID.AddInteger(MG->getMemOperand()->getFlags()); 793 break; 794 } 795 case ISD::MSCATTER: { 796 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 797 ID.AddInteger(MS->getMemoryVT().getRawBits()); 798 ID.AddInteger(MS->getRawSubclassData()); 799 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 800 ID.AddInteger(MS->getMemOperand()->getFlags()); 801 break; 802 } 803 case ISD::ATOMIC_CMP_SWAP: 804 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 805 case ISD::ATOMIC_SWAP: 806 case ISD::ATOMIC_LOAD_ADD: 807 case ISD::ATOMIC_LOAD_SUB: 808 case ISD::ATOMIC_LOAD_AND: 809 case ISD::ATOMIC_LOAD_CLR: 810 case ISD::ATOMIC_LOAD_OR: 811 case ISD::ATOMIC_LOAD_XOR: 812 case ISD::ATOMIC_LOAD_NAND: 813 case ISD::ATOMIC_LOAD_MIN: 814 case ISD::ATOMIC_LOAD_MAX: 815 case ISD::ATOMIC_LOAD_UMIN: 816 case ISD::ATOMIC_LOAD_UMAX: 817 case ISD::ATOMIC_LOAD: 818 case ISD::ATOMIC_STORE: { 819 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 820 ID.AddInteger(AT->getMemoryVT().getRawBits()); 821 ID.AddInteger(AT->getRawSubclassData()); 822 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 823 ID.AddInteger(AT->getMemOperand()->getFlags()); 824 break; 825 } 826 case ISD::PREFETCH: { 827 const MemSDNode *PF = cast<MemSDNode>(N); 828 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 829 ID.AddInteger(PF->getMemOperand()->getFlags()); 830 break; 831 } 832 case ISD::VECTOR_SHUFFLE: { 833 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 834 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 835 i != e; ++i) 836 ID.AddInteger(SVN->getMaskElt(i)); 837 break; 838 } 839 case ISD::TargetBlockAddress: 840 case ISD::BlockAddress: { 841 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 842 ID.AddPointer(BA->getBlockAddress()); 843 ID.AddInteger(BA->getOffset()); 844 ID.AddInteger(BA->getTargetFlags()); 845 break; 846 } 847 case ISD::AssertAlign: 848 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value()); 849 break; 850 } // end switch (N->getOpcode()) 851 852 // Target specific memory nodes could also have address spaces and flags 853 // to check. 854 if (N->isTargetMemoryOpcode()) { 855 const MemSDNode *MN = cast<MemSDNode>(N); 856 ID.AddInteger(MN->getPointerInfo().getAddrSpace()); 857 ID.AddInteger(MN->getMemOperand()->getFlags()); 858 } 859 } 860 861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 862 /// data. 863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 864 AddNodeIDOpcode(ID, N->getOpcode()); 865 // Add the return value info. 866 AddNodeIDValueTypes(ID, N->getVTList()); 867 // Add the operand info. 868 AddNodeIDOperands(ID, N->ops()); 869 870 // Handle SDNode leafs with special info. 871 AddNodeIDCustom(ID, N); 872 } 873 874 //===----------------------------------------------------------------------===// 875 // SelectionDAG Class 876 //===----------------------------------------------------------------------===// 877 878 /// doNotCSE - Return true if CSE should not be performed for this node. 879 static bool doNotCSE(SDNode *N) { 880 if (N->getValueType(0) == MVT::Glue) 881 return true; // Never CSE anything that produces a flag. 882 883 switch (N->getOpcode()) { 884 default: break; 885 case ISD::HANDLENODE: 886 case ISD::EH_LABEL: 887 return true; // Never CSE these nodes. 888 } 889 890 // Check that remaining values produced are not flags. 891 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 892 if (N->getValueType(i) == MVT::Glue) 893 return true; // Never CSE anything that produces a flag. 894 895 return false; 896 } 897 898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 899 /// SelectionDAG. 900 void SelectionDAG::RemoveDeadNodes() { 901 // Create a dummy node (which is not added to allnodes), that adds a reference 902 // to the root node, preventing it from being deleted. 903 HandleSDNode Dummy(getRoot()); 904 905 SmallVector<SDNode*, 128> DeadNodes; 906 907 // Add all obviously-dead nodes to the DeadNodes worklist. 908 for (SDNode &Node : allnodes()) 909 if (Node.use_empty()) 910 DeadNodes.push_back(&Node); 911 912 RemoveDeadNodes(DeadNodes); 913 914 // If the root changed (e.g. it was a dead load, update the root). 915 setRoot(Dummy.getValue()); 916 } 917 918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 919 /// given list, and any nodes that become unreachable as a result. 920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 921 922 // Process the worklist, deleting the nodes and adding their uses to the 923 // worklist. 924 while (!DeadNodes.empty()) { 925 SDNode *N = DeadNodes.pop_back_val(); 926 // Skip to next node if we've already managed to delete the node. This could 927 // happen if replacing a node causes a node previously added to the node to 928 // be deleted. 929 if (N->getOpcode() == ISD::DELETED_NODE) 930 continue; 931 932 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 933 DUL->NodeDeleted(N, nullptr); 934 935 // Take the node out of the appropriate CSE map. 936 RemoveNodeFromCSEMaps(N); 937 938 // Next, brutally remove the operand list. This is safe to do, as there are 939 // no cycles in the graph. 940 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 941 SDUse &Use = *I++; 942 SDNode *Operand = Use.getNode(); 943 Use.set(SDValue()); 944 945 // Now that we removed this operand, see if there are no uses of it left. 946 if (Operand->use_empty()) 947 DeadNodes.push_back(Operand); 948 } 949 950 DeallocateNode(N); 951 } 952 } 953 954 void SelectionDAG::RemoveDeadNode(SDNode *N){ 955 SmallVector<SDNode*, 16> DeadNodes(1, N); 956 957 // Create a dummy node that adds a reference to the root node, preventing 958 // it from being deleted. (This matters if the root is an operand of the 959 // dead node.) 960 HandleSDNode Dummy(getRoot()); 961 962 RemoveDeadNodes(DeadNodes); 963 } 964 965 void SelectionDAG::DeleteNode(SDNode *N) { 966 // First take this out of the appropriate CSE map. 967 RemoveNodeFromCSEMaps(N); 968 969 // Finally, remove uses due to operands of this node, remove from the 970 // AllNodes list, and delete the node. 971 DeleteNodeNotInCSEMaps(N); 972 } 973 974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 975 assert(N->getIterator() != AllNodes.begin() && 976 "Cannot delete the entry node!"); 977 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 978 979 // Drop all of the operands and decrement used node's use counts. 980 N->DropOperands(); 981 982 DeallocateNode(N); 983 } 984 985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 986 assert(!(V->isVariadic() && isParameter)); 987 if (isParameter) 988 ByvalParmDbgValues.push_back(V); 989 else 990 DbgValues.push_back(V); 991 for (const SDNode *Node : V->getSDNodes()) 992 if (Node) 993 DbgValMap[Node].push_back(V); 994 } 995 996 void SDDbgInfo::erase(const SDNode *Node) { 997 DbgValMapType::iterator I = DbgValMap.find(Node); 998 if (I == DbgValMap.end()) 999 return; 1000 for (auto &Val: I->second) 1001 Val->setIsInvalidated(); 1002 DbgValMap.erase(I); 1003 } 1004 1005 void SelectionDAG::DeallocateNode(SDNode *N) { 1006 // If we have operands, deallocate them. 1007 removeOperands(N); 1008 1009 NodeAllocator.Deallocate(AllNodes.remove(N)); 1010 1011 // Set the opcode to DELETED_NODE to help catch bugs when node 1012 // memory is reallocated. 1013 // FIXME: There are places in SDag that have grown a dependency on the opcode 1014 // value in the released node. 1015 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 1016 N->NodeType = ISD::DELETED_NODE; 1017 1018 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 1019 // them and forget about that node. 1020 DbgInfo->erase(N); 1021 } 1022 1023 #ifndef NDEBUG 1024 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 1025 static void VerifySDNode(SDNode *N) { 1026 switch (N->getOpcode()) { 1027 default: 1028 break; 1029 case ISD::BUILD_PAIR: { 1030 EVT VT = N->getValueType(0); 1031 assert(N->getNumValues() == 1 && "Too many results!"); 1032 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1033 "Wrong return type!"); 1034 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1035 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1036 "Mismatched operand types!"); 1037 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1038 "Wrong operand type!"); 1039 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1040 "Wrong return type size"); 1041 break; 1042 } 1043 case ISD::BUILD_VECTOR: { 1044 assert(N->getNumValues() == 1 && "Too many results!"); 1045 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1046 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1047 "Wrong number of operands!"); 1048 EVT EltVT = N->getValueType(0).getVectorElementType(); 1049 for (const SDUse &Op : N->ops()) { 1050 assert((Op.getValueType() == EltVT || 1051 (EltVT.isInteger() && Op.getValueType().isInteger() && 1052 EltVT.bitsLE(Op.getValueType()))) && 1053 "Wrong operand type!"); 1054 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1055 "Operands must all have the same type"); 1056 } 1057 break; 1058 } 1059 } 1060 } 1061 #endif // NDEBUG 1062 1063 /// Insert a newly allocated node into the DAG. 1064 /// 1065 /// Handles insertion into the all nodes list and CSE map, as well as 1066 /// verification and other common operations when a new node is allocated. 1067 void SelectionDAG::InsertNode(SDNode *N) { 1068 AllNodes.push_back(N); 1069 #ifndef NDEBUG 1070 N->PersistentId = NextPersistentId++; 1071 VerifySDNode(N); 1072 #endif 1073 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1074 DUL->NodeInserted(N); 1075 } 1076 1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1078 /// correspond to it. This is useful when we're about to delete or repurpose 1079 /// the node. We don't want future request for structurally identical nodes 1080 /// to return N anymore. 1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1082 bool Erased = false; 1083 switch (N->getOpcode()) { 1084 case ISD::HANDLENODE: return false; // noop. 1085 case ISD::CONDCODE: 1086 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1087 "Cond code doesn't exist!"); 1088 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1089 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1090 break; 1091 case ISD::ExternalSymbol: 1092 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1093 break; 1094 case ISD::TargetExternalSymbol: { 1095 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1096 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1097 ESN->getSymbol(), ESN->getTargetFlags())); 1098 break; 1099 } 1100 case ISD::MCSymbol: { 1101 auto *MCSN = cast<MCSymbolSDNode>(N); 1102 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1103 break; 1104 } 1105 case ISD::VALUETYPE: { 1106 EVT VT = cast<VTSDNode>(N)->getVT(); 1107 if (VT.isExtended()) { 1108 Erased = ExtendedValueTypeNodes.erase(VT); 1109 } else { 1110 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1111 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1112 } 1113 break; 1114 } 1115 default: 1116 // Remove it from the CSE Map. 1117 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1118 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1119 Erased = CSEMap.RemoveNode(N); 1120 break; 1121 } 1122 #ifndef NDEBUG 1123 // Verify that the node was actually in one of the CSE maps, unless it has a 1124 // flag result (which cannot be CSE'd) or is one of the special cases that are 1125 // not subject to CSE. 1126 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1127 !N->isMachineOpcode() && !doNotCSE(N)) { 1128 N->dump(this); 1129 dbgs() << "\n"; 1130 llvm_unreachable("Node is not in map!"); 1131 } 1132 #endif 1133 return Erased; 1134 } 1135 1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1138 /// node already exists, in which case transfer all its users to the existing 1139 /// node. This transfer can potentially trigger recursive merging. 1140 void 1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1142 // For node types that aren't CSE'd, just act as if no identical node 1143 // already exists. 1144 if (!doNotCSE(N)) { 1145 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1146 if (Existing != N) { 1147 // If there was already an existing matching node, use ReplaceAllUsesWith 1148 // to replace the dead one with the existing one. This can cause 1149 // recursive merging of other unrelated nodes down the line. 1150 ReplaceAllUsesWith(N, Existing); 1151 1152 // N is now dead. Inform the listeners and delete it. 1153 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1154 DUL->NodeDeleted(N, Existing); 1155 DeleteNodeNotInCSEMaps(N); 1156 return; 1157 } 1158 } 1159 1160 // If the node doesn't already exist, we updated it. Inform listeners. 1161 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1162 DUL->NodeUpdated(N); 1163 } 1164 1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1166 /// were replaced with those specified. If this node is never memoized, 1167 /// return null, otherwise return a pointer to the slot it would take. If a 1168 /// node already exists with these operands, the slot will be non-null. 1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1170 void *&InsertPos) { 1171 if (doNotCSE(N)) 1172 return nullptr; 1173 1174 SDValue Ops[] = { Op }; 1175 FoldingSetNodeID ID; 1176 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1177 AddNodeIDCustom(ID, N); 1178 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1179 if (Node) 1180 Node->intersectFlagsWith(N->getFlags()); 1181 return Node; 1182 } 1183 1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1185 /// were replaced with those specified. If this node is never memoized, 1186 /// return null, otherwise return a pointer to the slot it would take. If a 1187 /// node already exists with these operands, the slot will be non-null. 1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1189 SDValue Op1, SDValue Op2, 1190 void *&InsertPos) { 1191 if (doNotCSE(N)) 1192 return nullptr; 1193 1194 SDValue Ops[] = { Op1, Op2 }; 1195 FoldingSetNodeID ID; 1196 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1197 AddNodeIDCustom(ID, N); 1198 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1199 if (Node) 1200 Node->intersectFlagsWith(N->getFlags()); 1201 return Node; 1202 } 1203 1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1205 /// were replaced with those specified. If this node is never memoized, 1206 /// return null, otherwise return a pointer to the slot it would take. If a 1207 /// node already exists with these operands, the slot will be non-null. 1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1209 void *&InsertPos) { 1210 if (doNotCSE(N)) 1211 return nullptr; 1212 1213 FoldingSetNodeID ID; 1214 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1215 AddNodeIDCustom(ID, N); 1216 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1217 if (Node) 1218 Node->intersectFlagsWith(N->getFlags()); 1219 return Node; 1220 } 1221 1222 Align SelectionDAG::getEVTAlign(EVT VT) const { 1223 Type *Ty = VT == MVT::iPTR ? 1224 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1225 VT.getTypeForEVT(*getContext()); 1226 1227 return getDataLayout().getABITypeAlign(Ty); 1228 } 1229 1230 // EntryNode could meaningfully have debug info if we can find it... 1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1232 : TM(tm), OptLevel(OL), 1233 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1234 Root(getEntryNode()) { 1235 InsertNode(&EntryNode); 1236 DbgInfo = new SDDbgInfo(); 1237 } 1238 1239 void SelectionDAG::init(MachineFunction &NewMF, 1240 OptimizationRemarkEmitter &NewORE, 1241 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1242 LegacyDivergenceAnalysis * Divergence, 1243 ProfileSummaryInfo *PSIin, 1244 BlockFrequencyInfo *BFIin) { 1245 MF = &NewMF; 1246 SDAGISelPass = PassPtr; 1247 ORE = &NewORE; 1248 TLI = getSubtarget().getTargetLowering(); 1249 TSI = getSubtarget().getSelectionDAGInfo(); 1250 LibInfo = LibraryInfo; 1251 Context = &MF->getFunction().getContext(); 1252 DA = Divergence; 1253 PSI = PSIin; 1254 BFI = BFIin; 1255 } 1256 1257 SelectionDAG::~SelectionDAG() { 1258 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1259 allnodes_clear(); 1260 OperandRecycler.clear(OperandAllocator); 1261 delete DbgInfo; 1262 } 1263 1264 bool SelectionDAG::shouldOptForSize() const { 1265 return MF->getFunction().hasOptSize() || 1266 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1267 } 1268 1269 void SelectionDAG::allnodes_clear() { 1270 assert(&*AllNodes.begin() == &EntryNode); 1271 AllNodes.remove(AllNodes.begin()); 1272 while (!AllNodes.empty()) 1273 DeallocateNode(&AllNodes.front()); 1274 #ifndef NDEBUG 1275 NextPersistentId = 0; 1276 #endif 1277 } 1278 1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1280 void *&InsertPos) { 1281 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1282 if (N) { 1283 switch (N->getOpcode()) { 1284 default: break; 1285 case ISD::Constant: 1286 case ISD::ConstantFP: 1287 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1288 "debug location. Use another overload."); 1289 } 1290 } 1291 return N; 1292 } 1293 1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1295 const SDLoc &DL, void *&InsertPos) { 1296 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1297 if (N) { 1298 switch (N->getOpcode()) { 1299 case ISD::Constant: 1300 case ISD::ConstantFP: 1301 // Erase debug location from the node if the node is used at several 1302 // different places. Do not propagate one location to all uses as it 1303 // will cause a worse single stepping debugging experience. 1304 if (N->getDebugLoc() != DL.getDebugLoc()) 1305 N->setDebugLoc(DebugLoc()); 1306 break; 1307 default: 1308 // When the node's point of use is located earlier in the instruction 1309 // sequence than its prior point of use, update its debug info to the 1310 // earlier location. 1311 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1312 N->setDebugLoc(DL.getDebugLoc()); 1313 break; 1314 } 1315 } 1316 return N; 1317 } 1318 1319 void SelectionDAG::clear() { 1320 allnodes_clear(); 1321 OperandRecycler.clear(OperandAllocator); 1322 OperandAllocator.Reset(); 1323 CSEMap.clear(); 1324 1325 ExtendedValueTypeNodes.clear(); 1326 ExternalSymbols.clear(); 1327 TargetExternalSymbols.clear(); 1328 MCSymbols.clear(); 1329 SDCallSiteDbgInfo.clear(); 1330 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1331 static_cast<CondCodeSDNode*>(nullptr)); 1332 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1333 static_cast<SDNode*>(nullptr)); 1334 1335 EntryNode.UseList = nullptr; 1336 InsertNode(&EntryNode); 1337 Root = getEntryNode(); 1338 DbgInfo->clear(); 1339 } 1340 1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1342 return VT.bitsGT(Op.getValueType()) 1343 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1344 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1345 } 1346 1347 std::pair<SDValue, SDValue> 1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1349 const SDLoc &DL, EVT VT) { 1350 assert(!VT.bitsEq(Op.getValueType()) && 1351 "Strict no-op FP extend/round not allowed."); 1352 SDValue Res = 1353 VT.bitsGT(Op.getValueType()) 1354 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1355 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1356 {Chain, Op, getIntPtrConstant(0, DL)}); 1357 1358 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1359 } 1360 1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1362 return VT.bitsGT(Op.getValueType()) ? 1363 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1364 getNode(ISD::TRUNCATE, DL, VT, Op); 1365 } 1366 1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1368 return VT.bitsGT(Op.getValueType()) ? 1369 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1370 getNode(ISD::TRUNCATE, DL, VT, Op); 1371 } 1372 1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1374 return VT.bitsGT(Op.getValueType()) ? 1375 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1376 getNode(ISD::TRUNCATE, DL, VT, Op); 1377 } 1378 1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1380 EVT OpVT) { 1381 if (VT.bitsLE(Op.getValueType())) 1382 return getNode(ISD::TRUNCATE, SL, VT, Op); 1383 1384 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1385 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1386 } 1387 1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1389 EVT OpVT = Op.getValueType(); 1390 assert(VT.isInteger() && OpVT.isInteger() && 1391 "Cannot getZeroExtendInReg FP types"); 1392 assert(VT.isVector() == OpVT.isVector() && 1393 "getZeroExtendInReg type should be vector iff the operand " 1394 "type is vector!"); 1395 assert((!VT.isVector() || 1396 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1397 "Vector element counts must match in getZeroExtendInReg"); 1398 assert(VT.bitsLE(OpVT) && "Not extending!"); 1399 if (OpVT == VT) 1400 return Op; 1401 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1402 VT.getScalarSizeInBits()); 1403 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1404 } 1405 1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1407 // Only unsigned pointer semantics are supported right now. In the future this 1408 // might delegate to TLI to check pointer signedness. 1409 return getZExtOrTrunc(Op, DL, VT); 1410 } 1411 1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1413 // Only unsigned pointer semantics are supported right now. In the future this 1414 // might delegate to TLI to check pointer signedness. 1415 return getZeroExtendInReg(Op, DL, VT); 1416 } 1417 1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1420 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1421 } 1422 1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1424 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1425 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1426 } 1427 1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val, 1429 SDValue Mask, SDValue EVL, EVT VT) { 1430 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1431 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL); 1432 } 1433 1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1435 EVT OpVT) { 1436 if (!V) 1437 return getConstant(0, DL, VT); 1438 1439 switch (TLI->getBooleanContents(OpVT)) { 1440 case TargetLowering::ZeroOrOneBooleanContent: 1441 case TargetLowering::UndefinedBooleanContent: 1442 return getConstant(1, DL, VT); 1443 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1444 return getAllOnesConstant(DL, VT); 1445 } 1446 llvm_unreachable("Unexpected boolean content enum!"); 1447 } 1448 1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1450 bool isT, bool isO) { 1451 EVT EltVT = VT.getScalarType(); 1452 assert((EltVT.getSizeInBits() >= 64 || 1453 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1454 "getConstant with a uint64_t value that doesn't fit in the type!"); 1455 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1456 } 1457 1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1459 bool isT, bool isO) { 1460 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1461 } 1462 1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1464 EVT VT, bool isT, bool isO) { 1465 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1466 1467 EVT EltVT = VT.getScalarType(); 1468 const ConstantInt *Elt = &Val; 1469 1470 // In some cases the vector type is legal but the element type is illegal and 1471 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1472 // inserted value (the type does not need to match the vector element type). 1473 // Any extra bits introduced will be truncated away. 1474 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1475 TargetLowering::TypePromoteInteger) { 1476 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1477 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1478 Elt = ConstantInt::get(*getContext(), NewVal); 1479 } 1480 // In other cases the element type is illegal and needs to be expanded, for 1481 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1482 // the value into n parts and use a vector type with n-times the elements. 1483 // Then bitcast to the type requested. 1484 // Legalizing constants too early makes the DAGCombiner's job harder so we 1485 // only legalize if the DAG tells us we must produce legal types. 1486 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1487 TLI->getTypeAction(*getContext(), EltVT) == 1488 TargetLowering::TypeExpandInteger) { 1489 const APInt &NewVal = Elt->getValue(); 1490 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1491 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1492 1493 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1494 if (VT.isScalableVector()) { 1495 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1496 "Can only handle an even split!"); 1497 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1498 1499 SmallVector<SDValue, 2> ScalarParts; 1500 for (unsigned i = 0; i != Parts; ++i) 1501 ScalarParts.push_back(getConstant( 1502 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1503 ViaEltVT, isT, isO)); 1504 1505 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1506 } 1507 1508 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1509 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1510 1511 // Check the temporary vector is the correct size. If this fails then 1512 // getTypeToTransformTo() probably returned a type whose size (in bits) 1513 // isn't a power-of-2 factor of the requested type size. 1514 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1515 1516 SmallVector<SDValue, 2> EltParts; 1517 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1518 EltParts.push_back(getConstant( 1519 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1520 ViaEltVT, isT, isO)); 1521 1522 // EltParts is currently in little endian order. If we actually want 1523 // big-endian order then reverse it now. 1524 if (getDataLayout().isBigEndian()) 1525 std::reverse(EltParts.begin(), EltParts.end()); 1526 1527 // The elements must be reversed when the element order is different 1528 // to the endianness of the elements (because the BITCAST is itself a 1529 // vector shuffle in this situation). However, we do not need any code to 1530 // perform this reversal because getConstant() is producing a vector 1531 // splat. 1532 // This situation occurs in MIPS MSA. 1533 1534 SmallVector<SDValue, 8> Ops; 1535 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1536 llvm::append_range(Ops, EltParts); 1537 1538 SDValue V = 1539 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1540 return V; 1541 } 1542 1543 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1544 "APInt size does not match type size!"); 1545 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1546 FoldingSetNodeID ID; 1547 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1548 ID.AddPointer(Elt); 1549 ID.AddBoolean(isO); 1550 void *IP = nullptr; 1551 SDNode *N = nullptr; 1552 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1553 if (!VT.isVector()) 1554 return SDValue(N, 0); 1555 1556 if (!N) { 1557 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1558 CSEMap.InsertNode(N, IP); 1559 InsertNode(N); 1560 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1561 } 1562 1563 SDValue Result(N, 0); 1564 if (VT.isScalableVector()) 1565 Result = getSplatVector(VT, DL, Result); 1566 else if (VT.isVector()) 1567 Result = getSplatBuildVector(VT, DL, Result); 1568 1569 return Result; 1570 } 1571 1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1573 bool isTarget) { 1574 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1575 } 1576 1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1578 const SDLoc &DL, bool LegalTypes) { 1579 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1580 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1581 return getConstant(Val, DL, ShiftVT); 1582 } 1583 1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1585 bool isTarget) { 1586 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1587 } 1588 1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1590 bool isTarget) { 1591 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1592 } 1593 1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1595 EVT VT, bool isTarget) { 1596 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1597 1598 EVT EltVT = VT.getScalarType(); 1599 1600 // Do the map lookup using the actual bit pattern for the floating point 1601 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1602 // we don't have issues with SNANs. 1603 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1604 FoldingSetNodeID ID; 1605 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1606 ID.AddPointer(&V); 1607 void *IP = nullptr; 1608 SDNode *N = nullptr; 1609 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1610 if (!VT.isVector()) 1611 return SDValue(N, 0); 1612 1613 if (!N) { 1614 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1615 CSEMap.InsertNode(N, IP); 1616 InsertNode(N); 1617 } 1618 1619 SDValue Result(N, 0); 1620 if (VT.isScalableVector()) 1621 Result = getSplatVector(VT, DL, Result); 1622 else if (VT.isVector()) 1623 Result = getSplatBuildVector(VT, DL, Result); 1624 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1625 return Result; 1626 } 1627 1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1629 bool isTarget) { 1630 EVT EltVT = VT.getScalarType(); 1631 if (EltVT == MVT::f32) 1632 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1633 if (EltVT == MVT::f64) 1634 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1635 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1636 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1637 bool Ignored; 1638 APFloat APF = APFloat(Val); 1639 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1640 &Ignored); 1641 return getConstantFP(APF, DL, VT, isTarget); 1642 } 1643 llvm_unreachable("Unsupported type in getConstantFP"); 1644 } 1645 1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1647 EVT VT, int64_t Offset, bool isTargetGA, 1648 unsigned TargetFlags) { 1649 assert((TargetFlags == 0 || isTargetGA) && 1650 "Cannot set target flags on target-independent globals"); 1651 1652 // Truncate (with sign-extension) the offset value to the pointer size. 1653 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1654 if (BitWidth < 64) 1655 Offset = SignExtend64(Offset, BitWidth); 1656 1657 unsigned Opc; 1658 if (GV->isThreadLocal()) 1659 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1660 else 1661 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1662 1663 FoldingSetNodeID ID; 1664 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1665 ID.AddPointer(GV); 1666 ID.AddInteger(Offset); 1667 ID.AddInteger(TargetFlags); 1668 void *IP = nullptr; 1669 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1670 return SDValue(E, 0); 1671 1672 auto *N = newSDNode<GlobalAddressSDNode>( 1673 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1674 CSEMap.InsertNode(N, IP); 1675 InsertNode(N); 1676 return SDValue(N, 0); 1677 } 1678 1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1680 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1681 FoldingSetNodeID ID; 1682 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1683 ID.AddInteger(FI); 1684 void *IP = nullptr; 1685 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1686 return SDValue(E, 0); 1687 1688 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1689 CSEMap.InsertNode(N, IP); 1690 InsertNode(N); 1691 return SDValue(N, 0); 1692 } 1693 1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1695 unsigned TargetFlags) { 1696 assert((TargetFlags == 0 || isTarget) && 1697 "Cannot set target flags on target-independent jump tables"); 1698 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1699 FoldingSetNodeID ID; 1700 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1701 ID.AddInteger(JTI); 1702 ID.AddInteger(TargetFlags); 1703 void *IP = nullptr; 1704 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1705 return SDValue(E, 0); 1706 1707 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1708 CSEMap.InsertNode(N, IP); 1709 InsertNode(N); 1710 return SDValue(N, 0); 1711 } 1712 1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1714 MaybeAlign Alignment, int Offset, 1715 bool isTarget, unsigned TargetFlags) { 1716 assert((TargetFlags == 0 || isTarget) && 1717 "Cannot set target flags on target-independent globals"); 1718 if (!Alignment) 1719 Alignment = shouldOptForSize() 1720 ? getDataLayout().getABITypeAlign(C->getType()) 1721 : getDataLayout().getPrefTypeAlign(C->getType()); 1722 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1723 FoldingSetNodeID ID; 1724 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1725 ID.AddInteger(Alignment->value()); 1726 ID.AddInteger(Offset); 1727 ID.AddPointer(C); 1728 ID.AddInteger(TargetFlags); 1729 void *IP = nullptr; 1730 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1731 return SDValue(E, 0); 1732 1733 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1734 TargetFlags); 1735 CSEMap.InsertNode(N, IP); 1736 InsertNode(N); 1737 SDValue V = SDValue(N, 0); 1738 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1739 return V; 1740 } 1741 1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1743 MaybeAlign Alignment, int Offset, 1744 bool isTarget, unsigned TargetFlags) { 1745 assert((TargetFlags == 0 || isTarget) && 1746 "Cannot set target flags on target-independent globals"); 1747 if (!Alignment) 1748 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1749 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1750 FoldingSetNodeID ID; 1751 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1752 ID.AddInteger(Alignment->value()); 1753 ID.AddInteger(Offset); 1754 C->addSelectionDAGCSEId(ID); 1755 ID.AddInteger(TargetFlags); 1756 void *IP = nullptr; 1757 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1758 return SDValue(E, 0); 1759 1760 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1761 TargetFlags); 1762 CSEMap.InsertNode(N, IP); 1763 InsertNode(N); 1764 return SDValue(N, 0); 1765 } 1766 1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1768 unsigned TargetFlags) { 1769 FoldingSetNodeID ID; 1770 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1771 ID.AddInteger(Index); 1772 ID.AddInteger(Offset); 1773 ID.AddInteger(TargetFlags); 1774 void *IP = nullptr; 1775 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1776 return SDValue(E, 0); 1777 1778 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1779 CSEMap.InsertNode(N, IP); 1780 InsertNode(N); 1781 return SDValue(N, 0); 1782 } 1783 1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1785 FoldingSetNodeID ID; 1786 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1787 ID.AddPointer(MBB); 1788 void *IP = nullptr; 1789 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1790 return SDValue(E, 0); 1791 1792 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1793 CSEMap.InsertNode(N, IP); 1794 InsertNode(N); 1795 return SDValue(N, 0); 1796 } 1797 1798 SDValue SelectionDAG::getValueType(EVT VT) { 1799 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1800 ValueTypeNodes.size()) 1801 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1802 1803 SDNode *&N = VT.isExtended() ? 1804 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1805 1806 if (N) return SDValue(N, 0); 1807 N = newSDNode<VTSDNode>(VT); 1808 InsertNode(N); 1809 return SDValue(N, 0); 1810 } 1811 1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1813 SDNode *&N = ExternalSymbols[Sym]; 1814 if (N) return SDValue(N, 0); 1815 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1816 InsertNode(N); 1817 return SDValue(N, 0); 1818 } 1819 1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1821 SDNode *&N = MCSymbols[Sym]; 1822 if (N) 1823 return SDValue(N, 0); 1824 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1825 InsertNode(N); 1826 return SDValue(N, 0); 1827 } 1828 1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1830 unsigned TargetFlags) { 1831 SDNode *&N = 1832 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1833 if (N) return SDValue(N, 0); 1834 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1835 InsertNode(N); 1836 return SDValue(N, 0); 1837 } 1838 1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1840 if ((unsigned)Cond >= CondCodeNodes.size()) 1841 CondCodeNodes.resize(Cond+1); 1842 1843 if (!CondCodeNodes[Cond]) { 1844 auto *N = newSDNode<CondCodeSDNode>(Cond); 1845 CondCodeNodes[Cond] = N; 1846 InsertNode(N); 1847 } 1848 1849 return SDValue(CondCodeNodes[Cond], 0); 1850 } 1851 1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1853 APInt One(ResVT.getScalarSizeInBits(), 1); 1854 return getStepVector(DL, ResVT, One); 1855 } 1856 1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1858 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1859 if (ResVT.isScalableVector()) 1860 return getNode( 1861 ISD::STEP_VECTOR, DL, ResVT, 1862 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1863 1864 SmallVector<SDValue, 16> OpsStepConstants; 1865 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1866 OpsStepConstants.push_back( 1867 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1868 return getBuildVector(ResVT, DL, OpsStepConstants); 1869 } 1870 1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1874 std::swap(N1, N2); 1875 ShuffleVectorSDNode::commuteMask(M); 1876 } 1877 1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1879 SDValue N2, ArrayRef<int> Mask) { 1880 assert(VT.getVectorNumElements() == Mask.size() && 1881 "Must have the same number of vector elements as mask elements!"); 1882 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1883 "Invalid VECTOR_SHUFFLE"); 1884 1885 // Canonicalize shuffle undef, undef -> undef 1886 if (N1.isUndef() && N2.isUndef()) 1887 return getUNDEF(VT); 1888 1889 // Validate that all indices in Mask are within the range of the elements 1890 // input to the shuffle. 1891 int NElts = Mask.size(); 1892 assert(llvm::all_of(Mask, 1893 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1894 "Index out of range"); 1895 1896 // Copy the mask so we can do any needed cleanup. 1897 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1898 1899 // Canonicalize shuffle v, v -> v, undef 1900 if (N1 == N2) { 1901 N2 = getUNDEF(VT); 1902 for (int i = 0; i != NElts; ++i) 1903 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1904 } 1905 1906 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1907 if (N1.isUndef()) 1908 commuteShuffle(N1, N2, MaskVec); 1909 1910 if (TLI->hasVectorBlend()) { 1911 // If shuffling a splat, try to blend the splat instead. We do this here so 1912 // that even when this arises during lowering we don't have to re-handle it. 1913 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1914 BitVector UndefElements; 1915 SDValue Splat = BV->getSplatValue(&UndefElements); 1916 if (!Splat) 1917 return; 1918 1919 for (int i = 0; i < NElts; ++i) { 1920 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1921 continue; 1922 1923 // If this input comes from undef, mark it as such. 1924 if (UndefElements[MaskVec[i] - Offset]) { 1925 MaskVec[i] = -1; 1926 continue; 1927 } 1928 1929 // If we can blend a non-undef lane, use that instead. 1930 if (!UndefElements[i]) 1931 MaskVec[i] = i + Offset; 1932 } 1933 }; 1934 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1935 BlendSplat(N1BV, 0); 1936 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1937 BlendSplat(N2BV, NElts); 1938 } 1939 1940 // Canonicalize all index into lhs, -> shuffle lhs, undef 1941 // Canonicalize all index into rhs, -> shuffle rhs, undef 1942 bool AllLHS = true, AllRHS = true; 1943 bool N2Undef = N2.isUndef(); 1944 for (int i = 0; i != NElts; ++i) { 1945 if (MaskVec[i] >= NElts) { 1946 if (N2Undef) 1947 MaskVec[i] = -1; 1948 else 1949 AllLHS = false; 1950 } else if (MaskVec[i] >= 0) { 1951 AllRHS = false; 1952 } 1953 } 1954 if (AllLHS && AllRHS) 1955 return getUNDEF(VT); 1956 if (AllLHS && !N2Undef) 1957 N2 = getUNDEF(VT); 1958 if (AllRHS) { 1959 N1 = getUNDEF(VT); 1960 commuteShuffle(N1, N2, MaskVec); 1961 } 1962 // Reset our undef status after accounting for the mask. 1963 N2Undef = N2.isUndef(); 1964 // Re-check whether both sides ended up undef. 1965 if (N1.isUndef() && N2Undef) 1966 return getUNDEF(VT); 1967 1968 // If Identity shuffle return that node. 1969 bool Identity = true, AllSame = true; 1970 for (int i = 0; i != NElts; ++i) { 1971 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1972 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1973 } 1974 if (Identity && NElts) 1975 return N1; 1976 1977 // Shuffling a constant splat doesn't change the result. 1978 if (N2Undef) { 1979 SDValue V = N1; 1980 1981 // Look through any bitcasts. We check that these don't change the number 1982 // (and size) of elements and just changes their types. 1983 while (V.getOpcode() == ISD::BITCAST) 1984 V = V->getOperand(0); 1985 1986 // A splat should always show up as a build vector node. 1987 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1988 BitVector UndefElements; 1989 SDValue Splat = BV->getSplatValue(&UndefElements); 1990 // If this is a splat of an undef, shuffling it is also undef. 1991 if (Splat && Splat.isUndef()) 1992 return getUNDEF(VT); 1993 1994 bool SameNumElts = 1995 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1996 1997 // We only have a splat which can skip shuffles if there is a splatted 1998 // value and no undef lanes rearranged by the shuffle. 1999 if (Splat && UndefElements.none()) { 2000 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 2001 // number of elements match or the value splatted is a zero constant. 2002 if (SameNumElts) 2003 return N1; 2004 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 2005 if (C->isZero()) 2006 return N1; 2007 } 2008 2009 // If the shuffle itself creates a splat, build the vector directly. 2010 if (AllSame && SameNumElts) { 2011 EVT BuildVT = BV->getValueType(0); 2012 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2013 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2014 2015 // We may have jumped through bitcasts, so the type of the 2016 // BUILD_VECTOR may not match the type of the shuffle. 2017 if (BuildVT != VT) 2018 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2019 return NewBV; 2020 } 2021 } 2022 } 2023 2024 FoldingSetNodeID ID; 2025 SDValue Ops[2] = { N1, N2 }; 2026 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2027 for (int i = 0; i != NElts; ++i) 2028 ID.AddInteger(MaskVec[i]); 2029 2030 void* IP = nullptr; 2031 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2032 return SDValue(E, 0); 2033 2034 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2035 // SDNode doesn't have access to it. This memory will be "leaked" when 2036 // the node is deallocated, but recovered when the NodeAllocator is released. 2037 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2038 llvm::copy(MaskVec, MaskAlloc); 2039 2040 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2041 dl.getDebugLoc(), MaskAlloc); 2042 createOperands(N, Ops); 2043 2044 CSEMap.InsertNode(N, IP); 2045 InsertNode(N); 2046 SDValue V = SDValue(N, 0); 2047 NewSDValueDbgMsg(V, "Creating new node: ", this); 2048 return V; 2049 } 2050 2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2052 EVT VT = SV.getValueType(0); 2053 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2054 ShuffleVectorSDNode::commuteMask(MaskVec); 2055 2056 SDValue Op0 = SV.getOperand(0); 2057 SDValue Op1 = SV.getOperand(1); 2058 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2059 } 2060 2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2062 FoldingSetNodeID ID; 2063 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2064 ID.AddInteger(RegNo); 2065 void *IP = nullptr; 2066 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2067 return SDValue(E, 0); 2068 2069 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2070 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2071 CSEMap.InsertNode(N, IP); 2072 InsertNode(N); 2073 return SDValue(N, 0); 2074 } 2075 2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2077 FoldingSetNodeID ID; 2078 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2079 ID.AddPointer(RegMask); 2080 void *IP = nullptr; 2081 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2082 return SDValue(E, 0); 2083 2084 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2085 CSEMap.InsertNode(N, IP); 2086 InsertNode(N); 2087 return SDValue(N, 0); 2088 } 2089 2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2091 MCSymbol *Label) { 2092 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2093 } 2094 2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2096 SDValue Root, MCSymbol *Label) { 2097 FoldingSetNodeID ID; 2098 SDValue Ops[] = { Root }; 2099 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2100 ID.AddPointer(Label); 2101 void *IP = nullptr; 2102 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2103 return SDValue(E, 0); 2104 2105 auto *N = 2106 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2107 createOperands(N, Ops); 2108 2109 CSEMap.InsertNode(N, IP); 2110 InsertNode(N); 2111 return SDValue(N, 0); 2112 } 2113 2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2115 int64_t Offset, bool isTarget, 2116 unsigned TargetFlags) { 2117 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2118 2119 FoldingSetNodeID ID; 2120 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2121 ID.AddPointer(BA); 2122 ID.AddInteger(Offset); 2123 ID.AddInteger(TargetFlags); 2124 void *IP = nullptr; 2125 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2126 return SDValue(E, 0); 2127 2128 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2129 CSEMap.InsertNode(N, IP); 2130 InsertNode(N); 2131 return SDValue(N, 0); 2132 } 2133 2134 SDValue SelectionDAG::getSrcValue(const Value *V) { 2135 FoldingSetNodeID ID; 2136 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2137 ID.AddPointer(V); 2138 2139 void *IP = nullptr; 2140 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2141 return SDValue(E, 0); 2142 2143 auto *N = newSDNode<SrcValueSDNode>(V); 2144 CSEMap.InsertNode(N, IP); 2145 InsertNode(N); 2146 return SDValue(N, 0); 2147 } 2148 2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2150 FoldingSetNodeID ID; 2151 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2152 ID.AddPointer(MD); 2153 2154 void *IP = nullptr; 2155 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2156 return SDValue(E, 0); 2157 2158 auto *N = newSDNode<MDNodeSDNode>(MD); 2159 CSEMap.InsertNode(N, IP); 2160 InsertNode(N); 2161 return SDValue(N, 0); 2162 } 2163 2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2165 if (VT == V.getValueType()) 2166 return V; 2167 2168 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2169 } 2170 2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2172 unsigned SrcAS, unsigned DestAS) { 2173 SDValue Ops[] = {Ptr}; 2174 FoldingSetNodeID ID; 2175 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2176 ID.AddInteger(SrcAS); 2177 ID.AddInteger(DestAS); 2178 2179 void *IP = nullptr; 2180 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2181 return SDValue(E, 0); 2182 2183 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2184 VT, SrcAS, DestAS); 2185 createOperands(N, Ops); 2186 2187 CSEMap.InsertNode(N, IP); 2188 InsertNode(N); 2189 return SDValue(N, 0); 2190 } 2191 2192 SDValue SelectionDAG::getFreeze(SDValue V) { 2193 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2194 } 2195 2196 /// getShiftAmountOperand - Return the specified value casted to 2197 /// the target's desired shift amount type. 2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2199 EVT OpTy = Op.getValueType(); 2200 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2201 if (OpTy == ShTy || OpTy.isVector()) return Op; 2202 2203 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2204 } 2205 2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2207 SDLoc dl(Node); 2208 const TargetLowering &TLI = getTargetLoweringInfo(); 2209 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2210 EVT VT = Node->getValueType(0); 2211 SDValue Tmp1 = Node->getOperand(0); 2212 SDValue Tmp2 = Node->getOperand(1); 2213 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2214 2215 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2216 Tmp2, MachinePointerInfo(V)); 2217 SDValue VAList = VAListLoad; 2218 2219 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2220 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2221 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2222 2223 VAList = 2224 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2225 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2226 } 2227 2228 // Increment the pointer, VAList, to the next vaarg 2229 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2230 getConstant(getDataLayout().getTypeAllocSize( 2231 VT.getTypeForEVT(*getContext())), 2232 dl, VAList.getValueType())); 2233 // Store the incremented VAList to the legalized pointer 2234 Tmp1 = 2235 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2236 // Load the actual argument out of the pointer VAList 2237 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2238 } 2239 2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2241 SDLoc dl(Node); 2242 const TargetLowering &TLI = getTargetLoweringInfo(); 2243 // This defaults to loading a pointer from the input and storing it to the 2244 // output, returning the chain. 2245 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2246 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2247 SDValue Tmp1 = 2248 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2249 Node->getOperand(2), MachinePointerInfo(VS)); 2250 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2251 MachinePointerInfo(VD)); 2252 } 2253 2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2255 const DataLayout &DL = getDataLayout(); 2256 Type *Ty = VT.getTypeForEVT(*getContext()); 2257 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2258 2259 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2260 return RedAlign; 2261 2262 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2263 const Align StackAlign = TFI->getStackAlign(); 2264 2265 // See if we can choose a smaller ABI alignment in cases where it's an 2266 // illegal vector type that will get broken down. 2267 if (RedAlign > StackAlign) { 2268 EVT IntermediateVT; 2269 MVT RegisterVT; 2270 unsigned NumIntermediates; 2271 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2272 NumIntermediates, RegisterVT); 2273 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2274 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2275 if (RedAlign2 < RedAlign) 2276 RedAlign = RedAlign2; 2277 } 2278 2279 return RedAlign; 2280 } 2281 2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2283 MachineFrameInfo &MFI = MF->getFrameInfo(); 2284 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2285 int StackID = 0; 2286 if (Bytes.isScalable()) 2287 StackID = TFI->getStackIDForScalableVectors(); 2288 // The stack id gives an indication of whether the object is scalable or 2289 // not, so it's safe to pass in the minimum size here. 2290 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2291 false, nullptr, StackID); 2292 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2293 } 2294 2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2296 Type *Ty = VT.getTypeForEVT(*getContext()); 2297 Align StackAlign = 2298 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2299 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2300 } 2301 2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2303 TypeSize VT1Size = VT1.getStoreSize(); 2304 TypeSize VT2Size = VT2.getStoreSize(); 2305 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2306 "Don't know how to choose the maximum size when creating a stack " 2307 "temporary"); 2308 TypeSize Bytes = 2309 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2310 2311 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2312 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2313 const DataLayout &DL = getDataLayout(); 2314 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2315 return CreateStackTemporary(Bytes, Align); 2316 } 2317 2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2319 ISD::CondCode Cond, const SDLoc &dl) { 2320 EVT OpVT = N1.getValueType(); 2321 2322 // These setcc operations always fold. 2323 switch (Cond) { 2324 default: break; 2325 case ISD::SETFALSE: 2326 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2327 case ISD::SETTRUE: 2328 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2329 2330 case ISD::SETOEQ: 2331 case ISD::SETOGT: 2332 case ISD::SETOGE: 2333 case ISD::SETOLT: 2334 case ISD::SETOLE: 2335 case ISD::SETONE: 2336 case ISD::SETO: 2337 case ISD::SETUO: 2338 case ISD::SETUEQ: 2339 case ISD::SETUNE: 2340 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2341 break; 2342 } 2343 2344 if (OpVT.isInteger()) { 2345 // For EQ and NE, we can always pick a value for the undef to make the 2346 // predicate pass or fail, so we can return undef. 2347 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2348 // icmp eq/ne X, undef -> undef. 2349 if ((N1.isUndef() || N2.isUndef()) && 2350 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2351 return getUNDEF(VT); 2352 2353 // If both operands are undef, we can return undef for int comparison. 2354 // icmp undef, undef -> undef. 2355 if (N1.isUndef() && N2.isUndef()) 2356 return getUNDEF(VT); 2357 2358 // icmp X, X -> true/false 2359 // icmp X, undef -> true/false because undef could be X. 2360 if (N1 == N2) 2361 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2362 } 2363 2364 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2365 const APInt &C2 = N2C->getAPIntValue(); 2366 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2367 const APInt &C1 = N1C->getAPIntValue(); 2368 2369 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2370 dl, VT, OpVT); 2371 } 2372 } 2373 2374 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2375 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2376 2377 if (N1CFP && N2CFP) { 2378 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2379 switch (Cond) { 2380 default: break; 2381 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2382 return getUNDEF(VT); 2383 LLVM_FALLTHROUGH; 2384 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2385 OpVT); 2386 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2387 return getUNDEF(VT); 2388 LLVM_FALLTHROUGH; 2389 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2390 R==APFloat::cmpLessThan, dl, VT, 2391 OpVT); 2392 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2393 return getUNDEF(VT); 2394 LLVM_FALLTHROUGH; 2395 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2396 OpVT); 2397 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2398 return getUNDEF(VT); 2399 LLVM_FALLTHROUGH; 2400 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2401 VT, OpVT); 2402 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2403 return getUNDEF(VT); 2404 LLVM_FALLTHROUGH; 2405 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2406 R==APFloat::cmpEqual, dl, VT, 2407 OpVT); 2408 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2409 return getUNDEF(VT); 2410 LLVM_FALLTHROUGH; 2411 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2412 R==APFloat::cmpEqual, dl, VT, OpVT); 2413 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2414 OpVT); 2415 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2416 OpVT); 2417 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2418 R==APFloat::cmpEqual, dl, VT, 2419 OpVT); 2420 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2421 OpVT); 2422 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2423 R==APFloat::cmpLessThan, dl, VT, 2424 OpVT); 2425 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2426 R==APFloat::cmpUnordered, dl, VT, 2427 OpVT); 2428 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2429 VT, OpVT); 2430 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2431 OpVT); 2432 } 2433 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2434 // Ensure that the constant occurs on the RHS. 2435 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2436 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2437 return SDValue(); 2438 return getSetCC(dl, VT, N2, N1, SwappedCond); 2439 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2440 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2441 // If an operand is known to be a nan (or undef that could be a nan), we can 2442 // fold it. 2443 // Choosing NaN for the undef will always make unordered comparison succeed 2444 // and ordered comparison fails. 2445 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2446 switch (ISD::getUnorderedFlavor(Cond)) { 2447 default: 2448 llvm_unreachable("Unknown flavor!"); 2449 case 0: // Known false. 2450 return getBoolConstant(false, dl, VT, OpVT); 2451 case 1: // Known true. 2452 return getBoolConstant(true, dl, VT, OpVT); 2453 case 2: // Undefined. 2454 return getUNDEF(VT); 2455 } 2456 } 2457 2458 // Could not fold it. 2459 return SDValue(); 2460 } 2461 2462 /// See if the specified operand can be simplified with the knowledge that only 2463 /// the bits specified by DemandedBits are used. 2464 /// TODO: really we should be making this into the DAG equivalent of 2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2467 EVT VT = V.getValueType(); 2468 2469 if (VT.isScalableVector()) 2470 return SDValue(); 2471 2472 switch (V.getOpcode()) { 2473 default: 2474 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, *this); 2475 case ISD::Constant: { 2476 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2477 APInt NewVal = CVal & DemandedBits; 2478 if (NewVal != CVal) 2479 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2480 break; 2481 } 2482 case ISD::SRL: 2483 // Only look at single-use SRLs. 2484 if (!V.getNode()->hasOneUse()) 2485 break; 2486 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2487 // See if we can recursively simplify the LHS. 2488 unsigned Amt = RHSC->getZExtValue(); 2489 2490 // Watch out for shift count overflow though. 2491 if (Amt >= DemandedBits.getBitWidth()) 2492 break; 2493 APInt SrcDemandedBits = DemandedBits << Amt; 2494 if (SDValue SimplifyLHS = TLI->SimplifyMultipleUseDemandedBits( 2495 V.getOperand(0), SrcDemandedBits, *this)) 2496 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2497 V.getOperand(1)); 2498 } 2499 break; 2500 } 2501 return SDValue(); 2502 } 2503 2504 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2505 /// use this predicate to simplify operations downstream. 2506 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2507 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2508 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2509 } 2510 2511 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2512 /// this predicate to simplify operations downstream. Mask is known to be zero 2513 /// for bits that V cannot have. 2514 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2515 unsigned Depth) const { 2516 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2517 } 2518 2519 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2520 /// DemandedElts. We use this predicate to simplify operations downstream. 2521 /// Mask is known to be zero for bits that V cannot have. 2522 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2523 const APInt &DemandedElts, 2524 unsigned Depth) const { 2525 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2526 } 2527 2528 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in 2529 /// DemandedElts. We use this predicate to simplify operations downstream. 2530 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts, 2531 unsigned Depth /* = 0 */) const { 2532 APInt Mask = APInt::getAllOnes(V.getScalarValueSizeInBits()); 2533 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2534 } 2535 2536 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2537 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2538 unsigned Depth) const { 2539 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2540 } 2541 2542 /// isSplatValue - Return true if the vector V has the same value 2543 /// across all DemandedElts. For scalable vectors it does not make 2544 /// sense to specify which elements are demanded or undefined, therefore 2545 /// they are simply ignored. 2546 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2547 APInt &UndefElts, unsigned Depth) const { 2548 unsigned Opcode = V.getOpcode(); 2549 EVT VT = V.getValueType(); 2550 assert(VT.isVector() && "Vector type expected"); 2551 2552 if (!VT.isScalableVector() && !DemandedElts) 2553 return false; // No demanded elts, better to assume we don't know anything. 2554 2555 if (Depth >= MaxRecursionDepth) 2556 return false; // Limit search depth. 2557 2558 // Deal with some common cases here that work for both fixed and scalable 2559 // vector types. 2560 switch (Opcode) { 2561 case ISD::SPLAT_VECTOR: 2562 UndefElts = V.getOperand(0).isUndef() 2563 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2564 : APInt(DemandedElts.getBitWidth(), 0); 2565 return true; 2566 case ISD::ADD: 2567 case ISD::SUB: 2568 case ISD::AND: 2569 case ISD::XOR: 2570 case ISD::OR: { 2571 APInt UndefLHS, UndefRHS; 2572 SDValue LHS = V.getOperand(0); 2573 SDValue RHS = V.getOperand(1); 2574 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2575 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2576 UndefElts = UndefLHS | UndefRHS; 2577 return true; 2578 } 2579 return false; 2580 } 2581 case ISD::ABS: 2582 case ISD::TRUNCATE: 2583 case ISD::SIGN_EXTEND: 2584 case ISD::ZERO_EXTEND: 2585 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2586 default: 2587 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2588 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2589 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth); 2590 break; 2591 } 2592 2593 // We don't support other cases than those above for scalable vectors at 2594 // the moment. 2595 if (VT.isScalableVector()) 2596 return false; 2597 2598 unsigned NumElts = VT.getVectorNumElements(); 2599 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2600 UndefElts = APInt::getZero(NumElts); 2601 2602 switch (Opcode) { 2603 case ISD::BUILD_VECTOR: { 2604 SDValue Scl; 2605 for (unsigned i = 0; i != NumElts; ++i) { 2606 SDValue Op = V.getOperand(i); 2607 if (Op.isUndef()) { 2608 UndefElts.setBit(i); 2609 continue; 2610 } 2611 if (!DemandedElts[i]) 2612 continue; 2613 if (Scl && Scl != Op) 2614 return false; 2615 Scl = Op; 2616 } 2617 return true; 2618 } 2619 case ISD::VECTOR_SHUFFLE: { 2620 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2621 APInt DemandedLHS = APInt::getNullValue(NumElts); 2622 APInt DemandedRHS = APInt::getNullValue(NumElts); 2623 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2624 for (int i = 0; i != (int)NumElts; ++i) { 2625 int M = Mask[i]; 2626 if (M < 0) { 2627 UndefElts.setBit(i); 2628 continue; 2629 } 2630 if (!DemandedElts[i]) 2631 continue; 2632 if (M < (int)NumElts) 2633 DemandedLHS.setBit(M); 2634 else 2635 DemandedRHS.setBit(M - NumElts); 2636 } 2637 2638 // If we aren't demanding either op, assume there's no splat. 2639 // If we are demanding both ops, assume there's no splat. 2640 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2641 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2642 return false; 2643 2644 // See if the demanded elts of the source op is a splat or we only demand 2645 // one element, which should always be a splat. 2646 // TODO: Handle source ops splats with undefs. 2647 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2648 APInt SrcUndefs; 2649 return (SrcElts.countPopulation() == 1) || 2650 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2651 (SrcElts & SrcUndefs).isZero()); 2652 }; 2653 if (!DemandedLHS.isZero()) 2654 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2655 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2656 } 2657 case ISD::EXTRACT_SUBVECTOR: { 2658 // Offset the demanded elts by the subvector index. 2659 SDValue Src = V.getOperand(0); 2660 // We don't support scalable vectors at the moment. 2661 if (Src.getValueType().isScalableVector()) 2662 return false; 2663 uint64_t Idx = V.getConstantOperandVal(1); 2664 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2665 APInt UndefSrcElts; 2666 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 2667 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2668 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2669 return true; 2670 } 2671 break; 2672 } 2673 case ISD::ANY_EXTEND_VECTOR_INREG: 2674 case ISD::SIGN_EXTEND_VECTOR_INREG: 2675 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2676 // Widen the demanded elts by the src element count. 2677 SDValue Src = V.getOperand(0); 2678 // We don't support scalable vectors at the moment. 2679 if (Src.getValueType().isScalableVector()) 2680 return false; 2681 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2682 APInt UndefSrcElts; 2683 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 2684 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2685 UndefElts = UndefSrcElts.trunc(NumElts); 2686 return true; 2687 } 2688 break; 2689 } 2690 case ISD::BITCAST: { 2691 SDValue Src = V.getOperand(0); 2692 EVT SrcVT = Src.getValueType(); 2693 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2694 unsigned BitWidth = VT.getScalarSizeInBits(); 2695 2696 // Ignore bitcasts from unsupported types. 2697 // TODO: Add fp support? 2698 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2699 break; 2700 2701 // Bitcast 'small element' vector to 'large element' vector. 2702 if ((BitWidth % SrcBitWidth) == 0) { 2703 // See if each sub element is a splat. 2704 unsigned Scale = BitWidth / SrcBitWidth; 2705 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2706 APInt ScaledDemandedElts = 2707 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2708 for (unsigned I = 0; I != Scale; ++I) { 2709 APInt SubUndefElts; 2710 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2711 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2712 SubDemandedElts &= ScaledDemandedElts; 2713 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2714 return false; 2715 // TODO: Add support for merging sub undef elements. 2716 if (!SubUndefElts.isZero()) 2717 return false; 2718 } 2719 return true; 2720 } 2721 break; 2722 } 2723 } 2724 2725 return false; 2726 } 2727 2728 /// Helper wrapper to main isSplatValue function. 2729 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2730 EVT VT = V.getValueType(); 2731 assert(VT.isVector() && "Vector type expected"); 2732 2733 APInt UndefElts; 2734 APInt DemandedElts; 2735 2736 // For now we don't support this with scalable vectors. 2737 if (!VT.isScalableVector()) 2738 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2739 return isSplatValue(V, DemandedElts, UndefElts) && 2740 (AllowUndefs || !UndefElts); 2741 } 2742 2743 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2744 V = peekThroughExtractSubvectors(V); 2745 2746 EVT VT = V.getValueType(); 2747 unsigned Opcode = V.getOpcode(); 2748 switch (Opcode) { 2749 default: { 2750 APInt UndefElts; 2751 APInt DemandedElts; 2752 2753 if (!VT.isScalableVector()) 2754 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2755 2756 if (isSplatValue(V, DemandedElts, UndefElts)) { 2757 if (VT.isScalableVector()) { 2758 // DemandedElts and UndefElts are ignored for scalable vectors, since 2759 // the only supported cases are SPLAT_VECTOR nodes. 2760 SplatIdx = 0; 2761 } else { 2762 // Handle case where all demanded elements are UNDEF. 2763 if (DemandedElts.isSubsetOf(UndefElts)) { 2764 SplatIdx = 0; 2765 return getUNDEF(VT); 2766 } 2767 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2768 } 2769 return V; 2770 } 2771 break; 2772 } 2773 case ISD::SPLAT_VECTOR: 2774 SplatIdx = 0; 2775 return V; 2776 case ISD::VECTOR_SHUFFLE: { 2777 if (VT.isScalableVector()) 2778 return SDValue(); 2779 2780 // Check if this is a shuffle node doing a splat. 2781 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2782 // getTargetVShiftNode currently struggles without the splat source. 2783 auto *SVN = cast<ShuffleVectorSDNode>(V); 2784 if (!SVN->isSplat()) 2785 break; 2786 int Idx = SVN->getSplatIndex(); 2787 int NumElts = V.getValueType().getVectorNumElements(); 2788 SplatIdx = Idx % NumElts; 2789 return V.getOperand(Idx / NumElts); 2790 } 2791 } 2792 2793 return SDValue(); 2794 } 2795 2796 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2797 int SplatIdx; 2798 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2799 EVT SVT = SrcVector.getValueType().getScalarType(); 2800 EVT LegalSVT = SVT; 2801 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2802 if (!SVT.isInteger()) 2803 return SDValue(); 2804 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2805 if (LegalSVT.bitsLT(SVT)) 2806 return SDValue(); 2807 } 2808 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2809 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2810 } 2811 return SDValue(); 2812 } 2813 2814 const APInt * 2815 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2816 const APInt &DemandedElts) const { 2817 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2818 V.getOpcode() == ISD::SRA) && 2819 "Unknown shift node"); 2820 unsigned BitWidth = V.getScalarValueSizeInBits(); 2821 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2822 // Shifting more than the bitwidth is not valid. 2823 const APInt &ShAmt = SA->getAPIntValue(); 2824 if (ShAmt.ult(BitWidth)) 2825 return &ShAmt; 2826 } 2827 return nullptr; 2828 } 2829 2830 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2831 SDValue V, const APInt &DemandedElts) const { 2832 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2833 V.getOpcode() == ISD::SRA) && 2834 "Unknown shift node"); 2835 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2836 return ValidAmt; 2837 unsigned BitWidth = V.getScalarValueSizeInBits(); 2838 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2839 if (!BV) 2840 return nullptr; 2841 const APInt *MinShAmt = nullptr; 2842 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2843 if (!DemandedElts[i]) 2844 continue; 2845 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2846 if (!SA) 2847 return nullptr; 2848 // Shifting more than the bitwidth is not valid. 2849 const APInt &ShAmt = SA->getAPIntValue(); 2850 if (ShAmt.uge(BitWidth)) 2851 return nullptr; 2852 if (MinShAmt && MinShAmt->ule(ShAmt)) 2853 continue; 2854 MinShAmt = &ShAmt; 2855 } 2856 return MinShAmt; 2857 } 2858 2859 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2860 SDValue V, const APInt &DemandedElts) const { 2861 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2862 V.getOpcode() == ISD::SRA) && 2863 "Unknown shift node"); 2864 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2865 return ValidAmt; 2866 unsigned BitWidth = V.getScalarValueSizeInBits(); 2867 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2868 if (!BV) 2869 return nullptr; 2870 const APInt *MaxShAmt = nullptr; 2871 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2872 if (!DemandedElts[i]) 2873 continue; 2874 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2875 if (!SA) 2876 return nullptr; 2877 // Shifting more than the bitwidth is not valid. 2878 const APInt &ShAmt = SA->getAPIntValue(); 2879 if (ShAmt.uge(BitWidth)) 2880 return nullptr; 2881 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2882 continue; 2883 MaxShAmt = &ShAmt; 2884 } 2885 return MaxShAmt; 2886 } 2887 2888 /// Determine which bits of Op are known to be either zero or one and return 2889 /// them in Known. For vectors, the known bits are those that are shared by 2890 /// every vector element. 2891 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2892 EVT VT = Op.getValueType(); 2893 2894 // TOOD: Until we have a plan for how to represent demanded elements for 2895 // scalable vectors, we can just bail out for now. 2896 if (Op.getValueType().isScalableVector()) { 2897 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2898 return KnownBits(BitWidth); 2899 } 2900 2901 APInt DemandedElts = VT.isVector() 2902 ? APInt::getAllOnes(VT.getVectorNumElements()) 2903 : APInt(1, 1); 2904 return computeKnownBits(Op, DemandedElts, Depth); 2905 } 2906 2907 /// Determine which bits of Op are known to be either zero or one and return 2908 /// them in Known. The DemandedElts argument allows us to only collect the known 2909 /// bits that are shared by the requested vector elements. 2910 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2911 unsigned Depth) const { 2912 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2913 2914 KnownBits Known(BitWidth); // Don't know anything. 2915 2916 // TOOD: Until we have a plan for how to represent demanded elements for 2917 // scalable vectors, we can just bail out for now. 2918 if (Op.getValueType().isScalableVector()) 2919 return Known; 2920 2921 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2922 // We know all of the bits for a constant! 2923 return KnownBits::makeConstant(C->getAPIntValue()); 2924 } 2925 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2926 // We know all of the bits for a constant fp! 2927 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2928 } 2929 2930 if (Depth >= MaxRecursionDepth) 2931 return Known; // Limit search depth. 2932 2933 KnownBits Known2; 2934 unsigned NumElts = DemandedElts.getBitWidth(); 2935 assert((!Op.getValueType().isVector() || 2936 NumElts == Op.getValueType().getVectorNumElements()) && 2937 "Unexpected vector size"); 2938 2939 if (!DemandedElts) 2940 return Known; // No demanded elts, better to assume we don't know anything. 2941 2942 unsigned Opcode = Op.getOpcode(); 2943 switch (Opcode) { 2944 case ISD::MERGE_VALUES: 2945 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts, 2946 Depth + 1); 2947 case ISD::BUILD_VECTOR: 2948 // Collect the known bits that are shared by every demanded vector element. 2949 Known.Zero.setAllBits(); Known.One.setAllBits(); 2950 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2951 if (!DemandedElts[i]) 2952 continue; 2953 2954 SDValue SrcOp = Op.getOperand(i); 2955 Known2 = computeKnownBits(SrcOp, Depth + 1); 2956 2957 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2958 if (SrcOp.getValueSizeInBits() != BitWidth) { 2959 assert(SrcOp.getValueSizeInBits() > BitWidth && 2960 "Expected BUILD_VECTOR implicit truncation"); 2961 Known2 = Known2.trunc(BitWidth); 2962 } 2963 2964 // Known bits are the values that are shared by every demanded element. 2965 Known = KnownBits::commonBits(Known, Known2); 2966 2967 // If we don't know any bits, early out. 2968 if (Known.isUnknown()) 2969 break; 2970 } 2971 break; 2972 case ISD::VECTOR_SHUFFLE: { 2973 // Collect the known bits that are shared by every vector element referenced 2974 // by the shuffle. 2975 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2976 Known.Zero.setAllBits(); Known.One.setAllBits(); 2977 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2978 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2979 for (unsigned i = 0; i != NumElts; ++i) { 2980 if (!DemandedElts[i]) 2981 continue; 2982 2983 int M = SVN->getMaskElt(i); 2984 if (M < 0) { 2985 // For UNDEF elements, we don't know anything about the common state of 2986 // the shuffle result. 2987 Known.resetAll(); 2988 DemandedLHS.clearAllBits(); 2989 DemandedRHS.clearAllBits(); 2990 break; 2991 } 2992 2993 if ((unsigned)M < NumElts) 2994 DemandedLHS.setBit((unsigned)M % NumElts); 2995 else 2996 DemandedRHS.setBit((unsigned)M % NumElts); 2997 } 2998 // Known bits are the values that are shared by every demanded element. 2999 if (!!DemandedLHS) { 3000 SDValue LHS = Op.getOperand(0); 3001 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 3002 Known = KnownBits::commonBits(Known, Known2); 3003 } 3004 // If we don't know any bits, early out. 3005 if (Known.isUnknown()) 3006 break; 3007 if (!!DemandedRHS) { 3008 SDValue RHS = Op.getOperand(1); 3009 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3010 Known = KnownBits::commonBits(Known, Known2); 3011 } 3012 break; 3013 } 3014 case ISD::CONCAT_VECTORS: { 3015 // Split DemandedElts and test each of the demanded subvectors. 3016 Known.Zero.setAllBits(); Known.One.setAllBits(); 3017 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3018 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3019 unsigned NumSubVectors = Op.getNumOperands(); 3020 for (unsigned i = 0; i != NumSubVectors; ++i) { 3021 APInt DemandedSub = 3022 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3023 if (!!DemandedSub) { 3024 SDValue Sub = Op.getOperand(i); 3025 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3026 Known = KnownBits::commonBits(Known, Known2); 3027 } 3028 // If we don't know any bits, early out. 3029 if (Known.isUnknown()) 3030 break; 3031 } 3032 break; 3033 } 3034 case ISD::INSERT_SUBVECTOR: { 3035 // Demand any elements from the subvector and the remainder from the src its 3036 // inserted into. 3037 SDValue Src = Op.getOperand(0); 3038 SDValue Sub = Op.getOperand(1); 3039 uint64_t Idx = Op.getConstantOperandVal(2); 3040 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3041 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3042 APInt DemandedSrcElts = DemandedElts; 3043 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3044 3045 Known.One.setAllBits(); 3046 Known.Zero.setAllBits(); 3047 if (!!DemandedSubElts) { 3048 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3049 if (Known.isUnknown()) 3050 break; // early-out. 3051 } 3052 if (!!DemandedSrcElts) { 3053 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3054 Known = KnownBits::commonBits(Known, Known2); 3055 } 3056 break; 3057 } 3058 case ISD::EXTRACT_SUBVECTOR: { 3059 // Offset the demanded elts by the subvector index. 3060 SDValue Src = Op.getOperand(0); 3061 // Bail until we can represent demanded elements for scalable vectors. 3062 if (Src.getValueType().isScalableVector()) 3063 break; 3064 uint64_t Idx = Op.getConstantOperandVal(1); 3065 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3066 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3067 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3068 break; 3069 } 3070 case ISD::SCALAR_TO_VECTOR: { 3071 // We know about scalar_to_vector as much as we know about it source, 3072 // which becomes the first element of otherwise unknown vector. 3073 if (DemandedElts != 1) 3074 break; 3075 3076 SDValue N0 = Op.getOperand(0); 3077 Known = computeKnownBits(N0, Depth + 1); 3078 if (N0.getValueSizeInBits() != BitWidth) 3079 Known = Known.trunc(BitWidth); 3080 3081 break; 3082 } 3083 case ISD::BITCAST: { 3084 SDValue N0 = Op.getOperand(0); 3085 EVT SubVT = N0.getValueType(); 3086 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3087 3088 // Ignore bitcasts from unsupported types. 3089 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3090 break; 3091 3092 // Fast handling of 'identity' bitcasts. 3093 if (BitWidth == SubBitWidth) { 3094 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3095 break; 3096 } 3097 3098 bool IsLE = getDataLayout().isLittleEndian(); 3099 3100 // Bitcast 'small element' vector to 'large element' scalar/vector. 3101 if ((BitWidth % SubBitWidth) == 0) { 3102 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3103 3104 // Collect known bits for the (larger) output by collecting the known 3105 // bits from each set of sub elements and shift these into place. 3106 // We need to separately call computeKnownBits for each set of 3107 // sub elements as the knownbits for each is likely to be different. 3108 unsigned SubScale = BitWidth / SubBitWidth; 3109 APInt SubDemandedElts(NumElts * SubScale, 0); 3110 for (unsigned i = 0; i != NumElts; ++i) 3111 if (DemandedElts[i]) 3112 SubDemandedElts.setBit(i * SubScale); 3113 3114 for (unsigned i = 0; i != SubScale; ++i) { 3115 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3116 Depth + 1); 3117 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3118 Known.insertBits(Known2, SubBitWidth * Shifts); 3119 } 3120 } 3121 3122 // Bitcast 'large element' scalar/vector to 'small element' vector. 3123 if ((SubBitWidth % BitWidth) == 0) { 3124 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3125 3126 // Collect known bits for the (smaller) output by collecting the known 3127 // bits from the overlapping larger input elements and extracting the 3128 // sub sections we actually care about. 3129 unsigned SubScale = SubBitWidth / BitWidth; 3130 APInt SubDemandedElts = 3131 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3132 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3133 3134 Known.Zero.setAllBits(); Known.One.setAllBits(); 3135 for (unsigned i = 0; i != NumElts; ++i) 3136 if (DemandedElts[i]) { 3137 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3138 unsigned Offset = (Shifts % SubScale) * BitWidth; 3139 Known = KnownBits::commonBits(Known, 3140 Known2.extractBits(BitWidth, Offset)); 3141 // If we don't know any bits, early out. 3142 if (Known.isUnknown()) 3143 break; 3144 } 3145 } 3146 break; 3147 } 3148 case ISD::AND: 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::OR: 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::XOR: 3161 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3162 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3163 3164 Known ^= Known2; 3165 break; 3166 case ISD::MUL: { 3167 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3168 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3169 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3170 // TODO: SelfMultiply can be poison, but not undef. 3171 if (SelfMultiply) 3172 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3173 Op.getOperand(0), DemandedElts, false, Depth + 1); 3174 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3175 3176 // If the multiplication is known not to overflow, the product of a number 3177 // with itself is non-negative. Only do this if we didn't already computed 3178 // the opposite value for the sign bit. 3179 if (Op->getFlags().hasNoSignedWrap() && 3180 Op.getOperand(0) == Op.getOperand(1) && 3181 !Known.isNegative()) 3182 Known.makeNonNegative(); 3183 break; 3184 } 3185 case ISD::MULHU: { 3186 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3187 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3188 Known = KnownBits::mulhu(Known, Known2); 3189 break; 3190 } 3191 case ISD::MULHS: { 3192 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3193 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3194 Known = KnownBits::mulhs(Known, Known2); 3195 break; 3196 } 3197 case ISD::UMUL_LOHI: { 3198 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3199 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3200 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3201 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3202 if (Op.getResNo() == 0) 3203 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3204 else 3205 Known = KnownBits::mulhu(Known, Known2); 3206 break; 3207 } 3208 case ISD::SMUL_LOHI: { 3209 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3210 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3211 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3212 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3213 if (Op.getResNo() == 0) 3214 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3215 else 3216 Known = KnownBits::mulhs(Known, Known2); 3217 break; 3218 } 3219 case ISD::AVGCEILU: { 3220 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3221 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3222 Known = Known.zext(BitWidth + 1); 3223 Known2 = Known2.zext(BitWidth + 1); 3224 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3225 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3226 Known = Known.extractBits(BitWidth, 1); 3227 break; 3228 } 3229 case ISD::SELECT: 3230 case ISD::VSELECT: 3231 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3232 // If we don't know any bits, early out. 3233 if (Known.isUnknown()) 3234 break; 3235 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3236 3237 // Only known if known in both the LHS and RHS. 3238 Known = KnownBits::commonBits(Known, Known2); 3239 break; 3240 case ISD::SELECT_CC: 3241 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3242 // If we don't know any bits, early out. 3243 if (Known.isUnknown()) 3244 break; 3245 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3246 3247 // Only known if known in both the LHS and RHS. 3248 Known = KnownBits::commonBits(Known, Known2); 3249 break; 3250 case ISD::SMULO: 3251 case ISD::UMULO: 3252 if (Op.getResNo() != 1) 3253 break; 3254 // The boolean result conforms to getBooleanContents. 3255 // If we know the result of a setcc has the top bits zero, use this info. 3256 // We know that we have an integer-based boolean since these operations 3257 // are only available for integer. 3258 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3259 TargetLowering::ZeroOrOneBooleanContent && 3260 BitWidth > 1) 3261 Known.Zero.setBitsFrom(1); 3262 break; 3263 case ISD::SETCC: 3264 case ISD::SETCCCARRY: 3265 case ISD::STRICT_FSETCC: 3266 case ISD::STRICT_FSETCCS: { 3267 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3268 // If we know the result of a setcc has the top bits zero, use this info. 3269 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3270 TargetLowering::ZeroOrOneBooleanContent && 3271 BitWidth > 1) 3272 Known.Zero.setBitsFrom(1); 3273 break; 3274 } 3275 case ISD::SHL: 3276 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3277 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3278 Known = KnownBits::shl(Known, Known2); 3279 3280 // Minimum shift low bits are known zero. 3281 if (const APInt *ShMinAmt = 3282 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3283 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3284 break; 3285 case ISD::SRL: 3286 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3287 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3288 Known = KnownBits::lshr(Known, Known2); 3289 3290 // Minimum shift high bits are known zero. 3291 if (const APInt *ShMinAmt = 3292 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3293 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3294 break; 3295 case ISD::SRA: 3296 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3297 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3298 Known = KnownBits::ashr(Known, Known2); 3299 // TODO: Add minimum shift high known sign bits. 3300 break; 3301 case ISD::FSHL: 3302 case ISD::FSHR: 3303 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3304 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3305 3306 // For fshl, 0-shift returns the 1st arg. 3307 // For fshr, 0-shift returns the 2nd arg. 3308 if (Amt == 0) { 3309 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3310 DemandedElts, Depth + 1); 3311 break; 3312 } 3313 3314 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3315 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3316 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3317 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3318 if (Opcode == ISD::FSHL) { 3319 Known.One <<= Amt; 3320 Known.Zero <<= Amt; 3321 Known2.One.lshrInPlace(BitWidth - Amt); 3322 Known2.Zero.lshrInPlace(BitWidth - Amt); 3323 } else { 3324 Known.One <<= BitWidth - Amt; 3325 Known.Zero <<= BitWidth - Amt; 3326 Known2.One.lshrInPlace(Amt); 3327 Known2.Zero.lshrInPlace(Amt); 3328 } 3329 Known.One |= Known2.One; 3330 Known.Zero |= Known2.Zero; 3331 } 3332 break; 3333 case ISD::SHL_PARTS: 3334 case ISD::SRA_PARTS: 3335 case ISD::SRL_PARTS: { 3336 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3337 3338 // Collect lo/hi source values and concatenate. 3339 // TODO: Would a KnownBits::concatBits helper be useful? 3340 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits(); 3341 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits(); 3342 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3343 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3344 Known = Known.anyext(LoBits + HiBits); 3345 Known.insertBits(Known2, LoBits); 3346 3347 // Collect shift amount. 3348 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3349 3350 if (Opcode == ISD::SHL_PARTS) 3351 Known = KnownBits::shl(Known, Known2); 3352 else if (Opcode == ISD::SRA_PARTS) 3353 Known = KnownBits::ashr(Known, Known2); 3354 else // if (Opcode == ISD::SRL_PARTS) 3355 Known = KnownBits::lshr(Known, Known2); 3356 3357 // TODO: Minimum shift low/high bits are known zero. 3358 3359 if (Op.getResNo() == 0) 3360 Known = Known.extractBits(LoBits, 0); 3361 else 3362 Known = Known.extractBits(HiBits, LoBits); 3363 break; 3364 } 3365 case ISD::SIGN_EXTEND_INREG: { 3366 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3367 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3368 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3369 break; 3370 } 3371 case ISD::CTTZ: 3372 case ISD::CTTZ_ZERO_UNDEF: { 3373 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3374 // If we have a known 1, its position is our upper bound. 3375 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3376 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3377 Known.Zero.setBitsFrom(LowBits); 3378 break; 3379 } 3380 case ISD::CTLZ: 3381 case ISD::CTLZ_ZERO_UNDEF: { 3382 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3383 // If we have a known 1, its position is our upper bound. 3384 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3385 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3386 Known.Zero.setBitsFrom(LowBits); 3387 break; 3388 } 3389 case ISD::CTPOP: { 3390 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3391 // If we know some of the bits are zero, they can't be one. 3392 unsigned PossibleOnes = Known2.countMaxPopulation(); 3393 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3394 break; 3395 } 3396 case ISD::PARITY: { 3397 // Parity returns 0 everywhere but the LSB. 3398 Known.Zero.setBitsFrom(1); 3399 break; 3400 } 3401 case ISD::LOAD: { 3402 LoadSDNode *LD = cast<LoadSDNode>(Op); 3403 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3404 if (ISD::isNON_EXTLoad(LD) && Cst) { 3405 // Determine any common known bits from the loaded constant pool value. 3406 Type *CstTy = Cst->getType(); 3407 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3408 // If its a vector splat, then we can (quickly) reuse the scalar path. 3409 // NOTE: We assume all elements match and none are UNDEF. 3410 if (CstTy->isVectorTy()) { 3411 if (const Constant *Splat = Cst->getSplatValue()) { 3412 Cst = Splat; 3413 CstTy = Cst->getType(); 3414 } 3415 } 3416 // TODO - do we need to handle different bitwidths? 3417 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3418 // Iterate across all vector elements finding common known bits. 3419 Known.One.setAllBits(); 3420 Known.Zero.setAllBits(); 3421 for (unsigned i = 0; i != NumElts; ++i) { 3422 if (!DemandedElts[i]) 3423 continue; 3424 if (Constant *Elt = Cst->getAggregateElement(i)) { 3425 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3426 const APInt &Value = CInt->getValue(); 3427 Known.One &= Value; 3428 Known.Zero &= ~Value; 3429 continue; 3430 } 3431 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3432 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3433 Known.One &= Value; 3434 Known.Zero &= ~Value; 3435 continue; 3436 } 3437 } 3438 Known.One.clearAllBits(); 3439 Known.Zero.clearAllBits(); 3440 break; 3441 } 3442 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3443 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3444 Known = KnownBits::makeConstant(CInt->getValue()); 3445 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3446 Known = 3447 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3448 } 3449 } 3450 } 3451 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3452 // If this is a ZEXTLoad and we are looking at the loaded value. 3453 EVT VT = LD->getMemoryVT(); 3454 unsigned MemBits = VT.getScalarSizeInBits(); 3455 Known.Zero.setBitsFrom(MemBits); 3456 } else if (const MDNode *Ranges = LD->getRanges()) { 3457 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3458 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3459 } 3460 break; 3461 } 3462 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3463 EVT InVT = Op.getOperand(0).getValueType(); 3464 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3465 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3466 Known = Known.zext(BitWidth); 3467 break; 3468 } 3469 case ISD::ZERO_EXTEND: { 3470 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3471 Known = Known.zext(BitWidth); 3472 break; 3473 } 3474 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3475 EVT InVT = Op.getOperand(0).getValueType(); 3476 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3477 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3478 // If the sign bit is known to be zero or one, then sext will extend 3479 // it to the top bits, else it will just zext. 3480 Known = Known.sext(BitWidth); 3481 break; 3482 } 3483 case ISD::SIGN_EXTEND: { 3484 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3485 // If the sign bit is known to be zero or one, then sext will extend 3486 // it to the top bits, else it will just zext. 3487 Known = Known.sext(BitWidth); 3488 break; 3489 } 3490 case ISD::ANY_EXTEND_VECTOR_INREG: { 3491 EVT InVT = Op.getOperand(0).getValueType(); 3492 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3493 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3494 Known = Known.anyext(BitWidth); 3495 break; 3496 } 3497 case ISD::ANY_EXTEND: { 3498 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3499 Known = Known.anyext(BitWidth); 3500 break; 3501 } 3502 case ISD::TRUNCATE: { 3503 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3504 Known = Known.trunc(BitWidth); 3505 break; 3506 } 3507 case ISD::AssertZext: { 3508 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3509 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3510 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3511 Known.Zero |= (~InMask); 3512 Known.One &= (~Known.Zero); 3513 break; 3514 } 3515 case ISD::AssertAlign: { 3516 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3517 assert(LogOfAlign != 0); 3518 3519 // TODO: Should use maximum with source 3520 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3521 // well as clearing one bits. 3522 Known.Zero.setLowBits(LogOfAlign); 3523 Known.One.clearLowBits(LogOfAlign); 3524 break; 3525 } 3526 case ISD::FGETSIGN: 3527 // All bits are zero except the low bit. 3528 Known.Zero.setBitsFrom(1); 3529 break; 3530 case ISD::USUBO: 3531 case ISD::SSUBO: 3532 case ISD::SUBCARRY: 3533 case ISD::SSUBO_CARRY: 3534 if (Op.getResNo() == 1) { 3535 // If we know the result of a setcc has the top bits zero, use this info. 3536 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3537 TargetLowering::ZeroOrOneBooleanContent && 3538 BitWidth > 1) 3539 Known.Zero.setBitsFrom(1); 3540 break; 3541 } 3542 LLVM_FALLTHROUGH; 3543 case ISD::SUB: 3544 case ISD::SUBC: { 3545 assert(Op.getResNo() == 0 && 3546 "We only compute knownbits for the difference here."); 3547 3548 // TODO: Compute influence of the carry operand. 3549 if (Opcode == ISD::SUBCARRY || Opcode == ISD::SSUBO_CARRY) 3550 break; 3551 3552 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3553 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3554 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3555 Known, Known2); 3556 break; 3557 } 3558 case ISD::UADDO: 3559 case ISD::SADDO: 3560 case ISD::ADDCARRY: 3561 case ISD::SADDO_CARRY: 3562 if (Op.getResNo() == 1) { 3563 // If we know the result of a setcc has the top bits zero, use this info. 3564 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3565 TargetLowering::ZeroOrOneBooleanContent && 3566 BitWidth > 1) 3567 Known.Zero.setBitsFrom(1); 3568 break; 3569 } 3570 LLVM_FALLTHROUGH; 3571 case ISD::ADD: 3572 case ISD::ADDC: 3573 case ISD::ADDE: { 3574 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3575 3576 // With ADDE and ADDCARRY, a carry bit may be added in. 3577 KnownBits Carry(1); 3578 if (Opcode == ISD::ADDE) 3579 // Can't track carry from glue, set carry to unknown. 3580 Carry.resetAll(); 3581 else if (Opcode == ISD::ADDCARRY || Opcode == ISD::SADDO_CARRY) 3582 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3583 // the trouble (how often will we find a known carry bit). And I haven't 3584 // tested this very much yet, but something like this might work: 3585 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3586 // Carry = Carry.zextOrTrunc(1, false); 3587 Carry.resetAll(); 3588 else 3589 Carry.setAllZero(); 3590 3591 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3592 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3593 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3594 break; 3595 } 3596 case ISD::UDIV: { 3597 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3598 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3599 Known = KnownBits::udiv(Known, Known2); 3600 break; 3601 } 3602 case ISD::SREM: { 3603 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3604 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3605 Known = KnownBits::srem(Known, Known2); 3606 break; 3607 } 3608 case ISD::UREM: { 3609 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3610 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3611 Known = KnownBits::urem(Known, Known2); 3612 break; 3613 } 3614 case ISD::EXTRACT_ELEMENT: { 3615 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3616 const unsigned Index = Op.getConstantOperandVal(1); 3617 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3618 3619 // Remove low part of known bits mask 3620 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3621 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3622 3623 // Remove high part of known bit mask 3624 Known = Known.trunc(EltBitWidth); 3625 break; 3626 } 3627 case ISD::EXTRACT_VECTOR_ELT: { 3628 SDValue InVec = Op.getOperand(0); 3629 SDValue EltNo = Op.getOperand(1); 3630 EVT VecVT = InVec.getValueType(); 3631 // computeKnownBits not yet implemented for scalable vectors. 3632 if (VecVT.isScalableVector()) 3633 break; 3634 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3635 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3636 3637 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3638 // anything about the extended bits. 3639 if (BitWidth > EltBitWidth) 3640 Known = Known.trunc(EltBitWidth); 3641 3642 // If we know the element index, just demand that vector element, else for 3643 // an unknown element index, ignore DemandedElts and demand them all. 3644 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3645 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3646 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3647 DemandedSrcElts = 3648 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3649 3650 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3651 if (BitWidth > EltBitWidth) 3652 Known = Known.anyext(BitWidth); 3653 break; 3654 } 3655 case ISD::INSERT_VECTOR_ELT: { 3656 // If we know the element index, split the demand between the 3657 // source vector and the inserted element, otherwise assume we need 3658 // the original demanded vector elements and the value. 3659 SDValue InVec = Op.getOperand(0); 3660 SDValue InVal = Op.getOperand(1); 3661 SDValue EltNo = Op.getOperand(2); 3662 bool DemandedVal = true; 3663 APInt DemandedVecElts = DemandedElts; 3664 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3665 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3666 unsigned EltIdx = CEltNo->getZExtValue(); 3667 DemandedVal = !!DemandedElts[EltIdx]; 3668 DemandedVecElts.clearBit(EltIdx); 3669 } 3670 Known.One.setAllBits(); 3671 Known.Zero.setAllBits(); 3672 if (DemandedVal) { 3673 Known2 = computeKnownBits(InVal, Depth + 1); 3674 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3675 } 3676 if (!!DemandedVecElts) { 3677 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3678 Known = KnownBits::commonBits(Known, Known2); 3679 } 3680 break; 3681 } 3682 case ISD::BITREVERSE: { 3683 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3684 Known = Known2.reverseBits(); 3685 break; 3686 } 3687 case ISD::BSWAP: { 3688 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3689 Known = Known2.byteSwap(); 3690 break; 3691 } 3692 case ISD::ABS: { 3693 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3694 Known = Known2.abs(); 3695 break; 3696 } 3697 case ISD::USUBSAT: { 3698 // The result of usubsat will never be larger than the LHS. 3699 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3700 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3701 break; 3702 } 3703 case ISD::UMIN: { 3704 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3705 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3706 Known = KnownBits::umin(Known, Known2); 3707 break; 3708 } 3709 case ISD::UMAX: { 3710 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3711 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3712 Known = KnownBits::umax(Known, Known2); 3713 break; 3714 } 3715 case ISD::SMIN: 3716 case ISD::SMAX: { 3717 // If we have a clamp pattern, we know that the number of sign bits will be 3718 // the minimum of the clamp min/max range. 3719 bool IsMax = (Opcode == ISD::SMAX); 3720 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3721 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3722 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3723 CstHigh = 3724 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3725 if (CstLow && CstHigh) { 3726 if (!IsMax) 3727 std::swap(CstLow, CstHigh); 3728 3729 const APInt &ValueLow = CstLow->getAPIntValue(); 3730 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3731 if (ValueLow.sle(ValueHigh)) { 3732 unsigned LowSignBits = ValueLow.getNumSignBits(); 3733 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3734 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3735 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3736 Known.One.setHighBits(MinSignBits); 3737 break; 3738 } 3739 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3740 Known.Zero.setHighBits(MinSignBits); 3741 break; 3742 } 3743 } 3744 } 3745 3746 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3747 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3748 if (IsMax) 3749 Known = KnownBits::smax(Known, Known2); 3750 else 3751 Known = KnownBits::smin(Known, Known2); 3752 3753 // For SMAX, if CstLow is non-negative we know the result will be 3754 // non-negative and thus all sign bits are 0. 3755 // TODO: There's an equivalent of this for smin with negative constant for 3756 // known ones. 3757 if (IsMax && CstLow) { 3758 const APInt &ValueLow = CstLow->getAPIntValue(); 3759 if (ValueLow.isNonNegative()) { 3760 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3761 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits())); 3762 } 3763 } 3764 3765 break; 3766 } 3767 case ISD::FP_TO_UINT_SAT: { 3768 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3769 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3770 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3771 break; 3772 } 3773 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3774 if (Op.getResNo() == 1) { 3775 // The boolean result conforms to getBooleanContents. 3776 // If we know the result of a setcc has the top bits zero, use this info. 3777 // We know that we have an integer-based boolean since these operations 3778 // are only available for integer. 3779 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3780 TargetLowering::ZeroOrOneBooleanContent && 3781 BitWidth > 1) 3782 Known.Zero.setBitsFrom(1); 3783 break; 3784 } 3785 LLVM_FALLTHROUGH; 3786 case ISD::ATOMIC_CMP_SWAP: 3787 case ISD::ATOMIC_SWAP: 3788 case ISD::ATOMIC_LOAD_ADD: 3789 case ISD::ATOMIC_LOAD_SUB: 3790 case ISD::ATOMIC_LOAD_AND: 3791 case ISD::ATOMIC_LOAD_CLR: 3792 case ISD::ATOMIC_LOAD_OR: 3793 case ISD::ATOMIC_LOAD_XOR: 3794 case ISD::ATOMIC_LOAD_NAND: 3795 case ISD::ATOMIC_LOAD_MIN: 3796 case ISD::ATOMIC_LOAD_MAX: 3797 case ISD::ATOMIC_LOAD_UMIN: 3798 case ISD::ATOMIC_LOAD_UMAX: 3799 case ISD::ATOMIC_LOAD: { 3800 unsigned MemBits = 3801 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3802 // If we are looking at the loaded value. 3803 if (Op.getResNo() == 0) { 3804 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3805 Known.Zero.setBitsFrom(MemBits); 3806 } 3807 break; 3808 } 3809 case ISD::FrameIndex: 3810 case ISD::TargetFrameIndex: 3811 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3812 Known, getMachineFunction()); 3813 break; 3814 3815 default: 3816 if (Opcode < ISD::BUILTIN_OP_END) 3817 break; 3818 LLVM_FALLTHROUGH; 3819 case ISD::INTRINSIC_WO_CHAIN: 3820 case ISD::INTRINSIC_W_CHAIN: 3821 case ISD::INTRINSIC_VOID: 3822 // Allow the target to implement this method for its nodes. 3823 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3824 break; 3825 } 3826 3827 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3828 return Known; 3829 } 3830 3831 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3832 SDValue N1) const { 3833 // X + 0 never overflow 3834 if (isNullConstant(N1)) 3835 return OFK_Never; 3836 3837 KnownBits N1Known = computeKnownBits(N1); 3838 if (N1Known.Zero.getBoolValue()) { 3839 KnownBits N0Known = computeKnownBits(N0); 3840 3841 bool overflow; 3842 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3843 if (!overflow) 3844 return OFK_Never; 3845 } 3846 3847 // mulhi + 1 never overflow 3848 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3849 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3850 return OFK_Never; 3851 3852 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3853 KnownBits N0Known = computeKnownBits(N0); 3854 3855 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3856 return OFK_Never; 3857 } 3858 3859 return OFK_Sometime; 3860 } 3861 3862 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3863 EVT OpVT = Val.getValueType(); 3864 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3865 3866 // Is the constant a known power of 2? 3867 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3868 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3869 3870 // A left-shift of a constant one will have exactly one bit set because 3871 // shifting the bit off the end is undefined. 3872 if (Val.getOpcode() == ISD::SHL) { 3873 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3874 if (C && C->getAPIntValue() == 1) 3875 return true; 3876 } 3877 3878 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3879 // one bit set. 3880 if (Val.getOpcode() == ISD::SRL) { 3881 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3882 if (C && C->getAPIntValue().isSignMask()) 3883 return true; 3884 } 3885 3886 // Are all operands of a build vector constant powers of two? 3887 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3888 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3889 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3890 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3891 return false; 3892 })) 3893 return true; 3894 3895 // Is the operand of a splat vector a constant power of two? 3896 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3897 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3898 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3899 return true; 3900 3901 // vscale(power-of-two) is a power-of-two for some targets 3902 if (Val.getOpcode() == ISD::VSCALE && 3903 getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() && 3904 isKnownToBeAPowerOfTwo(Val.getOperand(0))) 3905 return true; 3906 3907 // More could be done here, though the above checks are enough 3908 // to handle some common cases. 3909 3910 // Fall back to computeKnownBits to catch other known cases. 3911 KnownBits Known = computeKnownBits(Val); 3912 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3913 } 3914 3915 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3916 EVT VT = Op.getValueType(); 3917 3918 // TODO: Assume we don't know anything for now. 3919 if (VT.isScalableVector()) 3920 return 1; 3921 3922 APInt DemandedElts = VT.isVector() 3923 ? APInt::getAllOnes(VT.getVectorNumElements()) 3924 : APInt(1, 1); 3925 return ComputeNumSignBits(Op, DemandedElts, Depth); 3926 } 3927 3928 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3929 unsigned Depth) const { 3930 EVT VT = Op.getValueType(); 3931 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3932 unsigned VTBits = VT.getScalarSizeInBits(); 3933 unsigned NumElts = DemandedElts.getBitWidth(); 3934 unsigned Tmp, Tmp2; 3935 unsigned FirstAnswer = 1; 3936 3937 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3938 const APInt &Val = C->getAPIntValue(); 3939 return Val.getNumSignBits(); 3940 } 3941 3942 if (Depth >= MaxRecursionDepth) 3943 return 1; // Limit search depth. 3944 3945 if (!DemandedElts || VT.isScalableVector()) 3946 return 1; // No demanded elts, better to assume we don't know anything. 3947 3948 unsigned Opcode = Op.getOpcode(); 3949 switch (Opcode) { 3950 default: break; 3951 case ISD::AssertSext: 3952 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3953 return VTBits-Tmp+1; 3954 case ISD::AssertZext: 3955 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3956 return VTBits-Tmp; 3957 case ISD::MERGE_VALUES: 3958 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts, 3959 Depth + 1); 3960 case ISD::BUILD_VECTOR: 3961 Tmp = VTBits; 3962 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3963 if (!DemandedElts[i]) 3964 continue; 3965 3966 SDValue SrcOp = Op.getOperand(i); 3967 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3968 3969 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3970 if (SrcOp.getValueSizeInBits() != VTBits) { 3971 assert(SrcOp.getValueSizeInBits() > VTBits && 3972 "Expected BUILD_VECTOR implicit truncation"); 3973 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3974 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3975 } 3976 Tmp = std::min(Tmp, Tmp2); 3977 } 3978 return Tmp; 3979 3980 case ISD::VECTOR_SHUFFLE: { 3981 // Collect the minimum number of sign bits that are shared by every vector 3982 // element referenced by the shuffle. 3983 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3984 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3985 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3986 for (unsigned i = 0; i != NumElts; ++i) { 3987 int M = SVN->getMaskElt(i); 3988 if (!DemandedElts[i]) 3989 continue; 3990 // For UNDEF elements, we don't know anything about the common state of 3991 // the shuffle result. 3992 if (M < 0) 3993 return 1; 3994 if ((unsigned)M < NumElts) 3995 DemandedLHS.setBit((unsigned)M % NumElts); 3996 else 3997 DemandedRHS.setBit((unsigned)M % NumElts); 3998 } 3999 Tmp = std::numeric_limits<unsigned>::max(); 4000 if (!!DemandedLHS) 4001 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 4002 if (!!DemandedRHS) { 4003 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 4004 Tmp = std::min(Tmp, Tmp2); 4005 } 4006 // If we don't know anything, early out and try computeKnownBits fall-back. 4007 if (Tmp == 1) 4008 break; 4009 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4010 return Tmp; 4011 } 4012 4013 case ISD::BITCAST: { 4014 SDValue N0 = Op.getOperand(0); 4015 EVT SrcVT = N0.getValueType(); 4016 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 4017 4018 // Ignore bitcasts from unsupported types.. 4019 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 4020 break; 4021 4022 // Fast handling of 'identity' bitcasts. 4023 if (VTBits == SrcBits) 4024 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 4025 4026 bool IsLE = getDataLayout().isLittleEndian(); 4027 4028 // Bitcast 'large element' scalar/vector to 'small element' vector. 4029 if ((SrcBits % VTBits) == 0) { 4030 assert(VT.isVector() && "Expected bitcast to vector"); 4031 4032 unsigned Scale = SrcBits / VTBits; 4033 APInt SrcDemandedElts = 4034 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 4035 4036 // Fast case - sign splat can be simply split across the small elements. 4037 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 4038 if (Tmp == SrcBits) 4039 return VTBits; 4040 4041 // Slow case - determine how far the sign extends into each sub-element. 4042 Tmp2 = VTBits; 4043 for (unsigned i = 0; i != NumElts; ++i) 4044 if (DemandedElts[i]) { 4045 unsigned SubOffset = i % Scale; 4046 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 4047 SubOffset = SubOffset * VTBits; 4048 if (Tmp <= SubOffset) 4049 return 1; 4050 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 4051 } 4052 return Tmp2; 4053 } 4054 break; 4055 } 4056 4057 case ISD::FP_TO_SINT_SAT: 4058 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 4059 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4060 return VTBits - Tmp + 1; 4061 case ISD::SIGN_EXTEND: 4062 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 4063 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 4064 case ISD::SIGN_EXTEND_INREG: 4065 // Max of the input and what this extends. 4066 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4067 Tmp = VTBits-Tmp+1; 4068 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4069 return std::max(Tmp, Tmp2); 4070 case ISD::SIGN_EXTEND_VECTOR_INREG: { 4071 SDValue Src = Op.getOperand(0); 4072 EVT SrcVT = Src.getValueType(); 4073 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements()); 4074 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4075 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4076 } 4077 case ISD::SRA: 4078 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4079 // SRA X, C -> adds C sign bits. 4080 if (const APInt *ShAmt = 4081 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4082 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4083 return Tmp; 4084 case ISD::SHL: 4085 if (const APInt *ShAmt = 4086 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4087 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4088 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4089 if (ShAmt->ult(Tmp)) 4090 return Tmp - ShAmt->getZExtValue(); 4091 } 4092 break; 4093 case ISD::AND: 4094 case ISD::OR: 4095 case ISD::XOR: // NOT is handled here. 4096 // Logical binary ops preserve the number of sign bits at the worst. 4097 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4098 if (Tmp != 1) { 4099 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4100 FirstAnswer = std::min(Tmp, Tmp2); 4101 // We computed what we know about the sign bits as our first 4102 // answer. Now proceed to the generic code that uses 4103 // computeKnownBits, and pick whichever answer is better. 4104 } 4105 break; 4106 4107 case ISD::SELECT: 4108 case ISD::VSELECT: 4109 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4110 if (Tmp == 1) return 1; // Early out. 4111 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4112 return std::min(Tmp, Tmp2); 4113 case ISD::SELECT_CC: 4114 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4115 if (Tmp == 1) return 1; // Early out. 4116 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4117 return std::min(Tmp, Tmp2); 4118 4119 case ISD::SMIN: 4120 case ISD::SMAX: { 4121 // If we have a clamp pattern, we know that the number of sign bits will be 4122 // the minimum of the clamp min/max range. 4123 bool IsMax = (Opcode == ISD::SMAX); 4124 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4125 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4126 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4127 CstHigh = 4128 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4129 if (CstLow && CstHigh) { 4130 if (!IsMax) 4131 std::swap(CstLow, CstHigh); 4132 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4133 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4134 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4135 return std::min(Tmp, Tmp2); 4136 } 4137 } 4138 4139 // Fallback - just get the minimum number of sign bits of the operands. 4140 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4141 if (Tmp == 1) 4142 return 1; // Early out. 4143 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4144 return std::min(Tmp, Tmp2); 4145 } 4146 case ISD::UMIN: 4147 case ISD::UMAX: 4148 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4149 if (Tmp == 1) 4150 return 1; // Early out. 4151 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4152 return std::min(Tmp, Tmp2); 4153 case ISD::SADDO: 4154 case ISD::UADDO: 4155 case ISD::SADDO_CARRY: 4156 case ISD::ADDCARRY: 4157 case ISD::SSUBO: 4158 case ISD::USUBO: 4159 case ISD::SSUBO_CARRY: 4160 case ISD::SUBCARRY: 4161 case ISD::SMULO: 4162 case ISD::UMULO: 4163 if (Op.getResNo() != 1) 4164 break; 4165 // The boolean result conforms to getBooleanContents. Fall through. 4166 // If setcc returns 0/-1, all bits are sign bits. 4167 // We know that we have an integer-based boolean since these operations 4168 // are only available for integer. 4169 if (TLI->getBooleanContents(VT.isVector(), false) == 4170 TargetLowering::ZeroOrNegativeOneBooleanContent) 4171 return VTBits; 4172 break; 4173 case ISD::SETCC: 4174 case ISD::SETCCCARRY: 4175 case ISD::STRICT_FSETCC: 4176 case ISD::STRICT_FSETCCS: { 4177 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4178 // If setcc returns 0/-1, all bits are sign bits. 4179 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4180 TargetLowering::ZeroOrNegativeOneBooleanContent) 4181 return VTBits; 4182 break; 4183 } 4184 case ISD::ROTL: 4185 case ISD::ROTR: 4186 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4187 4188 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4189 if (Tmp == VTBits) 4190 return VTBits; 4191 4192 if (ConstantSDNode *C = 4193 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4194 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4195 4196 // Handle rotate right by N like a rotate left by 32-N. 4197 if (Opcode == ISD::ROTR) 4198 RotAmt = (VTBits - RotAmt) % VTBits; 4199 4200 // If we aren't rotating out all of the known-in sign bits, return the 4201 // number that are left. This handles rotl(sext(x), 1) for example. 4202 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4203 } 4204 break; 4205 case ISD::ADD: 4206 case ISD::ADDC: 4207 // Add can have at most one carry bit. Thus we know that the output 4208 // is, at worst, one more bit than the inputs. 4209 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4210 if (Tmp == 1) return 1; // Early out. 4211 4212 // Special case decrementing a value (ADD X, -1): 4213 if (ConstantSDNode *CRHS = 4214 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4215 if (CRHS->isAllOnes()) { 4216 KnownBits Known = 4217 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4218 4219 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4220 // sign bits set. 4221 if ((Known.Zero | 1).isAllOnes()) 4222 return VTBits; 4223 4224 // If we are subtracting one from a positive number, there is no carry 4225 // out of the result. 4226 if (Known.isNonNegative()) 4227 return Tmp; 4228 } 4229 4230 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4231 if (Tmp2 == 1) return 1; // Early out. 4232 return std::min(Tmp, Tmp2) - 1; 4233 case ISD::SUB: 4234 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4235 if (Tmp2 == 1) return 1; // Early out. 4236 4237 // Handle NEG. 4238 if (ConstantSDNode *CLHS = 4239 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4240 if (CLHS->isZero()) { 4241 KnownBits Known = 4242 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4243 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4244 // sign bits set. 4245 if ((Known.Zero | 1).isAllOnes()) 4246 return VTBits; 4247 4248 // If the input is known to be positive (the sign bit is known clear), 4249 // the output of the NEG has the same number of sign bits as the input. 4250 if (Known.isNonNegative()) 4251 return Tmp2; 4252 4253 // Otherwise, we treat this like a SUB. 4254 } 4255 4256 // Sub can have at most one carry bit. Thus we know that the output 4257 // is, at worst, one more bit than the inputs. 4258 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4259 if (Tmp == 1) return 1; // Early out. 4260 return std::min(Tmp, Tmp2) - 1; 4261 case ISD::MUL: { 4262 // The output of the Mul can be at most twice the valid bits in the inputs. 4263 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4264 if (SignBitsOp0 == 1) 4265 break; 4266 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4267 if (SignBitsOp1 == 1) 4268 break; 4269 unsigned OutValidBits = 4270 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4271 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4272 } 4273 case ISD::SREM: 4274 // The sign bit is the LHS's sign bit, except when the result of the 4275 // remainder is zero. The magnitude of the result should be less than or 4276 // equal to the magnitude of the LHS. Therefore, the result should have 4277 // at least as many sign bits as the left hand side. 4278 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4279 case ISD::TRUNCATE: { 4280 // Check if the sign bits of source go down as far as the truncated value. 4281 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4282 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4283 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4284 return NumSrcSignBits - (NumSrcBits - VTBits); 4285 break; 4286 } 4287 case ISD::EXTRACT_ELEMENT: { 4288 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4289 const int BitWidth = Op.getValueSizeInBits(); 4290 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4291 4292 // Get reverse index (starting from 1), Op1 value indexes elements from 4293 // little end. Sign starts at big end. 4294 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4295 4296 // If the sign portion ends in our element the subtraction gives correct 4297 // result. Otherwise it gives either negative or > bitwidth result 4298 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4299 } 4300 case ISD::INSERT_VECTOR_ELT: { 4301 // If we know the element index, split the demand between the 4302 // source vector and the inserted element, otherwise assume we need 4303 // the original demanded vector elements and the value. 4304 SDValue InVec = Op.getOperand(0); 4305 SDValue InVal = Op.getOperand(1); 4306 SDValue EltNo = Op.getOperand(2); 4307 bool DemandedVal = true; 4308 APInt DemandedVecElts = DemandedElts; 4309 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4310 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4311 unsigned EltIdx = CEltNo->getZExtValue(); 4312 DemandedVal = !!DemandedElts[EltIdx]; 4313 DemandedVecElts.clearBit(EltIdx); 4314 } 4315 Tmp = std::numeric_limits<unsigned>::max(); 4316 if (DemandedVal) { 4317 // TODO - handle implicit truncation of inserted elements. 4318 if (InVal.getScalarValueSizeInBits() != VTBits) 4319 break; 4320 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4321 Tmp = std::min(Tmp, Tmp2); 4322 } 4323 if (!!DemandedVecElts) { 4324 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, 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::EXTRACT_VECTOR_ELT: { 4331 SDValue InVec = Op.getOperand(0); 4332 SDValue EltNo = Op.getOperand(1); 4333 EVT VecVT = InVec.getValueType(); 4334 // ComputeNumSignBits not yet implemented for scalable vectors. 4335 if (VecVT.isScalableVector()) 4336 break; 4337 const unsigned BitWidth = Op.getValueSizeInBits(); 4338 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4339 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4340 4341 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4342 // anything about sign bits. But if the sizes match we can derive knowledge 4343 // about sign bits from the vector operand. 4344 if (BitWidth != EltBitWidth) 4345 break; 4346 4347 // If we know the element index, just demand that vector element, else for 4348 // an unknown element index, ignore DemandedElts and demand them all. 4349 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4350 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4351 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4352 DemandedSrcElts = 4353 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4354 4355 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4356 } 4357 case ISD::EXTRACT_SUBVECTOR: { 4358 // Offset the demanded elts by the subvector index. 4359 SDValue Src = Op.getOperand(0); 4360 // Bail until we can represent demanded elements for scalable vectors. 4361 if (Src.getValueType().isScalableVector()) 4362 break; 4363 uint64_t Idx = Op.getConstantOperandVal(1); 4364 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4365 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 4366 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4367 } 4368 case ISD::CONCAT_VECTORS: { 4369 // Determine the minimum number of sign bits across all demanded 4370 // elts of the input vectors. Early out if the result is already 1. 4371 Tmp = std::numeric_limits<unsigned>::max(); 4372 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4373 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4374 unsigned NumSubVectors = Op.getNumOperands(); 4375 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4376 APInt DemandedSub = 4377 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4378 if (!DemandedSub) 4379 continue; 4380 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4381 Tmp = std::min(Tmp, Tmp2); 4382 } 4383 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4384 return Tmp; 4385 } 4386 case ISD::INSERT_SUBVECTOR: { 4387 // Demand any elements from the subvector and the remainder from the src its 4388 // inserted into. 4389 SDValue Src = Op.getOperand(0); 4390 SDValue Sub = Op.getOperand(1); 4391 uint64_t Idx = Op.getConstantOperandVal(2); 4392 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4393 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4394 APInt DemandedSrcElts = DemandedElts; 4395 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4396 4397 Tmp = std::numeric_limits<unsigned>::max(); 4398 if (!!DemandedSubElts) { 4399 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4400 if (Tmp == 1) 4401 return 1; // early-out 4402 } 4403 if (!!DemandedSrcElts) { 4404 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4405 Tmp = std::min(Tmp, Tmp2); 4406 } 4407 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4408 return Tmp; 4409 } 4410 case ISD::ATOMIC_CMP_SWAP: 4411 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4412 case ISD::ATOMIC_SWAP: 4413 case ISD::ATOMIC_LOAD_ADD: 4414 case ISD::ATOMIC_LOAD_SUB: 4415 case ISD::ATOMIC_LOAD_AND: 4416 case ISD::ATOMIC_LOAD_CLR: 4417 case ISD::ATOMIC_LOAD_OR: 4418 case ISD::ATOMIC_LOAD_XOR: 4419 case ISD::ATOMIC_LOAD_NAND: 4420 case ISD::ATOMIC_LOAD_MIN: 4421 case ISD::ATOMIC_LOAD_MAX: 4422 case ISD::ATOMIC_LOAD_UMIN: 4423 case ISD::ATOMIC_LOAD_UMAX: 4424 case ISD::ATOMIC_LOAD: { 4425 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4426 // If we are looking at the loaded value. 4427 if (Op.getResNo() == 0) { 4428 if (Tmp == VTBits) 4429 return 1; // early-out 4430 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4431 return VTBits - Tmp + 1; 4432 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4433 return VTBits - Tmp; 4434 } 4435 break; 4436 } 4437 } 4438 4439 // If we are looking at the loaded value of the SDNode. 4440 if (Op.getResNo() == 0) { 4441 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4442 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4443 unsigned ExtType = LD->getExtensionType(); 4444 switch (ExtType) { 4445 default: break; 4446 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4447 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4448 return VTBits - Tmp + 1; 4449 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4450 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4451 return VTBits - Tmp; 4452 case ISD::NON_EXTLOAD: 4453 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4454 // We only need to handle vectors - computeKnownBits should handle 4455 // scalar cases. 4456 Type *CstTy = Cst->getType(); 4457 if (CstTy->isVectorTy() && 4458 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4459 VTBits == CstTy->getScalarSizeInBits()) { 4460 Tmp = VTBits; 4461 for (unsigned i = 0; i != NumElts; ++i) { 4462 if (!DemandedElts[i]) 4463 continue; 4464 if (Constant *Elt = Cst->getAggregateElement(i)) { 4465 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4466 const APInt &Value = CInt->getValue(); 4467 Tmp = std::min(Tmp, Value.getNumSignBits()); 4468 continue; 4469 } 4470 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4471 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4472 Tmp = std::min(Tmp, Value.getNumSignBits()); 4473 continue; 4474 } 4475 } 4476 // Unknown type. Conservatively assume no bits match sign bit. 4477 return 1; 4478 } 4479 return Tmp; 4480 } 4481 } 4482 break; 4483 } 4484 } 4485 } 4486 4487 // Allow the target to implement this method for its nodes. 4488 if (Opcode >= ISD::BUILTIN_OP_END || 4489 Opcode == ISD::INTRINSIC_WO_CHAIN || 4490 Opcode == ISD::INTRINSIC_W_CHAIN || 4491 Opcode == ISD::INTRINSIC_VOID) { 4492 unsigned NumBits = 4493 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4494 if (NumBits > 1) 4495 FirstAnswer = std::max(FirstAnswer, NumBits); 4496 } 4497 4498 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4499 // use this information. 4500 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4501 return std::max(FirstAnswer, Known.countMinSignBits()); 4502 } 4503 4504 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4505 unsigned Depth) const { 4506 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4507 return Op.getScalarValueSizeInBits() - SignBits + 1; 4508 } 4509 4510 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4511 const APInt &DemandedElts, 4512 unsigned Depth) const { 4513 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4514 return Op.getScalarValueSizeInBits() - SignBits + 1; 4515 } 4516 4517 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4518 unsigned Depth) const { 4519 // Early out for FREEZE. 4520 if (Op.getOpcode() == ISD::FREEZE) 4521 return true; 4522 4523 // TODO: Assume we don't know anything for now. 4524 EVT VT = Op.getValueType(); 4525 if (VT.isScalableVector()) 4526 return false; 4527 4528 APInt DemandedElts = VT.isVector() 4529 ? APInt::getAllOnes(VT.getVectorNumElements()) 4530 : APInt(1, 1); 4531 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4532 } 4533 4534 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4535 const APInt &DemandedElts, 4536 bool PoisonOnly, 4537 unsigned Depth) const { 4538 unsigned Opcode = Op.getOpcode(); 4539 4540 // Early out for FREEZE. 4541 if (Opcode == ISD::FREEZE) 4542 return true; 4543 4544 if (Depth >= MaxRecursionDepth) 4545 return false; // Limit search depth. 4546 4547 if (isIntOrFPConstant(Op)) 4548 return true; 4549 4550 switch (Opcode) { 4551 case ISD::UNDEF: 4552 return PoisonOnly; 4553 4554 case ISD::BUILD_VECTOR: 4555 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4556 // this shouldn't affect the result. 4557 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4558 if (!DemandedElts[i]) 4559 continue; 4560 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4561 Depth + 1)) 4562 return false; 4563 } 4564 return true; 4565 4566 // TODO: Search for noundef attributes from library functions. 4567 4568 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4569 4570 default: 4571 // Allow the target to implement this method for its nodes. 4572 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4573 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4574 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4575 Op, DemandedElts, *this, PoisonOnly, Depth); 4576 break; 4577 } 4578 4579 return false; 4580 } 4581 4582 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4583 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4584 !isa<ConstantSDNode>(Op.getOperand(1))) 4585 return false; 4586 4587 if (Op.getOpcode() == ISD::OR && 4588 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4589 return false; 4590 4591 return true; 4592 } 4593 4594 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4595 // If we're told that NaNs won't happen, assume they won't. 4596 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4597 return true; 4598 4599 if (Depth >= MaxRecursionDepth) 4600 return false; // Limit search depth. 4601 4602 // TODO: Handle vectors. 4603 // If the value is a constant, we can obviously see if it is a NaN or not. 4604 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4605 return !C->getValueAPF().isNaN() || 4606 (SNaN && !C->getValueAPF().isSignaling()); 4607 } 4608 4609 unsigned Opcode = Op.getOpcode(); 4610 switch (Opcode) { 4611 case ISD::FADD: 4612 case ISD::FSUB: 4613 case ISD::FMUL: 4614 case ISD::FDIV: 4615 case ISD::FREM: 4616 case ISD::FSIN: 4617 case ISD::FCOS: { 4618 if (SNaN) 4619 return true; 4620 // TODO: Need isKnownNeverInfinity 4621 return false; 4622 } 4623 case ISD::FCANONICALIZE: 4624 case ISD::FEXP: 4625 case ISD::FEXP2: 4626 case ISD::FTRUNC: 4627 case ISD::FFLOOR: 4628 case ISD::FCEIL: 4629 case ISD::FROUND: 4630 case ISD::FROUNDEVEN: 4631 case ISD::FRINT: 4632 case ISD::FNEARBYINT: { 4633 if (SNaN) 4634 return true; 4635 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4636 } 4637 case ISD::FABS: 4638 case ISD::FNEG: 4639 case ISD::FCOPYSIGN: { 4640 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4641 } 4642 case ISD::SELECT: 4643 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4644 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4645 case ISD::FP_EXTEND: 4646 case ISD::FP_ROUND: { 4647 if (SNaN) 4648 return true; 4649 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4650 } 4651 case ISD::SINT_TO_FP: 4652 case ISD::UINT_TO_FP: 4653 return true; 4654 case ISD::FMA: 4655 case ISD::FMAD: { 4656 if (SNaN) 4657 return true; 4658 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4659 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4660 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4661 } 4662 case ISD::FSQRT: // Need is known positive 4663 case ISD::FLOG: 4664 case ISD::FLOG2: 4665 case ISD::FLOG10: 4666 case ISD::FPOWI: 4667 case ISD::FPOW: { 4668 if (SNaN) 4669 return true; 4670 // TODO: Refine on operand 4671 return false; 4672 } 4673 case ISD::FMINNUM: 4674 case ISD::FMAXNUM: { 4675 // Only one needs to be known not-nan, since it will be returned if the 4676 // other ends up being one. 4677 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4678 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4679 } 4680 case ISD::FMINNUM_IEEE: 4681 case ISD::FMAXNUM_IEEE: { 4682 if (SNaN) 4683 return true; 4684 // This can return a NaN if either operand is an sNaN, or if both operands 4685 // are NaN. 4686 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4687 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4688 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4689 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4690 } 4691 case ISD::FMINIMUM: 4692 case ISD::FMAXIMUM: { 4693 // TODO: Does this quiet or return the origina NaN as-is? 4694 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4695 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4696 } 4697 case ISD::EXTRACT_VECTOR_ELT: { 4698 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4699 } 4700 default: 4701 if (Opcode >= ISD::BUILTIN_OP_END || 4702 Opcode == ISD::INTRINSIC_WO_CHAIN || 4703 Opcode == ISD::INTRINSIC_W_CHAIN || 4704 Opcode == ISD::INTRINSIC_VOID) { 4705 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4706 } 4707 4708 return false; 4709 } 4710 } 4711 4712 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4713 assert(Op.getValueType().isFloatingPoint() && 4714 "Floating point type expected"); 4715 4716 // If the value is a constant, we can obviously see if it is a zero or not. 4717 // TODO: Add BuildVector support. 4718 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4719 return !C->isZero(); 4720 return false; 4721 } 4722 4723 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4724 assert(!Op.getValueType().isFloatingPoint() && 4725 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4726 4727 // If the value is a constant, we can obviously see if it is a zero or not. 4728 if (ISD::matchUnaryPredicate(Op, 4729 [](ConstantSDNode *C) { return !C->isZero(); })) 4730 return true; 4731 4732 // TODO: Recognize more cases here. 4733 switch (Op.getOpcode()) { 4734 default: break; 4735 case ISD::OR: 4736 if (isKnownNeverZero(Op.getOperand(1)) || 4737 isKnownNeverZero(Op.getOperand(0))) 4738 return true; 4739 break; 4740 } 4741 4742 return false; 4743 } 4744 4745 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4746 // Check the obvious case. 4747 if (A == B) return true; 4748 4749 // For for negative and positive zero. 4750 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4751 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4752 if (CA->isZero() && CB->isZero()) return true; 4753 4754 // Otherwise they may not be equal. 4755 return false; 4756 } 4757 4758 // Only bits set in Mask must be negated, other bits may be arbitrary. 4759 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) { 4760 if (isBitwiseNot(V, AllowUndefs)) 4761 return V.getOperand(0); 4762 4763 // Handle any_extend (not (truncate X)) pattern, where Mask only sets 4764 // bits in the non-extended part. 4765 ConstantSDNode *MaskC = isConstOrConstSplat(Mask); 4766 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND) 4767 return SDValue(); 4768 SDValue ExtArg = V.getOperand(0); 4769 if (ExtArg.getScalarValueSizeInBits() >= 4770 MaskC->getAPIntValue().getActiveBits() && 4771 isBitwiseNot(ExtArg, AllowUndefs) && 4772 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE && 4773 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType()) 4774 return ExtArg.getOperand(0).getOperand(0); 4775 return SDValue(); 4776 } 4777 4778 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) { 4779 // Match masked merge pattern (X & ~M) op (Y & M) 4780 // Including degenerate case (X & ~M) op M 4781 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask, 4782 SDValue Other) { 4783 if (SDValue NotOperand = 4784 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) { 4785 if (Other == NotOperand) 4786 return true; 4787 if (Other->getOpcode() == ISD::AND) 4788 return NotOperand == Other->getOperand(0) || 4789 NotOperand == Other->getOperand(1); 4790 } 4791 return false; 4792 }; 4793 if (A->getOpcode() == ISD::AND) 4794 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) || 4795 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B); 4796 return false; 4797 } 4798 4799 // FIXME: unify with llvm::haveNoCommonBitsSet. 4800 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4801 assert(A.getValueType() == B.getValueType() && 4802 "Values must have the same type"); 4803 if (haveNoCommonBitsSetCommutative(A, B) || 4804 haveNoCommonBitsSetCommutative(B, A)) 4805 return true; 4806 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4807 computeKnownBits(B)); 4808 } 4809 4810 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4811 SelectionDAG &DAG) { 4812 if (cast<ConstantSDNode>(Step)->isZero()) 4813 return DAG.getConstant(0, DL, VT); 4814 4815 return SDValue(); 4816 } 4817 4818 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4819 ArrayRef<SDValue> Ops, 4820 SelectionDAG &DAG) { 4821 int NumOps = Ops.size(); 4822 assert(NumOps != 0 && "Can't build an empty vector!"); 4823 assert(!VT.isScalableVector() && 4824 "BUILD_VECTOR cannot be used with scalable types"); 4825 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4826 "Incorrect element count in BUILD_VECTOR!"); 4827 4828 // BUILD_VECTOR of UNDEFs is UNDEF. 4829 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4830 return DAG.getUNDEF(VT); 4831 4832 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4833 SDValue IdentitySrc; 4834 bool IsIdentity = true; 4835 for (int i = 0; i != NumOps; ++i) { 4836 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4837 Ops[i].getOperand(0).getValueType() != VT || 4838 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4839 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4840 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4841 IsIdentity = false; 4842 break; 4843 } 4844 IdentitySrc = Ops[i].getOperand(0); 4845 } 4846 if (IsIdentity) 4847 return IdentitySrc; 4848 4849 return SDValue(); 4850 } 4851 4852 /// Try to simplify vector concatenation to an input value, undef, or build 4853 /// vector. 4854 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4855 ArrayRef<SDValue> Ops, 4856 SelectionDAG &DAG) { 4857 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4858 assert(llvm::all_of(Ops, 4859 [Ops](SDValue Op) { 4860 return Ops[0].getValueType() == Op.getValueType(); 4861 }) && 4862 "Concatenation of vectors with inconsistent value types!"); 4863 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4864 VT.getVectorElementCount() && 4865 "Incorrect element count in vector concatenation!"); 4866 4867 if (Ops.size() == 1) 4868 return Ops[0]; 4869 4870 // Concat of UNDEFs is UNDEF. 4871 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4872 return DAG.getUNDEF(VT); 4873 4874 // Scan the operands and look for extract operations from a single source 4875 // that correspond to insertion at the same location via this concatenation: 4876 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4877 SDValue IdentitySrc; 4878 bool IsIdentity = true; 4879 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4880 SDValue Op = Ops[i]; 4881 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4882 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4883 Op.getOperand(0).getValueType() != VT || 4884 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4885 Op.getConstantOperandVal(1) != IdentityIndex) { 4886 IsIdentity = false; 4887 break; 4888 } 4889 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4890 "Unexpected identity source vector for concat of extracts"); 4891 IdentitySrc = Op.getOperand(0); 4892 } 4893 if (IsIdentity) { 4894 assert(IdentitySrc && "Failed to set source vector of extracts"); 4895 return IdentitySrc; 4896 } 4897 4898 // The code below this point is only designed to work for fixed width 4899 // vectors, so we bail out for now. 4900 if (VT.isScalableVector()) 4901 return SDValue(); 4902 4903 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4904 // simplified to one big BUILD_VECTOR. 4905 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4906 EVT SVT = VT.getScalarType(); 4907 SmallVector<SDValue, 16> Elts; 4908 for (SDValue Op : Ops) { 4909 EVT OpVT = Op.getValueType(); 4910 if (Op.isUndef()) 4911 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4912 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4913 Elts.append(Op->op_begin(), Op->op_end()); 4914 else 4915 return SDValue(); 4916 } 4917 4918 // BUILD_VECTOR requires all inputs to be of the same type, find the 4919 // maximum type and extend them all. 4920 for (SDValue Op : Elts) 4921 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4922 4923 if (SVT.bitsGT(VT.getScalarType())) { 4924 for (SDValue &Op : Elts) { 4925 if (Op.isUndef()) 4926 Op = DAG.getUNDEF(SVT); 4927 else 4928 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4929 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4930 : DAG.getSExtOrTrunc(Op, DL, SVT); 4931 } 4932 } 4933 4934 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4935 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4936 return V; 4937 } 4938 4939 /// Gets or creates the specified node. 4940 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4941 FoldingSetNodeID ID; 4942 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4943 void *IP = nullptr; 4944 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4945 return SDValue(E, 0); 4946 4947 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4948 getVTList(VT)); 4949 CSEMap.InsertNode(N, IP); 4950 4951 InsertNode(N); 4952 SDValue V = SDValue(N, 0); 4953 NewSDValueDbgMsg(V, "Creating new node: ", this); 4954 return V; 4955 } 4956 4957 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4958 SDValue Operand) { 4959 SDNodeFlags Flags; 4960 if (Inserter) 4961 Flags = Inserter->getFlags(); 4962 return getNode(Opcode, DL, VT, Operand, Flags); 4963 } 4964 4965 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4966 SDValue Operand, const SDNodeFlags Flags) { 4967 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4968 "Operand is DELETED_NODE!"); 4969 // Constant fold unary operations with an integer constant operand. Even 4970 // opaque constant will be folded, because the folding of unary operations 4971 // doesn't create new constants with different values. Nevertheless, the 4972 // opaque flag is preserved during folding to prevent future folding with 4973 // other constants. 4974 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4975 const APInt &Val = C->getAPIntValue(); 4976 switch (Opcode) { 4977 default: break; 4978 case ISD::SIGN_EXTEND: 4979 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4980 C->isTargetOpcode(), C->isOpaque()); 4981 case ISD::TRUNCATE: 4982 if (C->isOpaque()) 4983 break; 4984 LLVM_FALLTHROUGH; 4985 case ISD::ZERO_EXTEND: 4986 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4987 C->isTargetOpcode(), C->isOpaque()); 4988 case ISD::ANY_EXTEND: 4989 // Some targets like RISCV prefer to sign extend some types. 4990 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4991 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4992 C->isTargetOpcode(), C->isOpaque()); 4993 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4994 C->isTargetOpcode(), C->isOpaque()); 4995 case ISD::UINT_TO_FP: 4996 case ISD::SINT_TO_FP: { 4997 APFloat apf(EVTToAPFloatSemantics(VT), 4998 APInt::getZero(VT.getSizeInBits())); 4999 (void)apf.convertFromAPInt(Val, 5000 Opcode==ISD::SINT_TO_FP, 5001 APFloat::rmNearestTiesToEven); 5002 return getConstantFP(apf, DL, VT); 5003 } 5004 case ISD::BITCAST: 5005 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 5006 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 5007 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 5008 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 5009 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 5010 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 5011 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 5012 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 5013 break; 5014 case ISD::ABS: 5015 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 5016 C->isOpaque()); 5017 case ISD::BITREVERSE: 5018 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 5019 C->isOpaque()); 5020 case ISD::BSWAP: 5021 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 5022 C->isOpaque()); 5023 case ISD::CTPOP: 5024 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 5025 C->isOpaque()); 5026 case ISD::CTLZ: 5027 case ISD::CTLZ_ZERO_UNDEF: 5028 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 5029 C->isOpaque()); 5030 case ISD::CTTZ: 5031 case ISD::CTTZ_ZERO_UNDEF: 5032 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 5033 C->isOpaque()); 5034 case ISD::FP16_TO_FP: 5035 case ISD::BF16_TO_FP: { 5036 bool Ignored; 5037 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf() 5038 : APFloat::BFloat(), 5039 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 5040 5041 // This can return overflow, underflow, or inexact; we don't care. 5042 // FIXME need to be more flexible about rounding mode. 5043 (void)FPV.convert(EVTToAPFloatSemantics(VT), 5044 APFloat::rmNearestTiesToEven, &Ignored); 5045 return getConstantFP(FPV, DL, VT); 5046 } 5047 case ISD::STEP_VECTOR: { 5048 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 5049 return V; 5050 break; 5051 } 5052 } 5053 } 5054 5055 // Constant fold unary operations with a floating point constant operand. 5056 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 5057 APFloat V = C->getValueAPF(); // make copy 5058 switch (Opcode) { 5059 case ISD::FNEG: 5060 V.changeSign(); 5061 return getConstantFP(V, DL, VT); 5062 case ISD::FABS: 5063 V.clearSign(); 5064 return getConstantFP(V, DL, VT); 5065 case ISD::FCEIL: { 5066 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 5067 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5068 return getConstantFP(V, DL, VT); 5069 break; 5070 } 5071 case ISD::FTRUNC: { 5072 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 5073 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5074 return getConstantFP(V, DL, VT); 5075 break; 5076 } 5077 case ISD::FFLOOR: { 5078 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 5079 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5080 return getConstantFP(V, DL, VT); 5081 break; 5082 } 5083 case ISD::FP_EXTEND: { 5084 bool ignored; 5085 // This can return overflow, underflow, or inexact; we don't care. 5086 // FIXME need to be more flexible about rounding mode. 5087 (void)V.convert(EVTToAPFloatSemantics(VT), 5088 APFloat::rmNearestTiesToEven, &ignored); 5089 return getConstantFP(V, DL, VT); 5090 } 5091 case ISD::FP_TO_SINT: 5092 case ISD::FP_TO_UINT: { 5093 bool ignored; 5094 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 5095 // FIXME need to be more flexible about rounding mode. 5096 APFloat::opStatus s = 5097 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 5098 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 5099 break; 5100 return getConstant(IntVal, DL, VT); 5101 } 5102 case ISD::BITCAST: 5103 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 5104 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5105 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 5106 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5107 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 5108 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5109 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 5110 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5111 break; 5112 case ISD::FP_TO_FP16: 5113 case ISD::FP_TO_BF16: { 5114 bool Ignored; 5115 // This can return overflow, underflow, or inexact; we don't care. 5116 // FIXME need to be more flexible about rounding mode. 5117 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf() 5118 : APFloat::BFloat(), 5119 APFloat::rmNearestTiesToEven, &Ignored); 5120 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5121 } 5122 } 5123 } 5124 5125 // Constant fold unary operations with a vector integer or float operand. 5126 switch (Opcode) { 5127 default: 5128 // FIXME: Entirely reasonable to perform folding of other unary 5129 // operations here as the need arises. 5130 break; 5131 case ISD::FNEG: 5132 case ISD::FABS: 5133 case ISD::FCEIL: 5134 case ISD::FTRUNC: 5135 case ISD::FFLOOR: 5136 case ISD::FP_EXTEND: 5137 case ISD::FP_TO_SINT: 5138 case ISD::FP_TO_UINT: 5139 case ISD::TRUNCATE: 5140 case ISD::ANY_EXTEND: 5141 case ISD::ZERO_EXTEND: 5142 case ISD::SIGN_EXTEND: 5143 case ISD::UINT_TO_FP: 5144 case ISD::SINT_TO_FP: 5145 case ISD::ABS: 5146 case ISD::BITREVERSE: 5147 case ISD::BSWAP: 5148 case ISD::CTLZ: 5149 case ISD::CTLZ_ZERO_UNDEF: 5150 case ISD::CTTZ: 5151 case ISD::CTTZ_ZERO_UNDEF: 5152 case ISD::CTPOP: { 5153 SDValue Ops = {Operand}; 5154 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5155 return Fold; 5156 } 5157 } 5158 5159 unsigned OpOpcode = Operand.getNode()->getOpcode(); 5160 switch (Opcode) { 5161 case ISD::STEP_VECTOR: 5162 assert(VT.isScalableVector() && 5163 "STEP_VECTOR can only be used with scalable types"); 5164 assert(OpOpcode == ISD::TargetConstant && 5165 VT.getVectorElementType() == Operand.getValueType() && 5166 "Unexpected step operand"); 5167 break; 5168 case ISD::FREEZE: 5169 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5170 if (isGuaranteedNotToBeUndefOrPoison(Operand)) 5171 return Operand; 5172 break; 5173 case ISD::TokenFactor: 5174 case ISD::MERGE_VALUES: 5175 case ISD::CONCAT_VECTORS: 5176 return Operand; // Factor, merge or concat of one node? No need. 5177 case ISD::BUILD_VECTOR: { 5178 // Attempt to simplify BUILD_VECTOR. 5179 SDValue Ops[] = {Operand}; 5180 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5181 return V; 5182 break; 5183 } 5184 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5185 case ISD::FP_EXTEND: 5186 assert(VT.isFloatingPoint() && 5187 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 5188 if (Operand.getValueType() == VT) return Operand; // noop conversion. 5189 assert((!VT.isVector() || 5190 VT.getVectorElementCount() == 5191 Operand.getValueType().getVectorElementCount()) && 5192 "Vector element count mismatch!"); 5193 assert(Operand.getValueType().bitsLT(VT) && 5194 "Invalid fpext node, dst < src!"); 5195 if (Operand.isUndef()) 5196 return getUNDEF(VT); 5197 break; 5198 case ISD::FP_TO_SINT: 5199 case ISD::FP_TO_UINT: 5200 if (Operand.isUndef()) 5201 return getUNDEF(VT); 5202 break; 5203 case ISD::SINT_TO_FP: 5204 case ISD::UINT_TO_FP: 5205 // [us]itofp(undef) = 0, because the result value is bounded. 5206 if (Operand.isUndef()) 5207 return getConstantFP(0.0, DL, VT); 5208 break; 5209 case ISD::SIGN_EXTEND: 5210 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5211 "Invalid SIGN_EXTEND!"); 5212 assert(VT.isVector() == Operand.getValueType().isVector() && 5213 "SIGN_EXTEND result type type should be vector iff the operand " 5214 "type is vector!"); 5215 if (Operand.getValueType() == VT) return Operand; // noop extension 5216 assert((!VT.isVector() || 5217 VT.getVectorElementCount() == 5218 Operand.getValueType().getVectorElementCount()) && 5219 "Vector element count mismatch!"); 5220 assert(Operand.getValueType().bitsLT(VT) && 5221 "Invalid sext node, dst < src!"); 5222 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5223 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5224 if (OpOpcode == ISD::UNDEF) 5225 // sext(undef) = 0, because the top bits will all be the same. 5226 return getConstant(0, DL, VT); 5227 break; 5228 case ISD::ZERO_EXTEND: 5229 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5230 "Invalid ZERO_EXTEND!"); 5231 assert(VT.isVector() == Operand.getValueType().isVector() && 5232 "ZERO_EXTEND result type type should be vector iff the operand " 5233 "type is vector!"); 5234 if (Operand.getValueType() == VT) return Operand; // noop extension 5235 assert((!VT.isVector() || 5236 VT.getVectorElementCount() == 5237 Operand.getValueType().getVectorElementCount()) && 5238 "Vector element count mismatch!"); 5239 assert(Operand.getValueType().bitsLT(VT) && 5240 "Invalid zext node, dst < src!"); 5241 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5242 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5243 if (OpOpcode == ISD::UNDEF) 5244 // zext(undef) = 0, because the top bits will be zero. 5245 return getConstant(0, DL, VT); 5246 break; 5247 case ISD::ANY_EXTEND: 5248 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5249 "Invalid ANY_EXTEND!"); 5250 assert(VT.isVector() == Operand.getValueType().isVector() && 5251 "ANY_EXTEND result type type should be vector iff the operand " 5252 "type is vector!"); 5253 if (Operand.getValueType() == VT) return Operand; // noop extension 5254 assert((!VT.isVector() || 5255 VT.getVectorElementCount() == 5256 Operand.getValueType().getVectorElementCount()) && 5257 "Vector element count mismatch!"); 5258 assert(Operand.getValueType().bitsLT(VT) && 5259 "Invalid anyext node, dst < src!"); 5260 5261 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5262 OpOpcode == ISD::ANY_EXTEND) 5263 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5264 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5265 if (OpOpcode == ISD::UNDEF) 5266 return getUNDEF(VT); 5267 5268 // (ext (trunc x)) -> x 5269 if (OpOpcode == ISD::TRUNCATE) { 5270 SDValue OpOp = Operand.getOperand(0); 5271 if (OpOp.getValueType() == VT) { 5272 transferDbgValues(Operand, OpOp); 5273 return OpOp; 5274 } 5275 } 5276 break; 5277 case ISD::TRUNCATE: 5278 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5279 "Invalid TRUNCATE!"); 5280 assert(VT.isVector() == Operand.getValueType().isVector() && 5281 "TRUNCATE result type type should be vector iff the operand " 5282 "type is vector!"); 5283 if (Operand.getValueType() == VT) return Operand; // noop truncate 5284 assert((!VT.isVector() || 5285 VT.getVectorElementCount() == 5286 Operand.getValueType().getVectorElementCount()) && 5287 "Vector element count mismatch!"); 5288 assert(Operand.getValueType().bitsGT(VT) && 5289 "Invalid truncate node, src < dst!"); 5290 if (OpOpcode == ISD::TRUNCATE) 5291 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5292 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5293 OpOpcode == ISD::ANY_EXTEND) { 5294 // If the source is smaller than the dest, we still need an extend. 5295 if (Operand.getOperand(0).getValueType().getScalarType() 5296 .bitsLT(VT.getScalarType())) 5297 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5298 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5299 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5300 return Operand.getOperand(0); 5301 } 5302 if (OpOpcode == ISD::UNDEF) 5303 return getUNDEF(VT); 5304 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5305 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5306 break; 5307 case ISD::ANY_EXTEND_VECTOR_INREG: 5308 case ISD::ZERO_EXTEND_VECTOR_INREG: 5309 case ISD::SIGN_EXTEND_VECTOR_INREG: 5310 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5311 assert(Operand.getValueType().bitsLE(VT) && 5312 "The input must be the same size or smaller than the result."); 5313 assert(VT.getVectorMinNumElements() < 5314 Operand.getValueType().getVectorMinNumElements() && 5315 "The destination vector type must have fewer lanes than the input."); 5316 break; 5317 case ISD::ABS: 5318 assert(VT.isInteger() && VT == Operand.getValueType() && 5319 "Invalid ABS!"); 5320 if (OpOpcode == ISD::UNDEF) 5321 return getConstant(0, DL, VT); 5322 break; 5323 case ISD::BSWAP: 5324 assert(VT.isInteger() && VT == Operand.getValueType() && 5325 "Invalid BSWAP!"); 5326 assert((VT.getScalarSizeInBits() % 16 == 0) && 5327 "BSWAP types must be a multiple of 16 bits!"); 5328 if (OpOpcode == ISD::UNDEF) 5329 return getUNDEF(VT); 5330 // bswap(bswap(X)) -> X. 5331 if (OpOpcode == ISD::BSWAP) 5332 return Operand.getOperand(0); 5333 break; 5334 case ISD::BITREVERSE: 5335 assert(VT.isInteger() && VT == Operand.getValueType() && 5336 "Invalid BITREVERSE!"); 5337 if (OpOpcode == ISD::UNDEF) 5338 return getUNDEF(VT); 5339 break; 5340 case ISD::BITCAST: 5341 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5342 "Cannot BITCAST between types of different sizes!"); 5343 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5344 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5345 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5346 if (OpOpcode == ISD::UNDEF) 5347 return getUNDEF(VT); 5348 break; 5349 case ISD::SCALAR_TO_VECTOR: 5350 assert(VT.isVector() && !Operand.getValueType().isVector() && 5351 (VT.getVectorElementType() == Operand.getValueType() || 5352 (VT.getVectorElementType().isInteger() && 5353 Operand.getValueType().isInteger() && 5354 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5355 "Illegal SCALAR_TO_VECTOR node!"); 5356 if (OpOpcode == ISD::UNDEF) 5357 return getUNDEF(VT); 5358 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5359 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5360 isa<ConstantSDNode>(Operand.getOperand(1)) && 5361 Operand.getConstantOperandVal(1) == 0 && 5362 Operand.getOperand(0).getValueType() == VT) 5363 return Operand.getOperand(0); 5364 break; 5365 case ISD::FNEG: 5366 // Negation of an unknown bag of bits is still completely undefined. 5367 if (OpOpcode == ISD::UNDEF) 5368 return getUNDEF(VT); 5369 5370 if (OpOpcode == ISD::FNEG) // --X -> X 5371 return Operand.getOperand(0); 5372 break; 5373 case ISD::FABS: 5374 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5375 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5376 break; 5377 case ISD::VSCALE: 5378 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5379 break; 5380 case ISD::CTPOP: 5381 if (Operand.getValueType().getScalarType() == MVT::i1) 5382 return Operand; 5383 break; 5384 case ISD::CTLZ: 5385 case ISD::CTTZ: 5386 if (Operand.getValueType().getScalarType() == MVT::i1) 5387 return getNOT(DL, Operand, Operand.getValueType()); 5388 break; 5389 case ISD::VECREDUCE_ADD: 5390 if (Operand.getValueType().getScalarType() == MVT::i1) 5391 return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand); 5392 break; 5393 case ISD::VECREDUCE_SMIN: 5394 case ISD::VECREDUCE_UMAX: 5395 if (Operand.getValueType().getScalarType() == MVT::i1) 5396 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5397 break; 5398 case ISD::VECREDUCE_SMAX: 5399 case ISD::VECREDUCE_UMIN: 5400 if (Operand.getValueType().getScalarType() == MVT::i1) 5401 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5402 break; 5403 } 5404 5405 SDNode *N; 5406 SDVTList VTs = getVTList(VT); 5407 SDValue Ops[] = {Operand}; 5408 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5409 FoldingSetNodeID ID; 5410 AddNodeIDNode(ID, Opcode, VTs, Ops); 5411 void *IP = nullptr; 5412 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5413 E->intersectFlagsWith(Flags); 5414 return SDValue(E, 0); 5415 } 5416 5417 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5418 N->setFlags(Flags); 5419 createOperands(N, Ops); 5420 CSEMap.InsertNode(N, IP); 5421 } else { 5422 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5423 createOperands(N, Ops); 5424 } 5425 5426 InsertNode(N); 5427 SDValue V = SDValue(N, 0); 5428 NewSDValueDbgMsg(V, "Creating new node: ", this); 5429 return V; 5430 } 5431 5432 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5433 const APInt &C2) { 5434 switch (Opcode) { 5435 case ISD::ADD: return C1 + C2; 5436 case ISD::SUB: return C1 - C2; 5437 case ISD::MUL: return C1 * C2; 5438 case ISD::AND: return C1 & C2; 5439 case ISD::OR: return C1 | C2; 5440 case ISD::XOR: return C1 ^ C2; 5441 case ISD::SHL: return C1 << C2; 5442 case ISD::SRL: return C1.lshr(C2); 5443 case ISD::SRA: return C1.ashr(C2); 5444 case ISD::ROTL: return C1.rotl(C2); 5445 case ISD::ROTR: return C1.rotr(C2); 5446 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5447 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5448 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5449 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5450 case ISD::SADDSAT: return C1.sadd_sat(C2); 5451 case ISD::UADDSAT: return C1.uadd_sat(C2); 5452 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5453 case ISD::USUBSAT: return C1.usub_sat(C2); 5454 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5455 case ISD::USHLSAT: return C1.ushl_sat(C2); 5456 case ISD::UDIV: 5457 if (!C2.getBoolValue()) 5458 break; 5459 return C1.udiv(C2); 5460 case ISD::UREM: 5461 if (!C2.getBoolValue()) 5462 break; 5463 return C1.urem(C2); 5464 case ISD::SDIV: 5465 if (!C2.getBoolValue()) 5466 break; 5467 return C1.sdiv(C2); 5468 case ISD::SREM: 5469 if (!C2.getBoolValue()) 5470 break; 5471 return C1.srem(C2); 5472 case ISD::MULHS: { 5473 unsigned FullWidth = C1.getBitWidth() * 2; 5474 APInt C1Ext = C1.sext(FullWidth); 5475 APInt C2Ext = C2.sext(FullWidth); 5476 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5477 } 5478 case ISD::MULHU: { 5479 unsigned FullWidth = C1.getBitWidth() * 2; 5480 APInt C1Ext = C1.zext(FullWidth); 5481 APInt C2Ext = C2.zext(FullWidth); 5482 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5483 } 5484 case ISD::AVGFLOORS: { 5485 unsigned FullWidth = C1.getBitWidth() + 1; 5486 APInt C1Ext = C1.sext(FullWidth); 5487 APInt C2Ext = C2.sext(FullWidth); 5488 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5489 } 5490 case ISD::AVGFLOORU: { 5491 unsigned FullWidth = C1.getBitWidth() + 1; 5492 APInt C1Ext = C1.zext(FullWidth); 5493 APInt C2Ext = C2.zext(FullWidth); 5494 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5495 } 5496 case ISD::AVGCEILS: { 5497 unsigned FullWidth = C1.getBitWidth() + 1; 5498 APInt C1Ext = C1.sext(FullWidth); 5499 APInt C2Ext = C2.sext(FullWidth); 5500 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5501 } 5502 case ISD::AVGCEILU: { 5503 unsigned FullWidth = C1.getBitWidth() + 1; 5504 APInt C1Ext = C1.zext(FullWidth); 5505 APInt C2Ext = C2.zext(FullWidth); 5506 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5507 } 5508 } 5509 return llvm::None; 5510 } 5511 5512 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5513 const GlobalAddressSDNode *GA, 5514 const SDNode *N2) { 5515 if (GA->getOpcode() != ISD::GlobalAddress) 5516 return SDValue(); 5517 if (!TLI->isOffsetFoldingLegal(GA)) 5518 return SDValue(); 5519 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5520 if (!C2) 5521 return SDValue(); 5522 int64_t Offset = C2->getSExtValue(); 5523 switch (Opcode) { 5524 case ISD::ADD: break; 5525 case ISD::SUB: Offset = -uint64_t(Offset); break; 5526 default: return SDValue(); 5527 } 5528 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5529 GA->getOffset() + uint64_t(Offset)); 5530 } 5531 5532 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5533 switch (Opcode) { 5534 case ISD::SDIV: 5535 case ISD::UDIV: 5536 case ISD::SREM: 5537 case ISD::UREM: { 5538 // If a divisor is zero/undef or any element of a divisor vector is 5539 // zero/undef, the whole op is undef. 5540 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5541 SDValue Divisor = Ops[1]; 5542 if (Divisor.isUndef() || isNullConstant(Divisor)) 5543 return true; 5544 5545 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5546 llvm::any_of(Divisor->op_values(), 5547 [](SDValue V) { return V.isUndef() || 5548 isNullConstant(V); }); 5549 // TODO: Handle signed overflow. 5550 } 5551 // TODO: Handle oversized shifts. 5552 default: 5553 return false; 5554 } 5555 } 5556 5557 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5558 EVT VT, ArrayRef<SDValue> Ops) { 5559 // If the opcode is a target-specific ISD node, there's nothing we can 5560 // do here and the operand rules may not line up with the below, so 5561 // bail early. 5562 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5563 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5564 // foldCONCAT_VECTORS in getNode before this is called. 5565 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5566 return SDValue(); 5567 5568 unsigned NumOps = Ops.size(); 5569 if (NumOps == 0) 5570 return SDValue(); 5571 5572 if (isUndef(Opcode, Ops)) 5573 return getUNDEF(VT); 5574 5575 // Handle binops special cases. 5576 if (NumOps == 2) { 5577 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5578 return CFP; 5579 5580 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5581 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5582 if (C1->isOpaque() || C2->isOpaque()) 5583 return SDValue(); 5584 5585 Optional<APInt> FoldAttempt = 5586 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5587 if (!FoldAttempt) 5588 return SDValue(); 5589 5590 SDValue Folded = getConstant(*FoldAttempt, DL, VT); 5591 assert((!Folded || !VT.isVector()) && 5592 "Can't fold vectors ops with scalar operands"); 5593 return Folded; 5594 } 5595 } 5596 5597 // fold (add Sym, c) -> Sym+c 5598 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5599 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5600 if (TLI->isCommutativeBinOp(Opcode)) 5601 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5602 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5603 } 5604 5605 // This is for vector folding only from here on. 5606 if (!VT.isVector()) 5607 return SDValue(); 5608 5609 ElementCount NumElts = VT.getVectorElementCount(); 5610 5611 // See if we can fold through bitcasted integer ops. 5612 // TODO: Can we handle undef elements? 5613 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5614 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5615 Ops[0].getOpcode() == ISD::BITCAST && 5616 Ops[1].getOpcode() == ISD::BITCAST) { 5617 SDValue N1 = peekThroughBitcasts(Ops[0]); 5618 SDValue N2 = peekThroughBitcasts(Ops[1]); 5619 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5620 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5621 EVT BVVT = N1.getValueType(); 5622 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5623 bool IsLE = getDataLayout().isLittleEndian(); 5624 unsigned EltBits = VT.getScalarSizeInBits(); 5625 SmallVector<APInt> RawBits1, RawBits2; 5626 BitVector UndefElts1, UndefElts2; 5627 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5628 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5629 UndefElts1.none() && UndefElts2.none()) { 5630 SmallVector<APInt> RawBits; 5631 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5632 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5633 if (!Fold) 5634 break; 5635 RawBits.push_back(*Fold); 5636 } 5637 if (RawBits.size() == NumElts.getFixedValue()) { 5638 // We have constant folded, but we need to cast this again back to 5639 // the original (possibly legalized) type. 5640 SmallVector<APInt> DstBits; 5641 BitVector DstUndefs; 5642 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5643 DstBits, RawBits, DstUndefs, 5644 BitVector(RawBits.size(), false)); 5645 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5646 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5647 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5648 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5649 if (DstUndefs[I]) 5650 continue; 5651 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT); 5652 } 5653 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5654 } 5655 } 5656 } 5657 } 5658 5659 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5660 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5661 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5662 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5663 APInt RHSVal; 5664 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5665 APInt NewStep = Opcode == ISD::MUL 5666 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5667 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5668 return getStepVector(DL, VT, NewStep); 5669 } 5670 } 5671 5672 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5673 return !Op.getValueType().isVector() || 5674 Op.getValueType().getVectorElementCount() == NumElts; 5675 }; 5676 5677 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5678 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5679 Op.getOpcode() == ISD::BUILD_VECTOR || 5680 Op.getOpcode() == ISD::SPLAT_VECTOR; 5681 }; 5682 5683 // All operands must be vector types with the same number of elements as 5684 // the result type and must be either UNDEF or a build/splat vector 5685 // or UNDEF scalars. 5686 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5687 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5688 return SDValue(); 5689 5690 // If we are comparing vectors, then the result needs to be a i1 boolean that 5691 // is then extended back to the legal result type depending on how booleans 5692 // are represented. 5693 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5694 ISD::NodeType ExtendCode = 5695 (Opcode == ISD::SETCC && SVT != VT.getScalarType()) 5696 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT)) 5697 : ISD::SIGN_EXTEND; 5698 5699 // Find legal integer scalar type for constant promotion and 5700 // ensure that its scalar size is at least as large as source. 5701 EVT LegalSVT = VT.getScalarType(); 5702 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5703 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5704 if (LegalSVT.bitsLT(VT.getScalarType())) 5705 return SDValue(); 5706 } 5707 5708 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5709 // only have one operand to check. For fixed-length vector types we may have 5710 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5711 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5712 5713 // Constant fold each scalar lane separately. 5714 SmallVector<SDValue, 4> ScalarResults; 5715 for (unsigned I = 0; I != NumVectorElts; I++) { 5716 SmallVector<SDValue, 4> ScalarOps; 5717 for (SDValue Op : Ops) { 5718 EVT InSVT = Op.getValueType().getScalarType(); 5719 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5720 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5721 if (Op.isUndef()) 5722 ScalarOps.push_back(getUNDEF(InSVT)); 5723 else 5724 ScalarOps.push_back(Op); 5725 continue; 5726 } 5727 5728 SDValue ScalarOp = 5729 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5730 EVT ScalarVT = ScalarOp.getValueType(); 5731 5732 // Build vector (integer) scalar operands may need implicit 5733 // truncation - do this before constant folding. 5734 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 5735 // Don't create illegally-typed nodes unless they're constants or undef 5736 // - if we fail to constant fold we can't guarantee the (dead) nodes 5737 // we're creating will be cleaned up before being visited for 5738 // legalization. 5739 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 5740 !isa<ConstantSDNode>(ScalarOp) && 5741 TLI->getTypeAction(*getContext(), InSVT) != 5742 TargetLowering::TypeLegal) 5743 return SDValue(); 5744 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5745 } 5746 5747 ScalarOps.push_back(ScalarOp); 5748 } 5749 5750 // Constant fold the scalar operands. 5751 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5752 5753 // Legalize the (integer) scalar constant if necessary. 5754 if (LegalSVT != SVT) 5755 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult); 5756 5757 // Scalar folding only succeeded if the result is a constant or UNDEF. 5758 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5759 ScalarResult.getOpcode() != ISD::ConstantFP) 5760 return SDValue(); 5761 ScalarResults.push_back(ScalarResult); 5762 } 5763 5764 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5765 : getBuildVector(VT, DL, ScalarResults); 5766 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5767 return V; 5768 } 5769 5770 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5771 EVT VT, SDValue N1, SDValue N2) { 5772 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5773 // should. That will require dealing with a potentially non-default 5774 // rounding mode, checking the "opStatus" return value from the APFloat 5775 // math calculations, and possibly other variations. 5776 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5777 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5778 if (N1CFP && N2CFP) { 5779 APFloat C1 = N1CFP->getValueAPF(); // make copy 5780 const APFloat &C2 = N2CFP->getValueAPF(); 5781 switch (Opcode) { 5782 case ISD::FADD: 5783 C1.add(C2, APFloat::rmNearestTiesToEven); 5784 return getConstantFP(C1, DL, VT); 5785 case ISD::FSUB: 5786 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5787 return getConstantFP(C1, DL, VT); 5788 case ISD::FMUL: 5789 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5790 return getConstantFP(C1, DL, VT); 5791 case ISD::FDIV: 5792 C1.divide(C2, APFloat::rmNearestTiesToEven); 5793 return getConstantFP(C1, DL, VT); 5794 case ISD::FREM: 5795 C1.mod(C2); 5796 return getConstantFP(C1, DL, VT); 5797 case ISD::FCOPYSIGN: 5798 C1.copySign(C2); 5799 return getConstantFP(C1, DL, VT); 5800 case ISD::FMINNUM: 5801 return getConstantFP(minnum(C1, C2), DL, VT); 5802 case ISD::FMAXNUM: 5803 return getConstantFP(maxnum(C1, C2), DL, VT); 5804 case ISD::FMINIMUM: 5805 return getConstantFP(minimum(C1, C2), DL, VT); 5806 case ISD::FMAXIMUM: 5807 return getConstantFP(maximum(C1, C2), DL, VT); 5808 default: break; 5809 } 5810 } 5811 if (N1CFP && Opcode == ISD::FP_ROUND) { 5812 APFloat C1 = N1CFP->getValueAPF(); // make copy 5813 bool Unused; 5814 // This can return overflow, underflow, or inexact; we don't care. 5815 // FIXME need to be more flexible about rounding mode. 5816 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5817 &Unused); 5818 return getConstantFP(C1, DL, VT); 5819 } 5820 5821 switch (Opcode) { 5822 case ISD::FSUB: 5823 // -0.0 - undef --> undef (consistent with "fneg undef") 5824 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5825 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5826 return getUNDEF(VT); 5827 LLVM_FALLTHROUGH; 5828 5829 case ISD::FADD: 5830 case ISD::FMUL: 5831 case ISD::FDIV: 5832 case ISD::FREM: 5833 // If both operands are undef, the result is undef. If 1 operand is undef, 5834 // the result is NaN. This should match the behavior of the IR optimizer. 5835 if (N1.isUndef() && N2.isUndef()) 5836 return getUNDEF(VT); 5837 if (N1.isUndef() || N2.isUndef()) 5838 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5839 } 5840 return SDValue(); 5841 } 5842 5843 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5844 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5845 5846 // There's no need to assert on a byte-aligned pointer. All pointers are at 5847 // least byte aligned. 5848 if (A == Align(1)) 5849 return Val; 5850 5851 FoldingSetNodeID ID; 5852 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5853 ID.AddInteger(A.value()); 5854 5855 void *IP = nullptr; 5856 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5857 return SDValue(E, 0); 5858 5859 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5860 Val.getValueType(), A); 5861 createOperands(N, {Val}); 5862 5863 CSEMap.InsertNode(N, IP); 5864 InsertNode(N); 5865 5866 SDValue V(N, 0); 5867 NewSDValueDbgMsg(V, "Creating new node: ", this); 5868 return V; 5869 } 5870 5871 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5872 SDValue N1, SDValue N2) { 5873 SDNodeFlags Flags; 5874 if (Inserter) 5875 Flags = Inserter->getFlags(); 5876 return getNode(Opcode, DL, VT, N1, N2, Flags); 5877 } 5878 5879 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5880 SDValue &N2) const { 5881 if (!TLI->isCommutativeBinOp(Opcode)) 5882 return; 5883 5884 // Canonicalize: 5885 // binop(const, nonconst) -> binop(nonconst, const) 5886 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5887 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5888 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5889 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5890 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5891 std::swap(N1, N2); 5892 5893 // Canonicalize: 5894 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5895 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5896 N2.getOpcode() == ISD::STEP_VECTOR) 5897 std::swap(N1, N2); 5898 } 5899 5900 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5901 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5902 assert(N1.getOpcode() != ISD::DELETED_NODE && 5903 N2.getOpcode() != ISD::DELETED_NODE && 5904 "Operand is DELETED_NODE!"); 5905 5906 canonicalizeCommutativeBinop(Opcode, N1, N2); 5907 5908 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5909 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5910 5911 // Don't allow undefs in vector splats - we might be returning N2 when folding 5912 // to zero etc. 5913 ConstantSDNode *N2CV = 5914 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5915 5916 switch (Opcode) { 5917 default: break; 5918 case ISD::TokenFactor: 5919 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5920 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5921 // Fold trivial token factors. 5922 if (N1.getOpcode() == ISD::EntryToken) return N2; 5923 if (N2.getOpcode() == ISD::EntryToken) return N1; 5924 if (N1 == N2) return N1; 5925 break; 5926 case ISD::BUILD_VECTOR: { 5927 // Attempt to simplify BUILD_VECTOR. 5928 SDValue Ops[] = {N1, N2}; 5929 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5930 return V; 5931 break; 5932 } 5933 case ISD::CONCAT_VECTORS: { 5934 SDValue Ops[] = {N1, N2}; 5935 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5936 return V; 5937 break; 5938 } 5939 case ISD::AND: 5940 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5941 assert(N1.getValueType() == N2.getValueType() && 5942 N1.getValueType() == VT && "Binary operator types must match!"); 5943 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5944 // worth handling here. 5945 if (N2CV && N2CV->isZero()) 5946 return N2; 5947 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5948 return N1; 5949 break; 5950 case ISD::OR: 5951 case ISD::XOR: 5952 case ISD::ADD: 5953 case ISD::SUB: 5954 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5955 assert(N1.getValueType() == N2.getValueType() && 5956 N1.getValueType() == VT && "Binary operator types must match!"); 5957 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5958 // it's worth handling here. 5959 if (N2CV && N2CV->isZero()) 5960 return N1; 5961 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5962 VT.getVectorElementType() == MVT::i1) 5963 return getNode(ISD::XOR, DL, VT, N1, N2); 5964 break; 5965 case ISD::MUL: 5966 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5967 assert(N1.getValueType() == N2.getValueType() && 5968 N1.getValueType() == VT && "Binary operator types must match!"); 5969 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5970 return getNode(ISD::AND, DL, VT, N1, N2); 5971 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5972 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5973 const APInt &N2CImm = N2C->getAPIntValue(); 5974 return getVScale(DL, VT, MulImm * N2CImm); 5975 } 5976 break; 5977 case ISD::UDIV: 5978 case ISD::UREM: 5979 case ISD::MULHU: 5980 case ISD::MULHS: 5981 case ISD::SDIV: 5982 case ISD::SREM: 5983 case ISD::SADDSAT: 5984 case ISD::SSUBSAT: 5985 case ISD::UADDSAT: 5986 case ISD::USUBSAT: 5987 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5988 assert(N1.getValueType() == N2.getValueType() && 5989 N1.getValueType() == VT && "Binary operator types must match!"); 5990 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5991 // fold (add_sat x, y) -> (or x, y) for bool types. 5992 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5993 return getNode(ISD::OR, DL, VT, N1, N2); 5994 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5995 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5996 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5997 } 5998 break; 5999 case ISD::SMIN: 6000 case ISD::UMAX: 6001 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6002 assert(N1.getValueType() == N2.getValueType() && 6003 N1.getValueType() == VT && "Binary operator types must match!"); 6004 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6005 return getNode(ISD::OR, DL, VT, N1, N2); 6006 break; 6007 case ISD::SMAX: 6008 case ISD::UMIN: 6009 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6010 assert(N1.getValueType() == N2.getValueType() && 6011 N1.getValueType() == VT && "Binary operator types must match!"); 6012 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6013 return getNode(ISD::AND, DL, VT, N1, N2); 6014 break; 6015 case ISD::FADD: 6016 case ISD::FSUB: 6017 case ISD::FMUL: 6018 case ISD::FDIV: 6019 case ISD::FREM: 6020 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6021 assert(N1.getValueType() == N2.getValueType() && 6022 N1.getValueType() == VT && "Binary operator types must match!"); 6023 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 6024 return V; 6025 break; 6026 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 6027 assert(N1.getValueType() == VT && 6028 N1.getValueType().isFloatingPoint() && 6029 N2.getValueType().isFloatingPoint() && 6030 "Invalid FCOPYSIGN!"); 6031 break; 6032 case ISD::SHL: 6033 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 6034 const APInt &MulImm = N1->getConstantOperandAPInt(0); 6035 const APInt &ShiftImm = N2C->getAPIntValue(); 6036 return getVScale(DL, VT, MulImm << ShiftImm); 6037 } 6038 LLVM_FALLTHROUGH; 6039 case ISD::SRA: 6040 case ISD::SRL: 6041 if (SDValue V = simplifyShift(N1, N2)) 6042 return V; 6043 LLVM_FALLTHROUGH; 6044 case ISD::ROTL: 6045 case ISD::ROTR: 6046 assert(VT == N1.getValueType() && 6047 "Shift operators return type must be the same as their first arg"); 6048 assert(VT.isInteger() && N2.getValueType().isInteger() && 6049 "Shifts only work on integers"); 6050 assert((!VT.isVector() || VT == N2.getValueType()) && 6051 "Vector shift amounts must be in the same as their first arg"); 6052 // Verify that the shift amount VT is big enough to hold valid shift 6053 // amounts. This catches things like trying to shift an i1024 value by an 6054 // i8, which is easy to fall into in generic code that uses 6055 // TLI.getShiftAmount(). 6056 assert(N2.getValueType().getScalarSizeInBits() >= 6057 Log2_32_Ceil(VT.getScalarSizeInBits()) && 6058 "Invalid use of small shift amount with oversized value!"); 6059 6060 // Always fold shifts of i1 values so the code generator doesn't need to 6061 // handle them. Since we know the size of the shift has to be less than the 6062 // size of the value, the shift/rotate count is guaranteed to be zero. 6063 if (VT == MVT::i1) 6064 return N1; 6065 if (N2CV && N2CV->isZero()) 6066 return N1; 6067 break; 6068 case ISD::FP_ROUND: 6069 assert(VT.isFloatingPoint() && 6070 N1.getValueType().isFloatingPoint() && 6071 VT.bitsLE(N1.getValueType()) && 6072 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 6073 "Invalid FP_ROUND!"); 6074 if (N1.getValueType() == VT) return N1; // noop conversion. 6075 break; 6076 case ISD::AssertSext: 6077 case ISD::AssertZext: { 6078 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6079 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6080 assert(VT.isInteger() && EVT.isInteger() && 6081 "Cannot *_EXTEND_INREG FP types"); 6082 assert(!EVT.isVector() && 6083 "AssertSExt/AssertZExt type should be the vector element type " 6084 "rather than the vector type!"); 6085 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 6086 if (VT.getScalarType() == EVT) return N1; // noop assertion. 6087 break; 6088 } 6089 case ISD::SIGN_EXTEND_INREG: { 6090 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6091 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6092 assert(VT.isInteger() && EVT.isInteger() && 6093 "Cannot *_EXTEND_INREG FP types"); 6094 assert(EVT.isVector() == VT.isVector() && 6095 "SIGN_EXTEND_INREG type should be vector iff the operand " 6096 "type is vector!"); 6097 assert((!EVT.isVector() || 6098 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 6099 "Vector element counts must match in SIGN_EXTEND_INREG"); 6100 assert(EVT.bitsLE(VT) && "Not extending!"); 6101 if (EVT == VT) return N1; // Not actually extending 6102 6103 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 6104 unsigned FromBits = EVT.getScalarSizeInBits(); 6105 Val <<= Val.getBitWidth() - FromBits; 6106 Val.ashrInPlace(Val.getBitWidth() - FromBits); 6107 return getConstant(Val, DL, ConstantVT); 6108 }; 6109 6110 if (N1C) { 6111 const APInt &Val = N1C->getAPIntValue(); 6112 return SignExtendInReg(Val, VT); 6113 } 6114 6115 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 6116 SmallVector<SDValue, 8> Ops; 6117 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 6118 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6119 SDValue Op = N1.getOperand(i); 6120 if (Op.isUndef()) { 6121 Ops.push_back(getUNDEF(OpVT)); 6122 continue; 6123 } 6124 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6125 APInt Val = C->getAPIntValue(); 6126 Ops.push_back(SignExtendInReg(Val, OpVT)); 6127 } 6128 return getBuildVector(VT, DL, Ops); 6129 } 6130 break; 6131 } 6132 case ISD::FP_TO_SINT_SAT: 6133 case ISD::FP_TO_UINT_SAT: { 6134 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6135 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6136 assert(N1.getValueType().isVector() == VT.isVector() && 6137 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6138 "vector!"); 6139 assert((!VT.isVector() || VT.getVectorElementCount() == 6140 N1.getValueType().getVectorElementCount()) && 6141 "Vector element counts must match in FP_TO_*INT_SAT"); 6142 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6143 "Type to saturate to must be a scalar."); 6144 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6145 "Not extending!"); 6146 break; 6147 } 6148 case ISD::EXTRACT_VECTOR_ELT: 6149 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6150 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6151 element type of the vector."); 6152 6153 // Extract from an undefined value or using an undefined index is undefined. 6154 if (N1.isUndef() || N2.isUndef()) 6155 return getUNDEF(VT); 6156 6157 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6158 // vectors. For scalable vectors we will provide appropriate support for 6159 // dealing with arbitrary indices. 6160 if (N2C && N1.getValueType().isFixedLengthVector() && 6161 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6162 return getUNDEF(VT); 6163 6164 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6165 // expanding copies of large vectors from registers. This only works for 6166 // fixed length vectors, since we need to know the exact number of 6167 // elements. 6168 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6169 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6170 unsigned Factor = 6171 N1.getOperand(0).getValueType().getVectorNumElements(); 6172 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6173 N1.getOperand(N2C->getZExtValue() / Factor), 6174 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6175 } 6176 6177 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6178 // lowering is expanding large vector constants. 6179 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6180 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6181 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6182 N1.getValueType().isFixedLengthVector()) && 6183 "BUILD_VECTOR used for scalable vectors"); 6184 unsigned Index = 6185 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6186 SDValue Elt = N1.getOperand(Index); 6187 6188 if (VT != Elt.getValueType()) 6189 // If the vector element type is not legal, the BUILD_VECTOR operands 6190 // are promoted and implicitly truncated, and the result implicitly 6191 // extended. Make that explicit here. 6192 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6193 6194 return Elt; 6195 } 6196 6197 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6198 // operations are lowered to scalars. 6199 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6200 // If the indices are the same, return the inserted element else 6201 // if the indices are known different, extract the element from 6202 // the original vector. 6203 SDValue N1Op2 = N1.getOperand(2); 6204 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6205 6206 if (N1Op2C && N2C) { 6207 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6208 if (VT == N1.getOperand(1).getValueType()) 6209 return N1.getOperand(1); 6210 if (VT.isFloatingPoint()) { 6211 assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits()); 6212 return getFPExtendOrRound(N1.getOperand(1), DL, VT); 6213 } 6214 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6215 } 6216 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6217 } 6218 } 6219 6220 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6221 // when vector types are scalarized and v1iX is legal. 6222 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6223 // Here we are completely ignoring the extract element index (N2), 6224 // which is fine for fixed width vectors, since any index other than 0 6225 // is undefined anyway. However, this cannot be ignored for scalable 6226 // vectors - in theory we could support this, but we don't want to do this 6227 // without a profitability check. 6228 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6229 N1.getValueType().isFixedLengthVector() && 6230 N1.getValueType().getVectorNumElements() == 1) { 6231 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6232 N1.getOperand(1)); 6233 } 6234 break; 6235 case ISD::EXTRACT_ELEMENT: 6236 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6237 assert(!N1.getValueType().isVector() && !VT.isVector() && 6238 (N1.getValueType().isInteger() == VT.isInteger()) && 6239 N1.getValueType() != VT && 6240 "Wrong types for EXTRACT_ELEMENT!"); 6241 6242 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6243 // 64-bit integers into 32-bit parts. Instead of building the extract of 6244 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6245 if (N1.getOpcode() == ISD::BUILD_PAIR) 6246 return N1.getOperand(N2C->getZExtValue()); 6247 6248 // EXTRACT_ELEMENT of a constant int is also very common. 6249 if (N1C) { 6250 unsigned ElementSize = VT.getSizeInBits(); 6251 unsigned Shift = ElementSize * N2C->getZExtValue(); 6252 const APInt &Val = N1C->getAPIntValue(); 6253 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6254 } 6255 break; 6256 case ISD::EXTRACT_SUBVECTOR: { 6257 EVT N1VT = N1.getValueType(); 6258 assert(VT.isVector() && N1VT.isVector() && 6259 "Extract subvector VTs must be vectors!"); 6260 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6261 "Extract subvector VTs must have the same element type!"); 6262 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6263 "Cannot extract a scalable vector from a fixed length vector!"); 6264 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6265 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6266 "Extract subvector must be from larger vector to smaller vector!"); 6267 assert(N2C && "Extract subvector index must be a constant"); 6268 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6269 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6270 N1VT.getVectorMinNumElements()) && 6271 "Extract subvector overflow!"); 6272 assert(N2C->getAPIntValue().getBitWidth() == 6273 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6274 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6275 6276 // Trivial extraction. 6277 if (VT == N1VT) 6278 return N1; 6279 6280 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6281 if (N1.isUndef()) 6282 return getUNDEF(VT); 6283 6284 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6285 // the concat have the same type as the extract. 6286 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6287 VT == N1.getOperand(0).getValueType()) { 6288 unsigned Factor = VT.getVectorMinNumElements(); 6289 return N1.getOperand(N2C->getZExtValue() / Factor); 6290 } 6291 6292 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6293 // during shuffle legalization. 6294 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6295 VT == N1.getOperand(1).getValueType()) 6296 return N1.getOperand(1); 6297 break; 6298 } 6299 } 6300 6301 // Perform trivial constant folding. 6302 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6303 return SV; 6304 6305 // Canonicalize an UNDEF to the RHS, even over a constant. 6306 if (N1.isUndef()) { 6307 if (TLI->isCommutativeBinOp(Opcode)) { 6308 std::swap(N1, N2); 6309 } else { 6310 switch (Opcode) { 6311 case ISD::SUB: 6312 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6313 case ISD::SIGN_EXTEND_INREG: 6314 case ISD::UDIV: 6315 case ISD::SDIV: 6316 case ISD::UREM: 6317 case ISD::SREM: 6318 case ISD::SSUBSAT: 6319 case ISD::USUBSAT: 6320 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6321 } 6322 } 6323 } 6324 6325 // Fold a bunch of operators when the RHS is undef. 6326 if (N2.isUndef()) { 6327 switch (Opcode) { 6328 case ISD::XOR: 6329 if (N1.isUndef()) 6330 // Handle undef ^ undef -> 0 special case. This is a common 6331 // idiom (misuse). 6332 return getConstant(0, DL, VT); 6333 LLVM_FALLTHROUGH; 6334 case ISD::ADD: 6335 case ISD::SUB: 6336 case ISD::UDIV: 6337 case ISD::SDIV: 6338 case ISD::UREM: 6339 case ISD::SREM: 6340 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6341 case ISD::MUL: 6342 case ISD::AND: 6343 case ISD::SSUBSAT: 6344 case ISD::USUBSAT: 6345 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6346 case ISD::OR: 6347 case ISD::SADDSAT: 6348 case ISD::UADDSAT: 6349 return getAllOnesConstant(DL, VT); 6350 } 6351 } 6352 6353 // Memoize this node if possible. 6354 SDNode *N; 6355 SDVTList VTs = getVTList(VT); 6356 SDValue Ops[] = {N1, N2}; 6357 if (VT != MVT::Glue) { 6358 FoldingSetNodeID ID; 6359 AddNodeIDNode(ID, Opcode, VTs, Ops); 6360 void *IP = nullptr; 6361 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6362 E->intersectFlagsWith(Flags); 6363 return SDValue(E, 0); 6364 } 6365 6366 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6367 N->setFlags(Flags); 6368 createOperands(N, Ops); 6369 CSEMap.InsertNode(N, IP); 6370 } else { 6371 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6372 createOperands(N, Ops); 6373 } 6374 6375 InsertNode(N); 6376 SDValue V = SDValue(N, 0); 6377 NewSDValueDbgMsg(V, "Creating new node: ", this); 6378 return V; 6379 } 6380 6381 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6382 SDValue N1, SDValue N2, SDValue N3) { 6383 SDNodeFlags Flags; 6384 if (Inserter) 6385 Flags = Inserter->getFlags(); 6386 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6387 } 6388 6389 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6390 SDValue N1, SDValue N2, SDValue N3, 6391 const SDNodeFlags Flags) { 6392 assert(N1.getOpcode() != ISD::DELETED_NODE && 6393 N2.getOpcode() != ISD::DELETED_NODE && 6394 N3.getOpcode() != ISD::DELETED_NODE && 6395 "Operand is DELETED_NODE!"); 6396 // Perform various simplifications. 6397 switch (Opcode) { 6398 case ISD::FMA: { 6399 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6400 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6401 N3.getValueType() == VT && "FMA types must match!"); 6402 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6403 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6404 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6405 if (N1CFP && N2CFP && N3CFP) { 6406 APFloat V1 = N1CFP->getValueAPF(); 6407 const APFloat &V2 = N2CFP->getValueAPF(); 6408 const APFloat &V3 = N3CFP->getValueAPF(); 6409 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6410 return getConstantFP(V1, DL, VT); 6411 } 6412 break; 6413 } 6414 case ISD::BUILD_VECTOR: { 6415 // Attempt to simplify BUILD_VECTOR. 6416 SDValue Ops[] = {N1, N2, N3}; 6417 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6418 return V; 6419 break; 6420 } 6421 case ISD::CONCAT_VECTORS: { 6422 SDValue Ops[] = {N1, N2, N3}; 6423 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6424 return V; 6425 break; 6426 } 6427 case ISD::SETCC: { 6428 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6429 assert(N1.getValueType() == N2.getValueType() && 6430 "SETCC operands must have the same type!"); 6431 assert(VT.isVector() == N1.getValueType().isVector() && 6432 "SETCC type should be vector iff the operand type is vector!"); 6433 assert((!VT.isVector() || VT.getVectorElementCount() == 6434 N1.getValueType().getVectorElementCount()) && 6435 "SETCC vector element counts must match!"); 6436 // Use FoldSetCC to simplify SETCC's. 6437 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6438 return V; 6439 // Vector constant folding. 6440 SDValue Ops[] = {N1, N2, N3}; 6441 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6442 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6443 return V; 6444 } 6445 break; 6446 } 6447 case ISD::SELECT: 6448 case ISD::VSELECT: 6449 if (SDValue V = simplifySelect(N1, N2, N3)) 6450 return V; 6451 break; 6452 case ISD::VECTOR_SHUFFLE: 6453 llvm_unreachable("should use getVectorShuffle constructor!"); 6454 case ISD::VECTOR_SPLICE: { 6455 if (cast<ConstantSDNode>(N3)->isNullValue()) 6456 return N1; 6457 break; 6458 } 6459 case ISD::INSERT_VECTOR_ELT: { 6460 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6461 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6462 // for scalable vectors where we will generate appropriate code to 6463 // deal with out-of-bounds cases correctly. 6464 if (N3C && N1.getValueType().isFixedLengthVector() && 6465 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6466 return getUNDEF(VT); 6467 6468 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6469 if (N3.isUndef()) 6470 return getUNDEF(VT); 6471 6472 // If the inserted element is an UNDEF, just use the input vector. 6473 if (N2.isUndef()) 6474 return N1; 6475 6476 break; 6477 } 6478 case ISD::INSERT_SUBVECTOR: { 6479 // Inserting undef into undef is still undef. 6480 if (N1.isUndef() && N2.isUndef()) 6481 return getUNDEF(VT); 6482 6483 EVT N2VT = N2.getValueType(); 6484 assert(VT == N1.getValueType() && 6485 "Dest and insert subvector source types must match!"); 6486 assert(VT.isVector() && N2VT.isVector() && 6487 "Insert subvector VTs must be vectors!"); 6488 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6489 "Cannot insert a scalable vector into a fixed length vector!"); 6490 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6491 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6492 "Insert subvector must be from smaller vector to larger vector!"); 6493 assert(isa<ConstantSDNode>(N3) && 6494 "Insert subvector index must be constant"); 6495 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6496 (N2VT.getVectorMinNumElements() + 6497 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6498 VT.getVectorMinNumElements()) && 6499 "Insert subvector overflow!"); 6500 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6501 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6502 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6503 6504 // Trivial insertion. 6505 if (VT == N2VT) 6506 return N2; 6507 6508 // If this is an insert of an extracted vector into an undef vector, we 6509 // can just use the input to the extract. 6510 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6511 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6512 return N2.getOperand(0); 6513 break; 6514 } 6515 case ISD::BITCAST: 6516 // Fold bit_convert nodes from a type to themselves. 6517 if (N1.getValueType() == VT) 6518 return N1; 6519 break; 6520 } 6521 6522 // Memoize node if it doesn't produce a flag. 6523 SDNode *N; 6524 SDVTList VTs = getVTList(VT); 6525 SDValue Ops[] = {N1, N2, N3}; 6526 if (VT != MVT::Glue) { 6527 FoldingSetNodeID ID; 6528 AddNodeIDNode(ID, Opcode, VTs, Ops); 6529 void *IP = nullptr; 6530 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6531 E->intersectFlagsWith(Flags); 6532 return SDValue(E, 0); 6533 } 6534 6535 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6536 N->setFlags(Flags); 6537 createOperands(N, Ops); 6538 CSEMap.InsertNode(N, IP); 6539 } else { 6540 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6541 createOperands(N, Ops); 6542 } 6543 6544 InsertNode(N); 6545 SDValue V = SDValue(N, 0); 6546 NewSDValueDbgMsg(V, "Creating new node: ", this); 6547 return V; 6548 } 6549 6550 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6551 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6552 SDValue Ops[] = { N1, N2, N3, N4 }; 6553 return getNode(Opcode, DL, VT, Ops); 6554 } 6555 6556 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6557 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6558 SDValue N5) { 6559 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6560 return getNode(Opcode, DL, VT, Ops); 6561 } 6562 6563 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6564 /// the incoming stack arguments to be loaded from the stack. 6565 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6566 SmallVector<SDValue, 8> ArgChains; 6567 6568 // Include the original chain at the beginning of the list. When this is 6569 // used by target LowerCall hooks, this helps legalize find the 6570 // CALLSEQ_BEGIN node. 6571 ArgChains.push_back(Chain); 6572 6573 // Add a chain value for each stack argument. 6574 for (SDNode *U : getEntryNode().getNode()->uses()) 6575 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6576 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6577 if (FI->getIndex() < 0) 6578 ArgChains.push_back(SDValue(L, 1)); 6579 6580 // Build a tokenfactor for all the chains. 6581 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6582 } 6583 6584 /// getMemsetValue - Vectorized representation of the memset value 6585 /// operand. 6586 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6587 const SDLoc &dl) { 6588 assert(!Value.isUndef()); 6589 6590 unsigned NumBits = VT.getScalarSizeInBits(); 6591 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6592 assert(C->getAPIntValue().getBitWidth() == 8); 6593 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6594 if (VT.isInteger()) { 6595 bool IsOpaque = VT.getSizeInBits() > 64 || 6596 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6597 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6598 } 6599 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6600 VT); 6601 } 6602 6603 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6604 EVT IntVT = VT.getScalarType(); 6605 if (!IntVT.isInteger()) 6606 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6607 6608 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6609 if (NumBits > 8) { 6610 // Use a multiplication with 0x010101... to extend the input to the 6611 // required length. 6612 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6613 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6614 DAG.getConstant(Magic, dl, IntVT)); 6615 } 6616 6617 if (VT != Value.getValueType() && !VT.isInteger()) 6618 Value = DAG.getBitcast(VT.getScalarType(), Value); 6619 if (VT != Value.getValueType()) 6620 Value = DAG.getSplatBuildVector(VT, dl, Value); 6621 6622 return Value; 6623 } 6624 6625 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6626 /// used when a memcpy is turned into a memset when the source is a constant 6627 /// string ptr. 6628 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6629 const TargetLowering &TLI, 6630 const ConstantDataArraySlice &Slice) { 6631 // Handle vector with all elements zero. 6632 if (Slice.Array == nullptr) { 6633 if (VT.isInteger()) 6634 return DAG.getConstant(0, dl, VT); 6635 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6636 return DAG.getConstantFP(0.0, dl, VT); 6637 if (VT.isVector()) { 6638 unsigned NumElts = VT.getVectorNumElements(); 6639 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6640 return DAG.getNode(ISD::BITCAST, dl, VT, 6641 DAG.getConstant(0, dl, 6642 EVT::getVectorVT(*DAG.getContext(), 6643 EltVT, NumElts))); 6644 } 6645 llvm_unreachable("Expected type!"); 6646 } 6647 6648 assert(!VT.isVector() && "Can't handle vector type here!"); 6649 unsigned NumVTBits = VT.getSizeInBits(); 6650 unsigned NumVTBytes = NumVTBits / 8; 6651 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6652 6653 APInt Val(NumVTBits, 0); 6654 if (DAG.getDataLayout().isLittleEndian()) { 6655 for (unsigned i = 0; i != NumBytes; ++i) 6656 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6657 } else { 6658 for (unsigned i = 0; i != NumBytes; ++i) 6659 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6660 } 6661 6662 // If the "cost" of materializing the integer immediate is less than the cost 6663 // of a load, then it is cost effective to turn the load into the immediate. 6664 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6665 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6666 return DAG.getConstant(Val, dl, VT); 6667 return SDValue(); 6668 } 6669 6670 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6671 const SDLoc &DL, 6672 const SDNodeFlags Flags) { 6673 EVT VT = Base.getValueType(); 6674 SDValue Index; 6675 6676 if (Offset.isScalable()) 6677 Index = getVScale(DL, Base.getValueType(), 6678 APInt(Base.getValueSizeInBits().getFixedSize(), 6679 Offset.getKnownMinSize())); 6680 else 6681 Index = getConstant(Offset.getFixedSize(), DL, VT); 6682 6683 return getMemBasePlusOffset(Base, Index, DL, Flags); 6684 } 6685 6686 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6687 const SDLoc &DL, 6688 const SDNodeFlags Flags) { 6689 assert(Offset.getValueType().isInteger()); 6690 EVT BasePtrVT = Ptr.getValueType(); 6691 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6692 } 6693 6694 /// Returns true if memcpy source is constant data. 6695 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6696 uint64_t SrcDelta = 0; 6697 GlobalAddressSDNode *G = nullptr; 6698 if (Src.getOpcode() == ISD::GlobalAddress) 6699 G = cast<GlobalAddressSDNode>(Src); 6700 else if (Src.getOpcode() == ISD::ADD && 6701 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6702 Src.getOperand(1).getOpcode() == ISD::Constant) { 6703 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6704 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6705 } 6706 if (!G) 6707 return false; 6708 6709 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6710 SrcDelta + G->getOffset()); 6711 } 6712 6713 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6714 SelectionDAG &DAG) { 6715 // On Darwin, -Os means optimize for size without hurting performance, so 6716 // only really optimize for size when -Oz (MinSize) is used. 6717 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6718 return MF.getFunction().hasMinSize(); 6719 return DAG.shouldOptForSize(); 6720 } 6721 6722 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6723 SmallVector<SDValue, 32> &OutChains, unsigned From, 6724 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6725 SmallVector<SDValue, 16> &OutStoreChains) { 6726 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6727 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6728 SmallVector<SDValue, 16> GluedLoadChains; 6729 for (unsigned i = From; i < To; ++i) { 6730 OutChains.push_back(OutLoadChains[i]); 6731 GluedLoadChains.push_back(OutLoadChains[i]); 6732 } 6733 6734 // Chain for all loads. 6735 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6736 GluedLoadChains); 6737 6738 for (unsigned i = From; i < To; ++i) { 6739 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6740 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6741 ST->getBasePtr(), ST->getMemoryVT(), 6742 ST->getMemOperand()); 6743 OutChains.push_back(NewStore); 6744 } 6745 } 6746 6747 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6748 SDValue Chain, SDValue Dst, SDValue Src, 6749 uint64_t Size, Align Alignment, 6750 bool isVol, bool AlwaysInline, 6751 MachinePointerInfo DstPtrInfo, 6752 MachinePointerInfo SrcPtrInfo, 6753 const AAMDNodes &AAInfo, AAResults *AA) { 6754 // Turn a memcpy of undef to nop. 6755 // FIXME: We need to honor volatile even is Src is undef. 6756 if (Src.isUndef()) 6757 return Chain; 6758 6759 // Expand memcpy to a series of load and store ops if the size operand falls 6760 // below a certain threshold. 6761 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6762 // rather than maybe a humongous number of loads and stores. 6763 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6764 const DataLayout &DL = DAG.getDataLayout(); 6765 LLVMContext &C = *DAG.getContext(); 6766 std::vector<EVT> MemOps; 6767 bool DstAlignCanChange = false; 6768 MachineFunction &MF = DAG.getMachineFunction(); 6769 MachineFrameInfo &MFI = MF.getFrameInfo(); 6770 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6771 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6772 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6773 DstAlignCanChange = true; 6774 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6775 if (!SrcAlign || Alignment > *SrcAlign) 6776 SrcAlign = Alignment; 6777 assert(SrcAlign && "SrcAlign must be set"); 6778 ConstantDataArraySlice Slice; 6779 // If marked as volatile, perform a copy even when marked as constant. 6780 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6781 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6782 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6783 const MemOp Op = isZeroConstant 6784 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6785 /*IsZeroMemset*/ true, isVol) 6786 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6787 *SrcAlign, isVol, CopyFromConstant); 6788 if (!TLI.findOptimalMemOpLowering( 6789 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6790 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6791 return SDValue(); 6792 6793 if (DstAlignCanChange) { 6794 Type *Ty = MemOps[0].getTypeForEVT(C); 6795 Align NewAlign = DL.getABITypeAlign(Ty); 6796 6797 // Don't promote to an alignment that would require dynamic stack 6798 // realignment. 6799 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6800 if (!TRI->hasStackRealignment(MF)) 6801 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6802 NewAlign = NewAlign.previous(); 6803 6804 if (NewAlign > Alignment) { 6805 // Give the stack frame object a larger alignment if needed. 6806 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6807 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6808 Alignment = NewAlign; 6809 } 6810 } 6811 6812 // Prepare AAInfo for loads/stores after lowering this memcpy. 6813 AAMDNodes NewAAInfo = AAInfo; 6814 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6815 6816 const Value *SrcVal = SrcPtrInfo.V.dyn_cast<const Value *>(); 6817 bool isConstant = 6818 AA && SrcVal && 6819 AA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo)); 6820 6821 MachineMemOperand::Flags MMOFlags = 6822 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6823 SmallVector<SDValue, 16> OutLoadChains; 6824 SmallVector<SDValue, 16> OutStoreChains; 6825 SmallVector<SDValue, 32> OutChains; 6826 unsigned NumMemOps = MemOps.size(); 6827 uint64_t SrcOff = 0, DstOff = 0; 6828 for (unsigned i = 0; i != NumMemOps; ++i) { 6829 EVT VT = MemOps[i]; 6830 unsigned VTSize = VT.getSizeInBits() / 8; 6831 SDValue Value, Store; 6832 6833 if (VTSize > Size) { 6834 // Issuing an unaligned load / store pair that overlaps with the previous 6835 // pair. Adjust the offset accordingly. 6836 assert(i == NumMemOps-1 && i != 0); 6837 SrcOff -= VTSize - Size; 6838 DstOff -= VTSize - Size; 6839 } 6840 6841 if (CopyFromConstant && 6842 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6843 // It's unlikely a store of a vector immediate can be done in a single 6844 // instruction. It would require a load from a constantpool first. 6845 // We only handle zero vectors here. 6846 // FIXME: Handle other cases where store of vector immediate is done in 6847 // a single instruction. 6848 ConstantDataArraySlice SubSlice; 6849 if (SrcOff < Slice.Length) { 6850 SubSlice = Slice; 6851 SubSlice.move(SrcOff); 6852 } else { 6853 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6854 SubSlice.Array = nullptr; 6855 SubSlice.Offset = 0; 6856 SubSlice.Length = VTSize; 6857 } 6858 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6859 if (Value.getNode()) { 6860 Store = DAG.getStore( 6861 Chain, dl, Value, 6862 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6863 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6864 OutChains.push_back(Store); 6865 } 6866 } 6867 6868 if (!Store.getNode()) { 6869 // The type might not be legal for the target. This should only happen 6870 // if the type is smaller than a legal type, as on PPC, so the right 6871 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6872 // to Load/Store if NVT==VT. 6873 // FIXME does the case above also need this? 6874 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6875 assert(NVT.bitsGE(VT)); 6876 6877 bool isDereferenceable = 6878 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6879 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6880 if (isDereferenceable) 6881 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6882 if (isConstant) 6883 SrcMMOFlags |= MachineMemOperand::MOInvariant; 6884 6885 Value = DAG.getExtLoad( 6886 ISD::EXTLOAD, dl, NVT, Chain, 6887 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6888 SrcPtrInfo.getWithOffset(SrcOff), VT, 6889 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6890 OutLoadChains.push_back(Value.getValue(1)); 6891 6892 Store = DAG.getTruncStore( 6893 Chain, dl, Value, 6894 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6895 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6896 OutStoreChains.push_back(Store); 6897 } 6898 SrcOff += VTSize; 6899 DstOff += VTSize; 6900 Size -= VTSize; 6901 } 6902 6903 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6904 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6905 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6906 6907 if (NumLdStInMemcpy) { 6908 // It may be that memcpy might be converted to memset if it's memcpy 6909 // of constants. In such a case, we won't have loads and stores, but 6910 // just stores. In the absence of loads, there is nothing to gang up. 6911 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6912 // If target does not care, just leave as it. 6913 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6914 OutChains.push_back(OutLoadChains[i]); 6915 OutChains.push_back(OutStoreChains[i]); 6916 } 6917 } else { 6918 // Ld/St less than/equal limit set by target. 6919 if (NumLdStInMemcpy <= GluedLdStLimit) { 6920 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6921 NumLdStInMemcpy, OutLoadChains, 6922 OutStoreChains); 6923 } else { 6924 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6925 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6926 unsigned GlueIter = 0; 6927 6928 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6929 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6930 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6931 6932 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6933 OutLoadChains, OutStoreChains); 6934 GlueIter += GluedLdStLimit; 6935 } 6936 6937 // Residual ld/st. 6938 if (RemainingLdStInMemcpy) { 6939 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6940 RemainingLdStInMemcpy, OutLoadChains, 6941 OutStoreChains); 6942 } 6943 } 6944 } 6945 } 6946 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6947 } 6948 6949 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6950 SDValue Chain, SDValue Dst, SDValue Src, 6951 uint64_t Size, Align Alignment, 6952 bool isVol, bool AlwaysInline, 6953 MachinePointerInfo DstPtrInfo, 6954 MachinePointerInfo SrcPtrInfo, 6955 const AAMDNodes &AAInfo) { 6956 // Turn a memmove of undef to nop. 6957 // FIXME: We need to honor volatile even is Src is undef. 6958 if (Src.isUndef()) 6959 return Chain; 6960 6961 // Expand memmove to a series of load and store ops if the size operand falls 6962 // below a certain threshold. 6963 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6964 const DataLayout &DL = DAG.getDataLayout(); 6965 LLVMContext &C = *DAG.getContext(); 6966 std::vector<EVT> MemOps; 6967 bool DstAlignCanChange = false; 6968 MachineFunction &MF = DAG.getMachineFunction(); 6969 MachineFrameInfo &MFI = MF.getFrameInfo(); 6970 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6971 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6972 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6973 DstAlignCanChange = true; 6974 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6975 if (!SrcAlign || Alignment > *SrcAlign) 6976 SrcAlign = Alignment; 6977 assert(SrcAlign && "SrcAlign must be set"); 6978 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6979 if (!TLI.findOptimalMemOpLowering( 6980 MemOps, Limit, 6981 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6982 /*IsVolatile*/ true), 6983 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6984 MF.getFunction().getAttributes())) 6985 return SDValue(); 6986 6987 if (DstAlignCanChange) { 6988 Type *Ty = MemOps[0].getTypeForEVT(C); 6989 Align NewAlign = DL.getABITypeAlign(Ty); 6990 if (NewAlign > Alignment) { 6991 // Give the stack frame object a larger alignment if needed. 6992 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6993 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6994 Alignment = NewAlign; 6995 } 6996 } 6997 6998 // Prepare AAInfo for loads/stores after lowering this memmove. 6999 AAMDNodes NewAAInfo = AAInfo; 7000 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7001 7002 MachineMemOperand::Flags MMOFlags = 7003 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 7004 uint64_t SrcOff = 0, DstOff = 0; 7005 SmallVector<SDValue, 8> LoadValues; 7006 SmallVector<SDValue, 8> LoadChains; 7007 SmallVector<SDValue, 8> OutChains; 7008 unsigned NumMemOps = MemOps.size(); 7009 for (unsigned i = 0; i < NumMemOps; i++) { 7010 EVT VT = MemOps[i]; 7011 unsigned VTSize = VT.getSizeInBits() / 8; 7012 SDValue Value; 7013 7014 bool isDereferenceable = 7015 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 7016 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 7017 if (isDereferenceable) 7018 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 7019 7020 Value = DAG.getLoad( 7021 VT, dl, Chain, 7022 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 7023 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 7024 LoadValues.push_back(Value); 7025 LoadChains.push_back(Value.getValue(1)); 7026 SrcOff += VTSize; 7027 } 7028 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 7029 OutChains.clear(); 7030 for (unsigned i = 0; i < NumMemOps; i++) { 7031 EVT VT = MemOps[i]; 7032 unsigned VTSize = VT.getSizeInBits() / 8; 7033 SDValue Store; 7034 7035 Store = DAG.getStore( 7036 Chain, dl, LoadValues[i], 7037 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7038 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 7039 OutChains.push_back(Store); 7040 DstOff += VTSize; 7041 } 7042 7043 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7044 } 7045 7046 /// Lower the call to 'memset' intrinsic function into a series of store 7047 /// operations. 7048 /// 7049 /// \param DAG Selection DAG where lowered code is placed. 7050 /// \param dl Link to corresponding IR location. 7051 /// \param Chain Control flow dependency. 7052 /// \param Dst Pointer to destination memory location. 7053 /// \param Src Value of byte to write into the memory. 7054 /// \param Size Number of bytes to write. 7055 /// \param Alignment Alignment of the destination in bytes. 7056 /// \param isVol True if destination is volatile. 7057 /// \param AlwaysInline Makes sure no function call is generated. 7058 /// \param DstPtrInfo IR information on the memory pointer. 7059 /// \returns New head in the control flow, if lowering was successful, empty 7060 /// SDValue otherwise. 7061 /// 7062 /// The function tries to replace 'llvm.memset' intrinsic with several store 7063 /// operations and value calculation code. This is usually profitable for small 7064 /// memory size or when the semantic requires inlining. 7065 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 7066 SDValue Chain, SDValue Dst, SDValue Src, 7067 uint64_t Size, Align Alignment, bool isVol, 7068 bool AlwaysInline, MachinePointerInfo DstPtrInfo, 7069 const AAMDNodes &AAInfo) { 7070 // Turn a memset of undef to nop. 7071 // FIXME: We need to honor volatile even is Src is undef. 7072 if (Src.isUndef()) 7073 return Chain; 7074 7075 // Expand memset to a series of load/store ops if the size operand 7076 // falls below a certain threshold. 7077 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7078 std::vector<EVT> MemOps; 7079 bool DstAlignCanChange = false; 7080 MachineFunction &MF = DAG.getMachineFunction(); 7081 MachineFrameInfo &MFI = MF.getFrameInfo(); 7082 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7083 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7084 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7085 DstAlignCanChange = true; 7086 bool IsZeroVal = 7087 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 7088 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize); 7089 7090 if (!TLI.findOptimalMemOpLowering( 7091 MemOps, Limit, 7092 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 7093 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 7094 return SDValue(); 7095 7096 if (DstAlignCanChange) { 7097 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 7098 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 7099 if (NewAlign > Alignment) { 7100 // Give the stack frame object a larger alignment if needed. 7101 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7102 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7103 Alignment = NewAlign; 7104 } 7105 } 7106 7107 SmallVector<SDValue, 8> OutChains; 7108 uint64_t DstOff = 0; 7109 unsigned NumMemOps = MemOps.size(); 7110 7111 // Find the largest store and generate the bit pattern for it. 7112 EVT LargestVT = MemOps[0]; 7113 for (unsigned i = 1; i < NumMemOps; i++) 7114 if (MemOps[i].bitsGT(LargestVT)) 7115 LargestVT = MemOps[i]; 7116 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 7117 7118 // Prepare AAInfo for loads/stores after lowering this memset. 7119 AAMDNodes NewAAInfo = AAInfo; 7120 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7121 7122 for (unsigned i = 0; i < NumMemOps; i++) { 7123 EVT VT = MemOps[i]; 7124 unsigned VTSize = VT.getSizeInBits() / 8; 7125 if (VTSize > Size) { 7126 // Issuing an unaligned load / store pair that overlaps with the previous 7127 // pair. Adjust the offset accordingly. 7128 assert(i == NumMemOps-1 && i != 0); 7129 DstOff -= VTSize - Size; 7130 } 7131 7132 // If this store is smaller than the largest store see whether we can get 7133 // the smaller value for free with a truncate. 7134 SDValue Value = MemSetValue; 7135 if (VT.bitsLT(LargestVT)) { 7136 if (!LargestVT.isVector() && !VT.isVector() && 7137 TLI.isTruncateFree(LargestVT, VT)) 7138 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7139 else 7140 Value = getMemsetValue(Src, VT, DAG, dl); 7141 } 7142 assert(Value.getValueType() == VT && "Value with wrong type."); 7143 SDValue Store = DAG.getStore( 7144 Chain, dl, Value, 7145 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7146 DstPtrInfo.getWithOffset(DstOff), Alignment, 7147 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7148 NewAAInfo); 7149 OutChains.push_back(Store); 7150 DstOff += VT.getSizeInBits() / 8; 7151 Size -= VTSize; 7152 } 7153 7154 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7155 } 7156 7157 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7158 unsigned AS) { 7159 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7160 // pointer operands can be losslessly bitcasted to pointers of address space 0 7161 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7162 report_fatal_error("cannot lower memory intrinsic in address space " + 7163 Twine(AS)); 7164 } 7165 } 7166 7167 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7168 SDValue Src, SDValue Size, Align Alignment, 7169 bool isVol, bool AlwaysInline, bool isTailCall, 7170 MachinePointerInfo DstPtrInfo, 7171 MachinePointerInfo SrcPtrInfo, 7172 const AAMDNodes &AAInfo, AAResults *AA) { 7173 // Check to see if we should lower the memcpy to loads and stores first. 7174 // For cases within the target-specified limits, this is the best choice. 7175 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7176 if (ConstantSize) { 7177 // Memcpy with size zero? Just return the original chain. 7178 if (ConstantSize->isZero()) 7179 return Chain; 7180 7181 SDValue Result = getMemcpyLoadsAndStores( 7182 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7183 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, AA); 7184 if (Result.getNode()) 7185 return Result; 7186 } 7187 7188 // Then check to see if we should lower the memcpy with target-specific 7189 // code. If the target chooses to do this, this is the next best. 7190 if (TSI) { 7191 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7192 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7193 DstPtrInfo, SrcPtrInfo); 7194 if (Result.getNode()) 7195 return Result; 7196 } 7197 7198 // If we really need inline code and the target declined to provide it, 7199 // use a (potentially long) sequence of loads and stores. 7200 if (AlwaysInline) { 7201 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7202 return getMemcpyLoadsAndStores( 7203 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7204 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, AA); 7205 } 7206 7207 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7208 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7209 7210 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7211 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7212 // respect volatile, so they may do things like read or write memory 7213 // beyond the given memory regions. But fixing this isn't easy, and most 7214 // people don't care. 7215 7216 // Emit a library call. 7217 TargetLowering::ArgListTy Args; 7218 TargetLowering::ArgListEntry Entry; 7219 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7220 Entry.Node = Dst; Args.push_back(Entry); 7221 Entry.Node = Src; Args.push_back(Entry); 7222 7223 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7224 Entry.Node = Size; Args.push_back(Entry); 7225 // FIXME: pass in SDLoc 7226 TargetLowering::CallLoweringInfo CLI(*this); 7227 CLI.setDebugLoc(dl) 7228 .setChain(Chain) 7229 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7230 Dst.getValueType().getTypeForEVT(*getContext()), 7231 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7232 TLI->getPointerTy(getDataLayout())), 7233 std::move(Args)) 7234 .setDiscardResult() 7235 .setTailCall(isTailCall); 7236 7237 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7238 return CallResult.second; 7239 } 7240 7241 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7242 SDValue Dst, SDValue Src, SDValue Size, 7243 Type *SizeTy, unsigned ElemSz, 7244 bool isTailCall, 7245 MachinePointerInfo DstPtrInfo, 7246 MachinePointerInfo SrcPtrInfo) { 7247 // Emit a library call. 7248 TargetLowering::ArgListTy Args; 7249 TargetLowering::ArgListEntry Entry; 7250 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7251 Entry.Node = Dst; 7252 Args.push_back(Entry); 7253 7254 Entry.Node = Src; 7255 Args.push_back(Entry); 7256 7257 Entry.Ty = SizeTy; 7258 Entry.Node = Size; 7259 Args.push_back(Entry); 7260 7261 RTLIB::Libcall LibraryCall = 7262 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7263 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7264 report_fatal_error("Unsupported element size"); 7265 7266 TargetLowering::CallLoweringInfo CLI(*this); 7267 CLI.setDebugLoc(dl) 7268 .setChain(Chain) 7269 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7270 Type::getVoidTy(*getContext()), 7271 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7272 TLI->getPointerTy(getDataLayout())), 7273 std::move(Args)) 7274 .setDiscardResult() 7275 .setTailCall(isTailCall); 7276 7277 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7278 return CallResult.second; 7279 } 7280 7281 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7282 SDValue Src, SDValue Size, Align Alignment, 7283 bool isVol, bool isTailCall, 7284 MachinePointerInfo DstPtrInfo, 7285 MachinePointerInfo SrcPtrInfo, 7286 const AAMDNodes &AAInfo, AAResults *AA) { 7287 // Check to see if we should lower the memmove to loads and stores first. 7288 // For cases within the target-specified limits, this is the best choice. 7289 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7290 if (ConstantSize) { 7291 // Memmove with size zero? Just return the original chain. 7292 if (ConstantSize->isZero()) 7293 return Chain; 7294 7295 SDValue Result = getMemmoveLoadsAndStores( 7296 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7297 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7298 if (Result.getNode()) 7299 return Result; 7300 } 7301 7302 // Then check to see if we should lower the memmove with target-specific 7303 // code. If the target chooses to do this, this is the next best. 7304 if (TSI) { 7305 SDValue Result = 7306 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7307 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7308 if (Result.getNode()) 7309 return Result; 7310 } 7311 7312 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7313 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7314 7315 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7316 // not be safe. See memcpy above for more details. 7317 7318 // Emit a library call. 7319 TargetLowering::ArgListTy Args; 7320 TargetLowering::ArgListEntry Entry; 7321 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7322 Entry.Node = Dst; Args.push_back(Entry); 7323 Entry.Node = Src; Args.push_back(Entry); 7324 7325 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7326 Entry.Node = Size; Args.push_back(Entry); 7327 // FIXME: pass in SDLoc 7328 TargetLowering::CallLoweringInfo CLI(*this); 7329 CLI.setDebugLoc(dl) 7330 .setChain(Chain) 7331 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7332 Dst.getValueType().getTypeForEVT(*getContext()), 7333 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7334 TLI->getPointerTy(getDataLayout())), 7335 std::move(Args)) 7336 .setDiscardResult() 7337 .setTailCall(isTailCall); 7338 7339 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7340 return CallResult.second; 7341 } 7342 7343 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7344 SDValue Dst, SDValue Src, SDValue Size, 7345 Type *SizeTy, unsigned ElemSz, 7346 bool isTailCall, 7347 MachinePointerInfo DstPtrInfo, 7348 MachinePointerInfo SrcPtrInfo) { 7349 // Emit a library call. 7350 TargetLowering::ArgListTy Args; 7351 TargetLowering::ArgListEntry Entry; 7352 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7353 Entry.Node = Dst; 7354 Args.push_back(Entry); 7355 7356 Entry.Node = Src; 7357 Args.push_back(Entry); 7358 7359 Entry.Ty = SizeTy; 7360 Entry.Node = Size; 7361 Args.push_back(Entry); 7362 7363 RTLIB::Libcall LibraryCall = 7364 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7365 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7366 report_fatal_error("Unsupported element size"); 7367 7368 TargetLowering::CallLoweringInfo CLI(*this); 7369 CLI.setDebugLoc(dl) 7370 .setChain(Chain) 7371 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7372 Type::getVoidTy(*getContext()), 7373 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7374 TLI->getPointerTy(getDataLayout())), 7375 std::move(Args)) 7376 .setDiscardResult() 7377 .setTailCall(isTailCall); 7378 7379 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7380 return CallResult.second; 7381 } 7382 7383 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7384 SDValue Src, SDValue Size, Align Alignment, 7385 bool isVol, bool AlwaysInline, bool isTailCall, 7386 MachinePointerInfo DstPtrInfo, 7387 const AAMDNodes &AAInfo) { 7388 // Check to see if we should lower the memset to stores first. 7389 // For cases within the target-specified limits, this is the best choice. 7390 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7391 if (ConstantSize) { 7392 // Memset with size zero? Just return the original chain. 7393 if (ConstantSize->isZero()) 7394 return Chain; 7395 7396 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7397 ConstantSize->getZExtValue(), Alignment, 7398 isVol, false, DstPtrInfo, AAInfo); 7399 7400 if (Result.getNode()) 7401 return Result; 7402 } 7403 7404 // Then check to see if we should lower the memset with target-specific 7405 // code. If the target chooses to do this, this is the next best. 7406 if (TSI) { 7407 SDValue Result = TSI->EmitTargetCodeForMemset( 7408 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo); 7409 if (Result.getNode()) 7410 return Result; 7411 } 7412 7413 // If we really need inline code and the target declined to provide it, 7414 // use a (potentially long) sequence of loads and stores. 7415 if (AlwaysInline) { 7416 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7417 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7418 ConstantSize->getZExtValue(), Alignment, 7419 isVol, true, DstPtrInfo, AAInfo); 7420 assert(Result && 7421 "getMemsetStores must return a valid sequence when AlwaysInline"); 7422 return Result; 7423 } 7424 7425 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7426 7427 // Emit a library call. 7428 auto &Ctx = *getContext(); 7429 const auto& DL = getDataLayout(); 7430 7431 TargetLowering::CallLoweringInfo CLI(*this); 7432 // FIXME: pass in SDLoc 7433 CLI.setDebugLoc(dl).setChain(Chain); 7434 7435 ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src); 7436 const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero(); 7437 const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO); 7438 7439 // Helper function to create an Entry from Node and Type. 7440 const auto CreateEntry = [](SDValue Node, Type *Ty) { 7441 TargetLowering::ArgListEntry Entry; 7442 Entry.Node = Node; 7443 Entry.Ty = Ty; 7444 return Entry; 7445 }; 7446 7447 // If zeroing out and bzero is present, use it. 7448 if (SrcIsZero && BzeroName) { 7449 TargetLowering::ArgListTy Args; 7450 Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx))); 7451 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 7452 CLI.setLibCallee( 7453 TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx), 7454 getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args)); 7455 } else { 7456 TargetLowering::ArgListTy Args; 7457 Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx))); 7458 Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx))); 7459 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 7460 CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7461 Dst.getValueType().getTypeForEVT(Ctx), 7462 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7463 TLI->getPointerTy(DL)), 7464 std::move(Args)); 7465 } 7466 7467 CLI.setDiscardResult().setTailCall(isTailCall); 7468 7469 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7470 return CallResult.second; 7471 } 7472 7473 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7474 SDValue Dst, SDValue Value, SDValue Size, 7475 Type *SizeTy, unsigned ElemSz, 7476 bool isTailCall, 7477 MachinePointerInfo DstPtrInfo) { 7478 // Emit a library call. 7479 TargetLowering::ArgListTy Args; 7480 TargetLowering::ArgListEntry Entry; 7481 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7482 Entry.Node = Dst; 7483 Args.push_back(Entry); 7484 7485 Entry.Ty = Type::getInt8Ty(*getContext()); 7486 Entry.Node = Value; 7487 Args.push_back(Entry); 7488 7489 Entry.Ty = SizeTy; 7490 Entry.Node = Size; 7491 Args.push_back(Entry); 7492 7493 RTLIB::Libcall LibraryCall = 7494 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7495 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7496 report_fatal_error("Unsupported element size"); 7497 7498 TargetLowering::CallLoweringInfo CLI(*this); 7499 CLI.setDebugLoc(dl) 7500 .setChain(Chain) 7501 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7502 Type::getVoidTy(*getContext()), 7503 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7504 TLI->getPointerTy(getDataLayout())), 7505 std::move(Args)) 7506 .setDiscardResult() 7507 .setTailCall(isTailCall); 7508 7509 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7510 return CallResult.second; 7511 } 7512 7513 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7514 SDVTList VTList, ArrayRef<SDValue> Ops, 7515 MachineMemOperand *MMO) { 7516 FoldingSetNodeID ID; 7517 ID.AddInteger(MemVT.getRawBits()); 7518 AddNodeIDNode(ID, Opcode, VTList, Ops); 7519 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7520 ID.AddInteger(MMO->getFlags()); 7521 void* IP = nullptr; 7522 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7523 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7524 return SDValue(E, 0); 7525 } 7526 7527 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7528 VTList, MemVT, MMO); 7529 createOperands(N, Ops); 7530 7531 CSEMap.InsertNode(N, IP); 7532 InsertNode(N); 7533 return SDValue(N, 0); 7534 } 7535 7536 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7537 EVT MemVT, SDVTList VTs, SDValue Chain, 7538 SDValue Ptr, SDValue Cmp, SDValue Swp, 7539 MachineMemOperand *MMO) { 7540 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7541 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7542 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7543 7544 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7545 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7546 } 7547 7548 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7549 SDValue Chain, SDValue Ptr, SDValue Val, 7550 MachineMemOperand *MMO) { 7551 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7552 Opcode == ISD::ATOMIC_LOAD_SUB || 7553 Opcode == ISD::ATOMIC_LOAD_AND || 7554 Opcode == ISD::ATOMIC_LOAD_CLR || 7555 Opcode == ISD::ATOMIC_LOAD_OR || 7556 Opcode == ISD::ATOMIC_LOAD_XOR || 7557 Opcode == ISD::ATOMIC_LOAD_NAND || 7558 Opcode == ISD::ATOMIC_LOAD_MIN || 7559 Opcode == ISD::ATOMIC_LOAD_MAX || 7560 Opcode == ISD::ATOMIC_LOAD_UMIN || 7561 Opcode == ISD::ATOMIC_LOAD_UMAX || 7562 Opcode == ISD::ATOMIC_LOAD_FADD || 7563 Opcode == ISD::ATOMIC_LOAD_FSUB || 7564 Opcode == ISD::ATOMIC_LOAD_FMAX || 7565 Opcode == ISD::ATOMIC_LOAD_FMIN || 7566 Opcode == ISD::ATOMIC_SWAP || 7567 Opcode == ISD::ATOMIC_STORE) && 7568 "Invalid Atomic Op"); 7569 7570 EVT VT = Val.getValueType(); 7571 7572 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7573 getVTList(VT, MVT::Other); 7574 SDValue Ops[] = {Chain, Ptr, Val}; 7575 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7576 } 7577 7578 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7579 EVT VT, SDValue Chain, SDValue Ptr, 7580 MachineMemOperand *MMO) { 7581 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7582 7583 SDVTList VTs = getVTList(VT, MVT::Other); 7584 SDValue Ops[] = {Chain, Ptr}; 7585 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7586 } 7587 7588 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7589 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7590 if (Ops.size() == 1) 7591 return Ops[0]; 7592 7593 SmallVector<EVT, 4> VTs; 7594 VTs.reserve(Ops.size()); 7595 for (const SDValue &Op : Ops) 7596 VTs.push_back(Op.getValueType()); 7597 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7598 } 7599 7600 SDValue SelectionDAG::getMemIntrinsicNode( 7601 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7602 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7603 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7604 if (!Size && MemVT.isScalableVector()) 7605 Size = MemoryLocation::UnknownSize; 7606 else if (!Size) 7607 Size = MemVT.getStoreSize(); 7608 7609 MachineFunction &MF = getMachineFunction(); 7610 MachineMemOperand *MMO = 7611 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7612 7613 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7614 } 7615 7616 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7617 SDVTList VTList, 7618 ArrayRef<SDValue> Ops, EVT MemVT, 7619 MachineMemOperand *MMO) { 7620 assert((Opcode == ISD::INTRINSIC_VOID || 7621 Opcode == ISD::INTRINSIC_W_CHAIN || 7622 Opcode == ISD::PREFETCH || 7623 ((int)Opcode <= std::numeric_limits<int>::max() && 7624 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7625 "Opcode is not a memory-accessing opcode!"); 7626 7627 // Memoize the node unless it returns a flag. 7628 MemIntrinsicSDNode *N; 7629 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7630 FoldingSetNodeID ID; 7631 AddNodeIDNode(ID, Opcode, VTList, Ops); 7632 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7633 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7634 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7635 ID.AddInteger(MMO->getFlags()); 7636 void *IP = nullptr; 7637 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7638 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7639 return SDValue(E, 0); 7640 } 7641 7642 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7643 VTList, MemVT, MMO); 7644 createOperands(N, Ops); 7645 7646 CSEMap.InsertNode(N, IP); 7647 } else { 7648 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7649 VTList, MemVT, MMO); 7650 createOperands(N, Ops); 7651 } 7652 InsertNode(N); 7653 SDValue V(N, 0); 7654 NewSDValueDbgMsg(V, "Creating new node: ", this); 7655 return V; 7656 } 7657 7658 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7659 SDValue Chain, int FrameIndex, 7660 int64_t Size, int64_t Offset) { 7661 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7662 const auto VTs = getVTList(MVT::Other); 7663 SDValue Ops[2] = { 7664 Chain, 7665 getFrameIndex(FrameIndex, 7666 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7667 true)}; 7668 7669 FoldingSetNodeID ID; 7670 AddNodeIDNode(ID, Opcode, VTs, Ops); 7671 ID.AddInteger(FrameIndex); 7672 ID.AddInteger(Size); 7673 ID.AddInteger(Offset); 7674 void *IP = nullptr; 7675 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7676 return SDValue(E, 0); 7677 7678 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7679 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7680 createOperands(N, Ops); 7681 CSEMap.InsertNode(N, IP); 7682 InsertNode(N); 7683 SDValue V(N, 0); 7684 NewSDValueDbgMsg(V, "Creating new node: ", this); 7685 return V; 7686 } 7687 7688 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7689 uint64_t Guid, uint64_t Index, 7690 uint32_t Attr) { 7691 const unsigned Opcode = ISD::PSEUDO_PROBE; 7692 const auto VTs = getVTList(MVT::Other); 7693 SDValue Ops[] = {Chain}; 7694 FoldingSetNodeID ID; 7695 AddNodeIDNode(ID, Opcode, VTs, Ops); 7696 ID.AddInteger(Guid); 7697 ID.AddInteger(Index); 7698 void *IP = nullptr; 7699 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7700 return SDValue(E, 0); 7701 7702 auto *N = newSDNode<PseudoProbeSDNode>( 7703 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7704 createOperands(N, Ops); 7705 CSEMap.InsertNode(N, IP); 7706 InsertNode(N); 7707 SDValue V(N, 0); 7708 NewSDValueDbgMsg(V, "Creating new node: ", this); 7709 return V; 7710 } 7711 7712 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7713 /// MachinePointerInfo record from it. This is particularly useful because the 7714 /// code generator has many cases where it doesn't bother passing in a 7715 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7716 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7717 SelectionDAG &DAG, SDValue Ptr, 7718 int64_t Offset = 0) { 7719 // If this is FI+Offset, we can model it. 7720 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7721 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7722 FI->getIndex(), Offset); 7723 7724 // If this is (FI+Offset1)+Offset2, we can model it. 7725 if (Ptr.getOpcode() != ISD::ADD || 7726 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7727 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7728 return Info; 7729 7730 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7731 return MachinePointerInfo::getFixedStack( 7732 DAG.getMachineFunction(), FI, 7733 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7734 } 7735 7736 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7737 /// MachinePointerInfo record from it. This is particularly useful because the 7738 /// code generator has many cases where it doesn't bother passing in a 7739 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7740 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7741 SelectionDAG &DAG, SDValue Ptr, 7742 SDValue OffsetOp) { 7743 // If the 'Offset' value isn't a constant, we can't handle this. 7744 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7745 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7746 if (OffsetOp.isUndef()) 7747 return InferPointerInfo(Info, DAG, Ptr); 7748 return Info; 7749 } 7750 7751 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7752 EVT VT, const SDLoc &dl, SDValue Chain, 7753 SDValue Ptr, SDValue Offset, 7754 MachinePointerInfo PtrInfo, EVT MemVT, 7755 Align Alignment, 7756 MachineMemOperand::Flags MMOFlags, 7757 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7758 assert(Chain.getValueType() == MVT::Other && 7759 "Invalid chain type"); 7760 7761 MMOFlags |= MachineMemOperand::MOLoad; 7762 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7763 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7764 // clients. 7765 if (PtrInfo.V.isNull()) 7766 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7767 7768 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7769 MachineFunction &MF = getMachineFunction(); 7770 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7771 Alignment, AAInfo, Ranges); 7772 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7773 } 7774 7775 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7776 EVT VT, const SDLoc &dl, SDValue Chain, 7777 SDValue Ptr, SDValue Offset, EVT MemVT, 7778 MachineMemOperand *MMO) { 7779 if (VT == MemVT) { 7780 ExtType = ISD::NON_EXTLOAD; 7781 } else if (ExtType == ISD::NON_EXTLOAD) { 7782 assert(VT == MemVT && "Non-extending load from different memory type!"); 7783 } else { 7784 // Extending load. 7785 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7786 "Should only be an extending load, not truncating!"); 7787 assert(VT.isInteger() == MemVT.isInteger() && 7788 "Cannot convert from FP to Int or Int -> FP!"); 7789 assert(VT.isVector() == MemVT.isVector() && 7790 "Cannot use an ext load to convert to or from a vector!"); 7791 assert((!VT.isVector() || 7792 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7793 "Cannot use an ext load to change the number of vector elements!"); 7794 } 7795 7796 bool Indexed = AM != ISD::UNINDEXED; 7797 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7798 7799 SDVTList VTs = Indexed ? 7800 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7801 SDValue Ops[] = { Chain, Ptr, Offset }; 7802 FoldingSetNodeID ID; 7803 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7804 ID.AddInteger(MemVT.getRawBits()); 7805 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7806 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7807 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7808 ID.AddInteger(MMO->getFlags()); 7809 void *IP = nullptr; 7810 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7811 cast<LoadSDNode>(E)->refineAlignment(MMO); 7812 return SDValue(E, 0); 7813 } 7814 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7815 ExtType, MemVT, MMO); 7816 createOperands(N, Ops); 7817 7818 CSEMap.InsertNode(N, IP); 7819 InsertNode(N); 7820 SDValue V(N, 0); 7821 NewSDValueDbgMsg(V, "Creating new node: ", this); 7822 return V; 7823 } 7824 7825 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7826 SDValue Ptr, MachinePointerInfo PtrInfo, 7827 MaybeAlign Alignment, 7828 MachineMemOperand::Flags MMOFlags, 7829 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7830 SDValue Undef = getUNDEF(Ptr.getValueType()); 7831 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7832 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7833 } 7834 7835 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7836 SDValue Ptr, MachineMemOperand *MMO) { 7837 SDValue Undef = getUNDEF(Ptr.getValueType()); 7838 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7839 VT, MMO); 7840 } 7841 7842 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7843 EVT VT, SDValue Chain, SDValue Ptr, 7844 MachinePointerInfo PtrInfo, EVT MemVT, 7845 MaybeAlign Alignment, 7846 MachineMemOperand::Flags MMOFlags, 7847 const AAMDNodes &AAInfo) { 7848 SDValue Undef = getUNDEF(Ptr.getValueType()); 7849 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7850 MemVT, Alignment, MMOFlags, AAInfo); 7851 } 7852 7853 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7854 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7855 MachineMemOperand *MMO) { 7856 SDValue Undef = getUNDEF(Ptr.getValueType()); 7857 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7858 MemVT, MMO); 7859 } 7860 7861 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7862 SDValue Base, SDValue Offset, 7863 ISD::MemIndexedMode AM) { 7864 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7865 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7866 // Don't propagate the invariant or dereferenceable flags. 7867 auto MMOFlags = 7868 LD->getMemOperand()->getFlags() & 7869 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7870 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7871 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7872 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7873 } 7874 7875 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7876 SDValue Ptr, MachinePointerInfo PtrInfo, 7877 Align Alignment, 7878 MachineMemOperand::Flags MMOFlags, 7879 const AAMDNodes &AAInfo) { 7880 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7881 7882 MMOFlags |= MachineMemOperand::MOStore; 7883 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7884 7885 if (PtrInfo.V.isNull()) 7886 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7887 7888 MachineFunction &MF = getMachineFunction(); 7889 uint64_t Size = 7890 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7891 MachineMemOperand *MMO = 7892 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7893 return getStore(Chain, dl, Val, Ptr, MMO); 7894 } 7895 7896 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7897 SDValue Ptr, MachineMemOperand *MMO) { 7898 assert(Chain.getValueType() == MVT::Other && 7899 "Invalid chain type"); 7900 EVT VT = Val.getValueType(); 7901 SDVTList VTs = getVTList(MVT::Other); 7902 SDValue Undef = getUNDEF(Ptr.getValueType()); 7903 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7904 FoldingSetNodeID ID; 7905 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7906 ID.AddInteger(VT.getRawBits()); 7907 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7908 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7909 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7910 ID.AddInteger(MMO->getFlags()); 7911 void *IP = nullptr; 7912 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7913 cast<StoreSDNode>(E)->refineAlignment(MMO); 7914 return SDValue(E, 0); 7915 } 7916 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7917 ISD::UNINDEXED, false, VT, MMO); 7918 createOperands(N, Ops); 7919 7920 CSEMap.InsertNode(N, IP); 7921 InsertNode(N); 7922 SDValue V(N, 0); 7923 NewSDValueDbgMsg(V, "Creating new node: ", this); 7924 return V; 7925 } 7926 7927 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7928 SDValue Ptr, MachinePointerInfo PtrInfo, 7929 EVT SVT, Align Alignment, 7930 MachineMemOperand::Flags MMOFlags, 7931 const AAMDNodes &AAInfo) { 7932 assert(Chain.getValueType() == MVT::Other && 7933 "Invalid chain type"); 7934 7935 MMOFlags |= MachineMemOperand::MOStore; 7936 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7937 7938 if (PtrInfo.V.isNull()) 7939 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7940 7941 MachineFunction &MF = getMachineFunction(); 7942 MachineMemOperand *MMO = MF.getMachineMemOperand( 7943 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7944 Alignment, AAInfo); 7945 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7946 } 7947 7948 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7949 SDValue Ptr, EVT SVT, 7950 MachineMemOperand *MMO) { 7951 EVT VT = Val.getValueType(); 7952 7953 assert(Chain.getValueType() == MVT::Other && 7954 "Invalid chain type"); 7955 if (VT == SVT) 7956 return getStore(Chain, dl, Val, Ptr, MMO); 7957 7958 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7959 "Should only be a truncating store, not extending!"); 7960 assert(VT.isInteger() == SVT.isInteger() && 7961 "Can't do FP-INT conversion!"); 7962 assert(VT.isVector() == SVT.isVector() && 7963 "Cannot use trunc store to convert to or from a vector!"); 7964 assert((!VT.isVector() || 7965 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7966 "Cannot use trunc store to change the number of vector elements!"); 7967 7968 SDVTList VTs = getVTList(MVT::Other); 7969 SDValue Undef = getUNDEF(Ptr.getValueType()); 7970 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7971 FoldingSetNodeID ID; 7972 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7973 ID.AddInteger(SVT.getRawBits()); 7974 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7975 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7976 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7977 ID.AddInteger(MMO->getFlags()); 7978 void *IP = nullptr; 7979 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7980 cast<StoreSDNode>(E)->refineAlignment(MMO); 7981 return SDValue(E, 0); 7982 } 7983 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7984 ISD::UNINDEXED, true, SVT, MMO); 7985 createOperands(N, Ops); 7986 7987 CSEMap.InsertNode(N, IP); 7988 InsertNode(N); 7989 SDValue V(N, 0); 7990 NewSDValueDbgMsg(V, "Creating new node: ", this); 7991 return V; 7992 } 7993 7994 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7995 SDValue Base, SDValue Offset, 7996 ISD::MemIndexedMode AM) { 7997 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7998 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7999 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8000 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 8001 FoldingSetNodeID ID; 8002 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 8003 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8004 ID.AddInteger(ST->getRawSubclassData()); 8005 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8006 ID.AddInteger(ST->getMemOperand()->getFlags()); 8007 void *IP = nullptr; 8008 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8009 return SDValue(E, 0); 8010 8011 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8012 ST->isTruncatingStore(), ST->getMemoryVT(), 8013 ST->getMemOperand()); 8014 createOperands(N, Ops); 8015 8016 CSEMap.InsertNode(N, IP); 8017 InsertNode(N); 8018 SDValue V(N, 0); 8019 NewSDValueDbgMsg(V, "Creating new node: ", this); 8020 return V; 8021 } 8022 8023 SDValue SelectionDAG::getLoadVP( 8024 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 8025 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 8026 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8027 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8028 const MDNode *Ranges, bool IsExpanding) { 8029 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8030 8031 MMOFlags |= MachineMemOperand::MOLoad; 8032 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8033 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8034 // clients. 8035 if (PtrInfo.V.isNull()) 8036 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8037 8038 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 8039 MachineFunction &MF = getMachineFunction(); 8040 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8041 Alignment, AAInfo, Ranges); 8042 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 8043 MMO, IsExpanding); 8044 } 8045 8046 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 8047 ISD::LoadExtType ExtType, EVT VT, 8048 const SDLoc &dl, SDValue Chain, SDValue Ptr, 8049 SDValue Offset, SDValue Mask, SDValue EVL, 8050 EVT MemVT, MachineMemOperand *MMO, 8051 bool IsExpanding) { 8052 bool Indexed = AM != ISD::UNINDEXED; 8053 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8054 8055 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8056 : getVTList(VT, MVT::Other); 8057 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 8058 FoldingSetNodeID ID; 8059 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 8060 ID.AddInteger(VT.getRawBits()); 8061 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 8062 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8063 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8064 ID.AddInteger(MMO->getFlags()); 8065 void *IP = nullptr; 8066 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8067 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 8068 return SDValue(E, 0); 8069 } 8070 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8071 ExtType, IsExpanding, MemVT, MMO); 8072 createOperands(N, Ops); 8073 8074 CSEMap.InsertNode(N, IP); 8075 InsertNode(N); 8076 SDValue V(N, 0); 8077 NewSDValueDbgMsg(V, "Creating new node: ", this); 8078 return V; 8079 } 8080 8081 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8082 SDValue Ptr, SDValue Mask, SDValue EVL, 8083 MachinePointerInfo PtrInfo, 8084 MaybeAlign Alignment, 8085 MachineMemOperand::Flags MMOFlags, 8086 const AAMDNodes &AAInfo, const MDNode *Ranges, 8087 bool IsExpanding) { 8088 SDValue Undef = getUNDEF(Ptr.getValueType()); 8089 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8090 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 8091 IsExpanding); 8092 } 8093 8094 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8095 SDValue Ptr, SDValue Mask, SDValue EVL, 8096 MachineMemOperand *MMO, bool IsExpanding) { 8097 SDValue Undef = getUNDEF(Ptr.getValueType()); 8098 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8099 Mask, EVL, VT, MMO, IsExpanding); 8100 } 8101 8102 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8103 EVT VT, SDValue Chain, SDValue Ptr, 8104 SDValue Mask, SDValue EVL, 8105 MachinePointerInfo PtrInfo, EVT MemVT, 8106 MaybeAlign Alignment, 8107 MachineMemOperand::Flags MMOFlags, 8108 const AAMDNodes &AAInfo, bool IsExpanding) { 8109 SDValue Undef = getUNDEF(Ptr.getValueType()); 8110 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8111 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 8112 IsExpanding); 8113 } 8114 8115 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8116 EVT VT, SDValue Chain, SDValue Ptr, 8117 SDValue Mask, SDValue EVL, EVT MemVT, 8118 MachineMemOperand *MMO, bool IsExpanding) { 8119 SDValue Undef = getUNDEF(Ptr.getValueType()); 8120 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8121 EVL, MemVT, MMO, IsExpanding); 8122 } 8123 8124 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 8125 SDValue Base, SDValue Offset, 8126 ISD::MemIndexedMode AM) { 8127 auto *LD = cast<VPLoadSDNode>(OrigLoad); 8128 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8129 // Don't propagate the invariant or dereferenceable flags. 8130 auto MMOFlags = 8131 LD->getMemOperand()->getFlags() & 8132 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8133 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8134 LD->getChain(), Base, Offset, LD->getMask(), 8135 LD->getVectorLength(), LD->getPointerInfo(), 8136 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 8137 nullptr, LD->isExpandingLoad()); 8138 } 8139 8140 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 8141 SDValue Ptr, SDValue Offset, SDValue Mask, 8142 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 8143 ISD::MemIndexedMode AM, bool IsTruncating, 8144 bool IsCompressing) { 8145 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8146 bool Indexed = AM != ISD::UNINDEXED; 8147 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8148 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8149 : getVTList(MVT::Other); 8150 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 8151 FoldingSetNodeID ID; 8152 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8153 ID.AddInteger(MemVT.getRawBits()); 8154 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8155 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8156 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8157 ID.AddInteger(MMO->getFlags()); 8158 void *IP = nullptr; 8159 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8160 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8161 return SDValue(E, 0); 8162 } 8163 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8164 IsTruncating, IsCompressing, MemVT, MMO); 8165 createOperands(N, Ops); 8166 8167 CSEMap.InsertNode(N, IP); 8168 InsertNode(N); 8169 SDValue V(N, 0); 8170 NewSDValueDbgMsg(V, "Creating new node: ", this); 8171 return V; 8172 } 8173 8174 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8175 SDValue Val, SDValue Ptr, SDValue Mask, 8176 SDValue EVL, MachinePointerInfo PtrInfo, 8177 EVT SVT, Align Alignment, 8178 MachineMemOperand::Flags MMOFlags, 8179 const AAMDNodes &AAInfo, 8180 bool IsCompressing) { 8181 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8182 8183 MMOFlags |= MachineMemOperand::MOStore; 8184 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8185 8186 if (PtrInfo.V.isNull()) 8187 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8188 8189 MachineFunction &MF = getMachineFunction(); 8190 MachineMemOperand *MMO = MF.getMachineMemOperand( 8191 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8192 Alignment, AAInfo); 8193 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8194 IsCompressing); 8195 } 8196 8197 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8198 SDValue Val, SDValue Ptr, SDValue Mask, 8199 SDValue EVL, EVT SVT, 8200 MachineMemOperand *MMO, 8201 bool IsCompressing) { 8202 EVT VT = Val.getValueType(); 8203 8204 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8205 if (VT == SVT) 8206 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8207 EVL, VT, MMO, ISD::UNINDEXED, 8208 /*IsTruncating*/ false, IsCompressing); 8209 8210 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8211 "Should only be a truncating store, not extending!"); 8212 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8213 assert(VT.isVector() == SVT.isVector() && 8214 "Cannot use trunc store to convert to or from a vector!"); 8215 assert((!VT.isVector() || 8216 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8217 "Cannot use trunc store to change the number of vector elements!"); 8218 8219 SDVTList VTs = getVTList(MVT::Other); 8220 SDValue Undef = getUNDEF(Ptr.getValueType()); 8221 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8222 FoldingSetNodeID ID; 8223 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8224 ID.AddInteger(SVT.getRawBits()); 8225 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8226 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8227 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8228 ID.AddInteger(MMO->getFlags()); 8229 void *IP = nullptr; 8230 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8231 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8232 return SDValue(E, 0); 8233 } 8234 auto *N = 8235 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8236 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8237 createOperands(N, Ops); 8238 8239 CSEMap.InsertNode(N, IP); 8240 InsertNode(N); 8241 SDValue V(N, 0); 8242 NewSDValueDbgMsg(V, "Creating new node: ", this); 8243 return V; 8244 } 8245 8246 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8247 SDValue Base, SDValue Offset, 8248 ISD::MemIndexedMode AM) { 8249 auto *ST = cast<VPStoreSDNode>(OrigStore); 8250 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8251 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8252 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8253 Offset, ST->getMask(), ST->getVectorLength()}; 8254 FoldingSetNodeID ID; 8255 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8256 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8257 ID.AddInteger(ST->getRawSubclassData()); 8258 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8259 ID.AddInteger(ST->getMemOperand()->getFlags()); 8260 void *IP = nullptr; 8261 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8262 return SDValue(E, 0); 8263 8264 auto *N = newSDNode<VPStoreSDNode>( 8265 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8266 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8267 createOperands(N, Ops); 8268 8269 CSEMap.InsertNode(N, IP); 8270 InsertNode(N); 8271 SDValue V(N, 0); 8272 NewSDValueDbgMsg(V, "Creating new node: ", this); 8273 return V; 8274 } 8275 8276 SDValue SelectionDAG::getStridedLoadVP( 8277 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8278 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8279 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8280 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8281 const MDNode *Ranges, bool IsExpanding) { 8282 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8283 8284 MMOFlags |= MachineMemOperand::MOLoad; 8285 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8286 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8287 // clients. 8288 if (PtrInfo.V.isNull()) 8289 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8290 8291 uint64_t Size = MemoryLocation::UnknownSize; 8292 MachineFunction &MF = getMachineFunction(); 8293 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8294 Alignment, AAInfo, Ranges); 8295 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8296 EVL, MemVT, MMO, IsExpanding); 8297 } 8298 8299 SDValue SelectionDAG::getStridedLoadVP( 8300 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8301 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8302 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8303 bool Indexed = AM != ISD::UNINDEXED; 8304 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8305 8306 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8307 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8308 : getVTList(VT, MVT::Other); 8309 FoldingSetNodeID ID; 8310 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8311 ID.AddInteger(VT.getRawBits()); 8312 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8313 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8314 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8315 8316 void *IP = nullptr; 8317 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8318 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8319 return SDValue(E, 0); 8320 } 8321 8322 auto *N = 8323 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8324 ExtType, IsExpanding, MemVT, MMO); 8325 createOperands(N, Ops); 8326 CSEMap.InsertNode(N, IP); 8327 InsertNode(N); 8328 SDValue V(N, 0); 8329 NewSDValueDbgMsg(V, "Creating new node: ", this); 8330 return V; 8331 } 8332 8333 SDValue SelectionDAG::getStridedLoadVP( 8334 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8335 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8336 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8337 const MDNode *Ranges, bool IsExpanding) { 8338 SDValue Undef = getUNDEF(Ptr.getValueType()); 8339 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8340 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8341 MMOFlags, AAInfo, Ranges, IsExpanding); 8342 } 8343 8344 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8345 SDValue Ptr, SDValue Stride, 8346 SDValue Mask, SDValue EVL, 8347 MachineMemOperand *MMO, 8348 bool IsExpanding) { 8349 SDValue Undef = getUNDEF(Ptr.getValueType()); 8350 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8351 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8352 } 8353 8354 SDValue SelectionDAG::getExtStridedLoadVP( 8355 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8356 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8357 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8358 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8359 bool IsExpanding) { 8360 SDValue Undef = getUNDEF(Ptr.getValueType()); 8361 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8362 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8363 MMOFlags, AAInfo, nullptr, IsExpanding); 8364 } 8365 8366 SDValue SelectionDAG::getExtStridedLoadVP( 8367 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8368 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8369 MachineMemOperand *MMO, bool IsExpanding) { 8370 SDValue Undef = getUNDEF(Ptr.getValueType()); 8371 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8372 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8373 } 8374 8375 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8376 SDValue Base, SDValue Offset, 8377 ISD::MemIndexedMode AM) { 8378 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8379 assert(SLD->getOffset().isUndef() && 8380 "Strided load is already a indexed load!"); 8381 // Don't propagate the invariant or dereferenceable flags. 8382 auto MMOFlags = 8383 SLD->getMemOperand()->getFlags() & 8384 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8385 return getStridedLoadVP( 8386 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8387 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8388 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8389 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8390 } 8391 8392 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8393 SDValue Val, SDValue Ptr, 8394 SDValue Offset, SDValue Stride, 8395 SDValue Mask, SDValue EVL, EVT MemVT, 8396 MachineMemOperand *MMO, 8397 ISD::MemIndexedMode AM, 8398 bool IsTruncating, bool IsCompressing) { 8399 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8400 bool Indexed = AM != ISD::UNINDEXED; 8401 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8402 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8403 : getVTList(MVT::Other); 8404 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8405 FoldingSetNodeID ID; 8406 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8407 ID.AddInteger(MemVT.getRawBits()); 8408 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8409 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8410 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8411 void *IP = nullptr; 8412 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8413 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8414 return SDValue(E, 0); 8415 } 8416 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8417 VTs, AM, IsTruncating, 8418 IsCompressing, MemVT, MMO); 8419 createOperands(N, Ops); 8420 8421 CSEMap.InsertNode(N, IP); 8422 InsertNode(N); 8423 SDValue V(N, 0); 8424 NewSDValueDbgMsg(V, "Creating new node: ", this); 8425 return V; 8426 } 8427 8428 SDValue SelectionDAG::getTruncStridedStoreVP( 8429 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8430 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8431 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8432 bool IsCompressing) { 8433 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8434 8435 MMOFlags |= MachineMemOperand::MOStore; 8436 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8437 8438 if (PtrInfo.V.isNull()) 8439 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8440 8441 MachineFunction &MF = getMachineFunction(); 8442 MachineMemOperand *MMO = MF.getMachineMemOperand( 8443 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8444 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8445 MMO, IsCompressing); 8446 } 8447 8448 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8449 SDValue Val, SDValue Ptr, 8450 SDValue Stride, SDValue Mask, 8451 SDValue EVL, EVT SVT, 8452 MachineMemOperand *MMO, 8453 bool IsCompressing) { 8454 EVT VT = Val.getValueType(); 8455 8456 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8457 if (VT == SVT) 8458 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8459 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8460 /*IsTruncating*/ false, IsCompressing); 8461 8462 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8463 "Should only be a truncating store, not extending!"); 8464 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8465 assert(VT.isVector() == SVT.isVector() && 8466 "Cannot use trunc store to convert to or from a vector!"); 8467 assert((!VT.isVector() || 8468 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8469 "Cannot use trunc store to change the number of vector elements!"); 8470 8471 SDVTList VTs = getVTList(MVT::Other); 8472 SDValue Undef = getUNDEF(Ptr.getValueType()); 8473 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8474 FoldingSetNodeID ID; 8475 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8476 ID.AddInteger(SVT.getRawBits()); 8477 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8478 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8479 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8480 void *IP = nullptr; 8481 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8482 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8483 return SDValue(E, 0); 8484 } 8485 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8486 VTs, ISD::UNINDEXED, true, 8487 IsCompressing, SVT, MMO); 8488 createOperands(N, Ops); 8489 8490 CSEMap.InsertNode(N, IP); 8491 InsertNode(N); 8492 SDValue V(N, 0); 8493 NewSDValueDbgMsg(V, "Creating new node: ", this); 8494 return V; 8495 } 8496 8497 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 8498 const SDLoc &DL, SDValue Base, 8499 SDValue Offset, 8500 ISD::MemIndexedMode AM) { 8501 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 8502 assert(SST->getOffset().isUndef() && 8503 "Strided store is already an indexed store!"); 8504 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8505 SDValue Ops[] = { 8506 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 8507 SST->getMask(), SST->getVectorLength()}; 8508 FoldingSetNodeID ID; 8509 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8510 ID.AddInteger(SST->getMemoryVT().getRawBits()); 8511 ID.AddInteger(SST->getRawSubclassData()); 8512 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 8513 void *IP = nullptr; 8514 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8515 return SDValue(E, 0); 8516 8517 auto *N = newSDNode<VPStridedStoreSDNode>( 8518 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 8519 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 8520 createOperands(N, Ops); 8521 8522 CSEMap.InsertNode(N, IP); 8523 InsertNode(N); 8524 SDValue V(N, 0); 8525 NewSDValueDbgMsg(V, "Creating new node: ", this); 8526 return V; 8527 } 8528 8529 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8530 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8531 ISD::MemIndexType IndexType) { 8532 assert(Ops.size() == 6 && "Incompatible number of operands"); 8533 8534 FoldingSetNodeID ID; 8535 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8536 ID.AddInteger(VT.getRawBits()); 8537 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8538 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8539 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8540 ID.AddInteger(MMO->getFlags()); 8541 void *IP = nullptr; 8542 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8543 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8544 return SDValue(E, 0); 8545 } 8546 8547 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8548 VT, MMO, IndexType); 8549 createOperands(N, Ops); 8550 8551 assert(N->getMask().getValueType().getVectorElementCount() == 8552 N->getValueType(0).getVectorElementCount() && 8553 "Vector width mismatch between mask and data"); 8554 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8555 N->getValueType(0).getVectorElementCount().isScalable() && 8556 "Scalable flags of index and data do not match"); 8557 assert(ElementCount::isKnownGE( 8558 N->getIndex().getValueType().getVectorElementCount(), 8559 N->getValueType(0).getVectorElementCount()) && 8560 "Vector width mismatch between index and data"); 8561 assert(isa<ConstantSDNode>(N->getScale()) && 8562 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8563 "Scale should be a constant power of 2"); 8564 8565 CSEMap.InsertNode(N, IP); 8566 InsertNode(N); 8567 SDValue V(N, 0); 8568 NewSDValueDbgMsg(V, "Creating new node: ", this); 8569 return V; 8570 } 8571 8572 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8573 ArrayRef<SDValue> Ops, 8574 MachineMemOperand *MMO, 8575 ISD::MemIndexType IndexType) { 8576 assert(Ops.size() == 7 && "Incompatible number of operands"); 8577 8578 FoldingSetNodeID ID; 8579 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8580 ID.AddInteger(VT.getRawBits()); 8581 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8582 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8583 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8584 ID.AddInteger(MMO->getFlags()); 8585 void *IP = nullptr; 8586 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8587 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8588 return SDValue(E, 0); 8589 } 8590 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8591 VT, MMO, IndexType); 8592 createOperands(N, Ops); 8593 8594 assert(N->getMask().getValueType().getVectorElementCount() == 8595 N->getValue().getValueType().getVectorElementCount() && 8596 "Vector width mismatch between mask and data"); 8597 assert( 8598 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8599 N->getValue().getValueType().getVectorElementCount().isScalable() && 8600 "Scalable flags of index and data do not match"); 8601 assert(ElementCount::isKnownGE( 8602 N->getIndex().getValueType().getVectorElementCount(), 8603 N->getValue().getValueType().getVectorElementCount()) && 8604 "Vector width mismatch between index and data"); 8605 assert(isa<ConstantSDNode>(N->getScale()) && 8606 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8607 "Scale should be a constant power of 2"); 8608 8609 CSEMap.InsertNode(N, IP); 8610 InsertNode(N); 8611 SDValue V(N, 0); 8612 NewSDValueDbgMsg(V, "Creating new node: ", this); 8613 return V; 8614 } 8615 8616 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8617 SDValue Base, SDValue Offset, SDValue Mask, 8618 SDValue PassThru, EVT MemVT, 8619 MachineMemOperand *MMO, 8620 ISD::MemIndexedMode AM, 8621 ISD::LoadExtType ExtTy, bool isExpanding) { 8622 bool Indexed = AM != ISD::UNINDEXED; 8623 assert((Indexed || Offset.isUndef()) && 8624 "Unindexed masked load with an offset!"); 8625 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8626 : getVTList(VT, MVT::Other); 8627 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8628 FoldingSetNodeID ID; 8629 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8630 ID.AddInteger(MemVT.getRawBits()); 8631 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8632 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8633 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8634 ID.AddInteger(MMO->getFlags()); 8635 void *IP = nullptr; 8636 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8637 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8638 return SDValue(E, 0); 8639 } 8640 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8641 AM, ExtTy, isExpanding, MemVT, MMO); 8642 createOperands(N, Ops); 8643 8644 CSEMap.InsertNode(N, IP); 8645 InsertNode(N); 8646 SDValue V(N, 0); 8647 NewSDValueDbgMsg(V, "Creating new node: ", this); 8648 return V; 8649 } 8650 8651 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8652 SDValue Base, SDValue Offset, 8653 ISD::MemIndexedMode AM) { 8654 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8655 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8656 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8657 Offset, LD->getMask(), LD->getPassThru(), 8658 LD->getMemoryVT(), LD->getMemOperand(), AM, 8659 LD->getExtensionType(), LD->isExpandingLoad()); 8660 } 8661 8662 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8663 SDValue Val, SDValue Base, SDValue Offset, 8664 SDValue Mask, EVT MemVT, 8665 MachineMemOperand *MMO, 8666 ISD::MemIndexedMode AM, bool IsTruncating, 8667 bool IsCompressing) { 8668 assert(Chain.getValueType() == MVT::Other && 8669 "Invalid chain type"); 8670 bool Indexed = AM != ISD::UNINDEXED; 8671 assert((Indexed || Offset.isUndef()) && 8672 "Unindexed masked store with an offset!"); 8673 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8674 : getVTList(MVT::Other); 8675 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8676 FoldingSetNodeID ID; 8677 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8678 ID.AddInteger(MemVT.getRawBits()); 8679 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8680 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8681 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8682 ID.AddInteger(MMO->getFlags()); 8683 void *IP = nullptr; 8684 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8685 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8686 return SDValue(E, 0); 8687 } 8688 auto *N = 8689 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8690 IsTruncating, IsCompressing, MemVT, MMO); 8691 createOperands(N, Ops); 8692 8693 CSEMap.InsertNode(N, IP); 8694 InsertNode(N); 8695 SDValue V(N, 0); 8696 NewSDValueDbgMsg(V, "Creating new node: ", this); 8697 return V; 8698 } 8699 8700 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8701 SDValue Base, SDValue Offset, 8702 ISD::MemIndexedMode AM) { 8703 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8704 assert(ST->getOffset().isUndef() && 8705 "Masked store is already a indexed store!"); 8706 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8707 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8708 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8709 } 8710 8711 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8712 ArrayRef<SDValue> Ops, 8713 MachineMemOperand *MMO, 8714 ISD::MemIndexType IndexType, 8715 ISD::LoadExtType ExtTy) { 8716 assert(Ops.size() == 6 && "Incompatible number of operands"); 8717 8718 FoldingSetNodeID ID; 8719 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8720 ID.AddInteger(MemVT.getRawBits()); 8721 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8722 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8723 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8724 ID.AddInteger(MMO->getFlags()); 8725 void *IP = nullptr; 8726 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8727 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8728 return SDValue(E, 0); 8729 } 8730 8731 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8732 VTs, MemVT, MMO, IndexType, ExtTy); 8733 createOperands(N, Ops); 8734 8735 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8736 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8737 assert(N->getMask().getValueType().getVectorElementCount() == 8738 N->getValueType(0).getVectorElementCount() && 8739 "Vector width mismatch between mask and data"); 8740 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8741 N->getValueType(0).getVectorElementCount().isScalable() && 8742 "Scalable flags of index and data do not match"); 8743 assert(ElementCount::isKnownGE( 8744 N->getIndex().getValueType().getVectorElementCount(), 8745 N->getValueType(0).getVectorElementCount()) && 8746 "Vector width mismatch between index and data"); 8747 assert(isa<ConstantSDNode>(N->getScale()) && 8748 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8749 "Scale should be a constant power of 2"); 8750 8751 CSEMap.InsertNode(N, IP); 8752 InsertNode(N); 8753 SDValue V(N, 0); 8754 NewSDValueDbgMsg(V, "Creating new node: ", this); 8755 return V; 8756 } 8757 8758 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8759 ArrayRef<SDValue> Ops, 8760 MachineMemOperand *MMO, 8761 ISD::MemIndexType IndexType, 8762 bool IsTrunc) { 8763 assert(Ops.size() == 6 && "Incompatible number of operands"); 8764 8765 FoldingSetNodeID ID; 8766 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8767 ID.AddInteger(MemVT.getRawBits()); 8768 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8769 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8770 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8771 ID.AddInteger(MMO->getFlags()); 8772 void *IP = nullptr; 8773 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8774 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8775 return SDValue(E, 0); 8776 } 8777 8778 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8779 VTs, MemVT, MMO, IndexType, IsTrunc); 8780 createOperands(N, Ops); 8781 8782 assert(N->getMask().getValueType().getVectorElementCount() == 8783 N->getValue().getValueType().getVectorElementCount() && 8784 "Vector width mismatch between mask and data"); 8785 assert( 8786 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8787 N->getValue().getValueType().getVectorElementCount().isScalable() && 8788 "Scalable flags of index and data do not match"); 8789 assert(ElementCount::isKnownGE( 8790 N->getIndex().getValueType().getVectorElementCount(), 8791 N->getValue().getValueType().getVectorElementCount()) && 8792 "Vector width mismatch between index and data"); 8793 assert(isa<ConstantSDNode>(N->getScale()) && 8794 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8795 "Scale should be a constant power of 2"); 8796 8797 CSEMap.InsertNode(N, IP); 8798 InsertNode(N); 8799 SDValue V(N, 0); 8800 NewSDValueDbgMsg(V, "Creating new node: ", this); 8801 return V; 8802 } 8803 8804 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8805 // select undef, T, F --> T (if T is a constant), otherwise F 8806 // select, ?, undef, F --> F 8807 // select, ?, T, undef --> T 8808 if (Cond.isUndef()) 8809 return isConstantValueOfAnyType(T) ? T : F; 8810 if (T.isUndef()) 8811 return F; 8812 if (F.isUndef()) 8813 return T; 8814 8815 // select true, T, F --> T 8816 // select false, T, F --> F 8817 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8818 return CondC->isZero() ? F : T; 8819 8820 // TODO: This should simplify VSELECT with constant condition using something 8821 // like this (but check boolean contents to be complete?): 8822 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8823 // return T; 8824 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8825 // return F; 8826 8827 // select ?, T, T --> T 8828 if (T == F) 8829 return T; 8830 8831 return SDValue(); 8832 } 8833 8834 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8835 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8836 if (X.isUndef()) 8837 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8838 // shift X, undef --> undef (because it may shift by the bitwidth) 8839 if (Y.isUndef()) 8840 return getUNDEF(X.getValueType()); 8841 8842 // shift 0, Y --> 0 8843 // shift X, 0 --> X 8844 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8845 return X; 8846 8847 // shift X, C >= bitwidth(X) --> undef 8848 // All vector elements must be too big (or undef) to avoid partial undefs. 8849 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8850 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8851 }; 8852 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8853 return getUNDEF(X.getValueType()); 8854 8855 return SDValue(); 8856 } 8857 8858 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8859 SDNodeFlags Flags) { 8860 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8861 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8862 // operation is poison. That result can be relaxed to undef. 8863 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8864 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8865 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8866 (YC && YC->getValueAPF().isNaN()); 8867 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8868 (YC && YC->getValueAPF().isInfinity()); 8869 8870 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8871 return getUNDEF(X.getValueType()); 8872 8873 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8874 return getUNDEF(X.getValueType()); 8875 8876 if (!YC) 8877 return SDValue(); 8878 8879 // X + -0.0 --> X 8880 if (Opcode == ISD::FADD) 8881 if (YC->getValueAPF().isNegZero()) 8882 return X; 8883 8884 // X - +0.0 --> X 8885 if (Opcode == ISD::FSUB) 8886 if (YC->getValueAPF().isPosZero()) 8887 return X; 8888 8889 // X * 1.0 --> X 8890 // X / 1.0 --> X 8891 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8892 if (YC->getValueAPF().isExactlyValue(1.0)) 8893 return X; 8894 8895 // X * 0.0 --> 0.0 8896 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8897 if (YC->getValueAPF().isZero()) 8898 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8899 8900 return SDValue(); 8901 } 8902 8903 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8904 SDValue Ptr, SDValue SV, unsigned Align) { 8905 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8906 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8907 } 8908 8909 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8910 ArrayRef<SDUse> Ops) { 8911 switch (Ops.size()) { 8912 case 0: return getNode(Opcode, DL, VT); 8913 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8914 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8915 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8916 default: break; 8917 } 8918 8919 // Copy from an SDUse array into an SDValue array for use with 8920 // the regular getNode logic. 8921 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8922 return getNode(Opcode, DL, VT, NewOps); 8923 } 8924 8925 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8926 ArrayRef<SDValue> Ops) { 8927 SDNodeFlags Flags; 8928 if (Inserter) 8929 Flags = Inserter->getFlags(); 8930 return getNode(Opcode, DL, VT, Ops, Flags); 8931 } 8932 8933 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8934 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8935 unsigned NumOps = Ops.size(); 8936 switch (NumOps) { 8937 case 0: return getNode(Opcode, DL, VT); 8938 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8939 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8940 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8941 default: break; 8942 } 8943 8944 #ifndef NDEBUG 8945 for (const auto &Op : Ops) 8946 assert(Op.getOpcode() != ISD::DELETED_NODE && 8947 "Operand is DELETED_NODE!"); 8948 #endif 8949 8950 switch (Opcode) { 8951 default: break; 8952 case ISD::BUILD_VECTOR: 8953 // Attempt to simplify BUILD_VECTOR. 8954 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8955 return V; 8956 break; 8957 case ISD::CONCAT_VECTORS: 8958 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8959 return V; 8960 break; 8961 case ISD::SELECT_CC: 8962 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8963 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8964 "LHS and RHS of condition must have same type!"); 8965 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8966 "True and False arms of SelectCC must have same type!"); 8967 assert(Ops[2].getValueType() == VT && 8968 "select_cc node must be of same type as true and false value!"); 8969 assert((!Ops[0].getValueType().isVector() || 8970 Ops[0].getValueType().getVectorElementCount() == 8971 VT.getVectorElementCount()) && 8972 "Expected select_cc with vector result to have the same sized " 8973 "comparison type!"); 8974 break; 8975 case ISD::BR_CC: 8976 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8977 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8978 "LHS/RHS of comparison should match types!"); 8979 break; 8980 case ISD::VP_ADD: 8981 case ISD::VP_SUB: 8982 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR 8983 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8984 Opcode = ISD::VP_XOR; 8985 break; 8986 case ISD::VP_MUL: 8987 // If it is VP_MUL mask operation then turn it to VP_AND 8988 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8989 Opcode = ISD::VP_AND; 8990 break; 8991 case ISD::VP_REDUCE_MUL: 8992 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND 8993 if (VT == MVT::i1) 8994 Opcode = ISD::VP_REDUCE_AND; 8995 break; 8996 case ISD::VP_REDUCE_ADD: 8997 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR 8998 if (VT == MVT::i1) 8999 Opcode = ISD::VP_REDUCE_XOR; 9000 break; 9001 case ISD::VP_REDUCE_SMAX: 9002 case ISD::VP_REDUCE_UMIN: 9003 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to 9004 // VP_REDUCE_AND. 9005 if (VT == MVT::i1) 9006 Opcode = ISD::VP_REDUCE_AND; 9007 break; 9008 case ISD::VP_REDUCE_SMIN: 9009 case ISD::VP_REDUCE_UMAX: 9010 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to 9011 // VP_REDUCE_OR. 9012 if (VT == MVT::i1) 9013 Opcode = ISD::VP_REDUCE_OR; 9014 break; 9015 } 9016 9017 // Memoize nodes. 9018 SDNode *N; 9019 SDVTList VTs = getVTList(VT); 9020 9021 if (VT != MVT::Glue) { 9022 FoldingSetNodeID ID; 9023 AddNodeIDNode(ID, Opcode, VTs, Ops); 9024 void *IP = nullptr; 9025 9026 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9027 return SDValue(E, 0); 9028 9029 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9030 createOperands(N, Ops); 9031 9032 CSEMap.InsertNode(N, IP); 9033 } else { 9034 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9035 createOperands(N, Ops); 9036 } 9037 9038 N->setFlags(Flags); 9039 InsertNode(N); 9040 SDValue V(N, 0); 9041 NewSDValueDbgMsg(V, "Creating new node: ", this); 9042 return V; 9043 } 9044 9045 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 9046 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 9047 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 9048 } 9049 9050 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9051 ArrayRef<SDValue> Ops) { 9052 SDNodeFlags Flags; 9053 if (Inserter) 9054 Flags = Inserter->getFlags(); 9055 return getNode(Opcode, DL, VTList, Ops, Flags); 9056 } 9057 9058 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9059 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 9060 if (VTList.NumVTs == 1) 9061 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags); 9062 9063 #ifndef NDEBUG 9064 for (const auto &Op : Ops) 9065 assert(Op.getOpcode() != ISD::DELETED_NODE && 9066 "Operand is DELETED_NODE!"); 9067 #endif 9068 9069 switch (Opcode) { 9070 case ISD::SADDO: 9071 case ISD::UADDO: 9072 case ISD::SSUBO: 9073 case ISD::USUBO: { 9074 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 9075 "Invalid add/sub overflow op!"); 9076 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() && 9077 Ops[0].getValueType() == Ops[1].getValueType() && 9078 Ops[0].getValueType() == VTList.VTs[0] && 9079 "Binary operator types must match!"); 9080 SDValue N1 = Ops[0], N2 = Ops[1]; 9081 canonicalizeCommutativeBinop(Opcode, N1, N2); 9082 9083 // (X +- 0) -> X with zero-overflow. 9084 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false, 9085 /*AllowTruncation*/ true); 9086 if (N2CV && N2CV->isZero()) { 9087 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]); 9088 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags); 9089 } 9090 break; 9091 } 9092 case ISD::STRICT_FP_EXTEND: 9093 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 9094 "Invalid STRICT_FP_EXTEND!"); 9095 assert(VTList.VTs[0].isFloatingPoint() && 9096 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 9097 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9098 "STRICT_FP_EXTEND result type should be vector iff the operand " 9099 "type is vector!"); 9100 assert((!VTList.VTs[0].isVector() || 9101 VTList.VTs[0].getVectorNumElements() == 9102 Ops[1].getValueType().getVectorNumElements()) && 9103 "Vector element count mismatch!"); 9104 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 9105 "Invalid fpext node, dst <= src!"); 9106 break; 9107 case ISD::STRICT_FP_ROUND: 9108 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 9109 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9110 "STRICT_FP_ROUND result type should be vector iff the operand " 9111 "type is vector!"); 9112 assert((!VTList.VTs[0].isVector() || 9113 VTList.VTs[0].getVectorNumElements() == 9114 Ops[1].getValueType().getVectorNumElements()) && 9115 "Vector element count mismatch!"); 9116 assert(VTList.VTs[0].isFloatingPoint() && 9117 Ops[1].getValueType().isFloatingPoint() && 9118 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 9119 isa<ConstantSDNode>(Ops[2]) && 9120 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 9121 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 9122 "Invalid STRICT_FP_ROUND!"); 9123 break; 9124 #if 0 9125 // FIXME: figure out how to safely handle things like 9126 // int foo(int x) { return 1 << (x & 255); } 9127 // int bar() { return foo(256); } 9128 case ISD::SRA_PARTS: 9129 case ISD::SRL_PARTS: 9130 case ISD::SHL_PARTS: 9131 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 9132 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 9133 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9134 else if (N3.getOpcode() == ISD::AND) 9135 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 9136 // If the and is only masking out bits that cannot effect the shift, 9137 // eliminate the and. 9138 unsigned NumBits = VT.getScalarSizeInBits()*2; 9139 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 9140 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9141 } 9142 break; 9143 #endif 9144 } 9145 9146 // Memoize the node unless it returns a flag. 9147 SDNode *N; 9148 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 9149 FoldingSetNodeID ID; 9150 AddNodeIDNode(ID, Opcode, VTList, Ops); 9151 void *IP = nullptr; 9152 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9153 return SDValue(E, 0); 9154 9155 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9156 createOperands(N, Ops); 9157 CSEMap.InsertNode(N, IP); 9158 } else { 9159 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9160 createOperands(N, Ops); 9161 } 9162 9163 N->setFlags(Flags); 9164 InsertNode(N); 9165 SDValue V(N, 0); 9166 NewSDValueDbgMsg(V, "Creating new node: ", this); 9167 return V; 9168 } 9169 9170 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 9171 SDVTList VTList) { 9172 return getNode(Opcode, DL, VTList, None); 9173 } 9174 9175 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9176 SDValue N1) { 9177 SDValue Ops[] = { N1 }; 9178 return getNode(Opcode, DL, VTList, Ops); 9179 } 9180 9181 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9182 SDValue N1, SDValue N2) { 9183 SDValue Ops[] = { N1, N2 }; 9184 return getNode(Opcode, DL, VTList, Ops); 9185 } 9186 9187 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9188 SDValue N1, SDValue N2, SDValue N3) { 9189 SDValue Ops[] = { N1, N2, N3 }; 9190 return getNode(Opcode, DL, VTList, Ops); 9191 } 9192 9193 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9194 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 9195 SDValue Ops[] = { N1, N2, N3, N4 }; 9196 return getNode(Opcode, DL, VTList, Ops); 9197 } 9198 9199 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9200 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 9201 SDValue N5) { 9202 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 9203 return getNode(Opcode, DL, VTList, Ops); 9204 } 9205 9206 SDVTList SelectionDAG::getVTList(EVT VT) { 9207 return makeVTList(SDNode::getValueTypeList(VT), 1); 9208 } 9209 9210 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 9211 FoldingSetNodeID ID; 9212 ID.AddInteger(2U); 9213 ID.AddInteger(VT1.getRawBits()); 9214 ID.AddInteger(VT2.getRawBits()); 9215 9216 void *IP = nullptr; 9217 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9218 if (!Result) { 9219 EVT *Array = Allocator.Allocate<EVT>(2); 9220 Array[0] = VT1; 9221 Array[1] = VT2; 9222 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 9223 VTListMap.InsertNode(Result, IP); 9224 } 9225 return Result->getSDVTList(); 9226 } 9227 9228 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 9229 FoldingSetNodeID ID; 9230 ID.AddInteger(3U); 9231 ID.AddInteger(VT1.getRawBits()); 9232 ID.AddInteger(VT2.getRawBits()); 9233 ID.AddInteger(VT3.getRawBits()); 9234 9235 void *IP = nullptr; 9236 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9237 if (!Result) { 9238 EVT *Array = Allocator.Allocate<EVT>(3); 9239 Array[0] = VT1; 9240 Array[1] = VT2; 9241 Array[2] = VT3; 9242 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9243 VTListMap.InsertNode(Result, IP); 9244 } 9245 return Result->getSDVTList(); 9246 } 9247 9248 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9249 FoldingSetNodeID ID; 9250 ID.AddInteger(4U); 9251 ID.AddInteger(VT1.getRawBits()); 9252 ID.AddInteger(VT2.getRawBits()); 9253 ID.AddInteger(VT3.getRawBits()); 9254 ID.AddInteger(VT4.getRawBits()); 9255 9256 void *IP = nullptr; 9257 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9258 if (!Result) { 9259 EVT *Array = Allocator.Allocate<EVT>(4); 9260 Array[0] = VT1; 9261 Array[1] = VT2; 9262 Array[2] = VT3; 9263 Array[3] = VT4; 9264 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9265 VTListMap.InsertNode(Result, IP); 9266 } 9267 return Result->getSDVTList(); 9268 } 9269 9270 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9271 unsigned NumVTs = VTs.size(); 9272 FoldingSetNodeID ID; 9273 ID.AddInteger(NumVTs); 9274 for (unsigned index = 0; index < NumVTs; index++) { 9275 ID.AddInteger(VTs[index].getRawBits()); 9276 } 9277 9278 void *IP = nullptr; 9279 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9280 if (!Result) { 9281 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9282 llvm::copy(VTs, Array); 9283 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9284 VTListMap.InsertNode(Result, IP); 9285 } 9286 return Result->getSDVTList(); 9287 } 9288 9289 9290 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9291 /// specified operands. If the resultant node already exists in the DAG, 9292 /// this does not modify the specified node, instead it returns the node that 9293 /// already exists. If the resultant node does not exist in the DAG, the 9294 /// input node is returned. As a degenerate case, if you specify the same 9295 /// input operands as the node already has, the input node is returned. 9296 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9297 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9298 9299 // Check to see if there is no change. 9300 if (Op == N->getOperand(0)) return N; 9301 9302 // See if the modified node already exists. 9303 void *InsertPos = nullptr; 9304 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9305 return Existing; 9306 9307 // Nope it doesn't. Remove the node from its current place in the maps. 9308 if (InsertPos) 9309 if (!RemoveNodeFromCSEMaps(N)) 9310 InsertPos = nullptr; 9311 9312 // Now we update the operands. 9313 N->OperandList[0].set(Op); 9314 9315 updateDivergence(N); 9316 // If this gets put into a CSE map, add it. 9317 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9318 return N; 9319 } 9320 9321 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9322 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9323 9324 // Check to see if there is no change. 9325 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9326 return N; // No operands changed, just return the input node. 9327 9328 // See if the modified node already exists. 9329 void *InsertPos = nullptr; 9330 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9331 return Existing; 9332 9333 // Nope it doesn't. Remove the node from its current place in the maps. 9334 if (InsertPos) 9335 if (!RemoveNodeFromCSEMaps(N)) 9336 InsertPos = nullptr; 9337 9338 // Now we update the operands. 9339 if (N->OperandList[0] != Op1) 9340 N->OperandList[0].set(Op1); 9341 if (N->OperandList[1] != Op2) 9342 N->OperandList[1].set(Op2); 9343 9344 updateDivergence(N); 9345 // If this gets put into a CSE map, add it. 9346 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9347 return N; 9348 } 9349 9350 SDNode *SelectionDAG:: 9351 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9352 SDValue Ops[] = { Op1, Op2, Op3 }; 9353 return UpdateNodeOperands(N, Ops); 9354 } 9355 9356 SDNode *SelectionDAG:: 9357 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9358 SDValue Op3, SDValue Op4) { 9359 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9360 return UpdateNodeOperands(N, Ops); 9361 } 9362 9363 SDNode *SelectionDAG:: 9364 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9365 SDValue Op3, SDValue Op4, SDValue Op5) { 9366 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9367 return UpdateNodeOperands(N, Ops); 9368 } 9369 9370 SDNode *SelectionDAG:: 9371 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9372 unsigned NumOps = Ops.size(); 9373 assert(N->getNumOperands() == NumOps && 9374 "Update with wrong number of operands"); 9375 9376 // If no operands changed just return the input node. 9377 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9378 return N; 9379 9380 // See if the modified node already exists. 9381 void *InsertPos = nullptr; 9382 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9383 return Existing; 9384 9385 // Nope it doesn't. Remove the node from its current place in the maps. 9386 if (InsertPos) 9387 if (!RemoveNodeFromCSEMaps(N)) 9388 InsertPos = nullptr; 9389 9390 // Now we update the operands. 9391 for (unsigned i = 0; i != NumOps; ++i) 9392 if (N->OperandList[i] != Ops[i]) 9393 N->OperandList[i].set(Ops[i]); 9394 9395 updateDivergence(N); 9396 // If this gets put into a CSE map, add it. 9397 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9398 return N; 9399 } 9400 9401 /// DropOperands - Release the operands and set this node to have 9402 /// zero operands. 9403 void SDNode::DropOperands() { 9404 // Unlike the code in MorphNodeTo that does this, we don't need to 9405 // watch for dead nodes here. 9406 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9407 SDUse &Use = *I++; 9408 Use.set(SDValue()); 9409 } 9410 } 9411 9412 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9413 ArrayRef<MachineMemOperand *> NewMemRefs) { 9414 if (NewMemRefs.empty()) { 9415 N->clearMemRefs(); 9416 return; 9417 } 9418 9419 // Check if we can avoid allocating by storing a single reference directly. 9420 if (NewMemRefs.size() == 1) { 9421 N->MemRefs = NewMemRefs[0]; 9422 N->NumMemRefs = 1; 9423 return; 9424 } 9425 9426 MachineMemOperand **MemRefsBuffer = 9427 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 9428 llvm::copy(NewMemRefs, MemRefsBuffer); 9429 N->MemRefs = MemRefsBuffer; 9430 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 9431 } 9432 9433 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 9434 /// machine opcode. 9435 /// 9436 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9437 EVT VT) { 9438 SDVTList VTs = getVTList(VT); 9439 return SelectNodeTo(N, MachineOpc, VTs, None); 9440 } 9441 9442 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9443 EVT VT, SDValue Op1) { 9444 SDVTList VTs = getVTList(VT); 9445 SDValue Ops[] = { Op1 }; 9446 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9447 } 9448 9449 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9450 EVT VT, SDValue Op1, 9451 SDValue Op2) { 9452 SDVTList VTs = getVTList(VT); 9453 SDValue Ops[] = { Op1, Op2 }; 9454 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9455 } 9456 9457 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9458 EVT VT, SDValue Op1, 9459 SDValue Op2, SDValue Op3) { 9460 SDVTList VTs = getVTList(VT); 9461 SDValue Ops[] = { Op1, Op2, Op3 }; 9462 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9463 } 9464 9465 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9466 EVT VT, ArrayRef<SDValue> Ops) { 9467 SDVTList VTs = getVTList(VT); 9468 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9469 } 9470 9471 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9472 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 9473 SDVTList VTs = getVTList(VT1, VT2); 9474 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9475 } 9476 9477 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9478 EVT VT1, EVT VT2) { 9479 SDVTList VTs = getVTList(VT1, VT2); 9480 return SelectNodeTo(N, MachineOpc, VTs, None); 9481 } 9482 9483 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9484 EVT VT1, EVT VT2, EVT VT3, 9485 ArrayRef<SDValue> Ops) { 9486 SDVTList VTs = getVTList(VT1, VT2, VT3); 9487 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9488 } 9489 9490 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9491 EVT VT1, EVT VT2, 9492 SDValue Op1, SDValue Op2) { 9493 SDVTList VTs = getVTList(VT1, VT2); 9494 SDValue Ops[] = { Op1, Op2 }; 9495 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9496 } 9497 9498 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9499 SDVTList VTs,ArrayRef<SDValue> Ops) { 9500 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 9501 // Reset the NodeID to -1. 9502 New->setNodeId(-1); 9503 if (New != N) { 9504 ReplaceAllUsesWith(N, New); 9505 RemoveDeadNode(N); 9506 } 9507 return New; 9508 } 9509 9510 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 9511 /// the line number information on the merged node since it is not possible to 9512 /// preserve the information that operation is associated with multiple lines. 9513 /// This will make the debugger working better at -O0, were there is a higher 9514 /// probability having other instructions associated with that line. 9515 /// 9516 /// For IROrder, we keep the smaller of the two 9517 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 9518 DebugLoc NLoc = N->getDebugLoc(); 9519 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 9520 N->setDebugLoc(DebugLoc()); 9521 } 9522 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 9523 N->setIROrder(Order); 9524 return N; 9525 } 9526 9527 /// MorphNodeTo - This *mutates* the specified node to have the specified 9528 /// return type, opcode, and operands. 9529 /// 9530 /// Note that MorphNodeTo returns the resultant node. If there is already a 9531 /// node of the specified opcode and operands, it returns that node instead of 9532 /// the current one. Note that the SDLoc need not be the same. 9533 /// 9534 /// Using MorphNodeTo is faster than creating a new node and swapping it in 9535 /// with ReplaceAllUsesWith both because it often avoids allocating a new 9536 /// node, and because it doesn't require CSE recalculation for any of 9537 /// the node's users. 9538 /// 9539 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 9540 /// As a consequence it isn't appropriate to use from within the DAG combiner or 9541 /// the legalizer which maintain worklists that would need to be updated when 9542 /// deleting things. 9543 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 9544 SDVTList VTs, ArrayRef<SDValue> Ops) { 9545 // If an identical node already exists, use it. 9546 void *IP = nullptr; 9547 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 9548 FoldingSetNodeID ID; 9549 AddNodeIDNode(ID, Opc, VTs, Ops); 9550 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 9551 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 9552 } 9553 9554 if (!RemoveNodeFromCSEMaps(N)) 9555 IP = nullptr; 9556 9557 // Start the morphing. 9558 N->NodeType = Opc; 9559 N->ValueList = VTs.VTs; 9560 N->NumValues = VTs.NumVTs; 9561 9562 // Clear the operands list, updating used nodes to remove this from their 9563 // use list. Keep track of any operands that become dead as a result. 9564 SmallPtrSet<SDNode*, 16> DeadNodeSet; 9565 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 9566 SDUse &Use = *I++; 9567 SDNode *Used = Use.getNode(); 9568 Use.set(SDValue()); 9569 if (Used->use_empty()) 9570 DeadNodeSet.insert(Used); 9571 } 9572 9573 // For MachineNode, initialize the memory references information. 9574 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 9575 MN->clearMemRefs(); 9576 9577 // Swap for an appropriately sized array from the recycler. 9578 removeOperands(N); 9579 createOperands(N, Ops); 9580 9581 // Delete any nodes that are still dead after adding the uses for the 9582 // new operands. 9583 if (!DeadNodeSet.empty()) { 9584 SmallVector<SDNode *, 16> DeadNodes; 9585 for (SDNode *N : DeadNodeSet) 9586 if (N->use_empty()) 9587 DeadNodes.push_back(N); 9588 RemoveDeadNodes(DeadNodes); 9589 } 9590 9591 if (IP) 9592 CSEMap.InsertNode(N, IP); // Memoize the new node. 9593 return N; 9594 } 9595 9596 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9597 unsigned OrigOpc = Node->getOpcode(); 9598 unsigned NewOpc; 9599 switch (OrigOpc) { 9600 default: 9601 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9602 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9603 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9604 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9605 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9606 #include "llvm/IR/ConstrainedOps.def" 9607 } 9608 9609 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9610 9611 // We're taking this node out of the chain, so we need to re-link things. 9612 SDValue InputChain = Node->getOperand(0); 9613 SDValue OutputChain = SDValue(Node, 1); 9614 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9615 9616 SmallVector<SDValue, 3> Ops; 9617 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9618 Ops.push_back(Node->getOperand(i)); 9619 9620 SDVTList VTs = getVTList(Node->getValueType(0)); 9621 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9622 9623 // MorphNodeTo can operate in two ways: if an existing node with the 9624 // specified operands exists, it can just return it. Otherwise, it 9625 // updates the node in place to have the requested operands. 9626 if (Res == Node) { 9627 // If we updated the node in place, reset the node ID. To the isel, 9628 // this should be just like a newly allocated machine node. 9629 Res->setNodeId(-1); 9630 } else { 9631 ReplaceAllUsesWith(Node, Res); 9632 RemoveDeadNode(Node); 9633 } 9634 9635 return Res; 9636 } 9637 9638 /// getMachineNode - These are used for target selectors to create a new node 9639 /// with specified return type(s), MachineInstr opcode, and operands. 9640 /// 9641 /// Note that getMachineNode returns the resultant node. If there is already a 9642 /// node of the specified opcode and operands, it returns that node instead of 9643 /// the current one. 9644 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9645 EVT VT) { 9646 SDVTList VTs = getVTList(VT); 9647 return getMachineNode(Opcode, dl, VTs, None); 9648 } 9649 9650 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9651 EVT VT, SDValue Op1) { 9652 SDVTList VTs = getVTList(VT); 9653 SDValue Ops[] = { Op1 }; 9654 return getMachineNode(Opcode, dl, VTs, Ops); 9655 } 9656 9657 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9658 EVT VT, SDValue Op1, SDValue Op2) { 9659 SDVTList VTs = getVTList(VT); 9660 SDValue Ops[] = { Op1, Op2 }; 9661 return getMachineNode(Opcode, dl, VTs, Ops); 9662 } 9663 9664 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9665 EVT VT, SDValue Op1, SDValue Op2, 9666 SDValue Op3) { 9667 SDVTList VTs = getVTList(VT); 9668 SDValue Ops[] = { Op1, Op2, Op3 }; 9669 return getMachineNode(Opcode, dl, VTs, Ops); 9670 } 9671 9672 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9673 EVT VT, ArrayRef<SDValue> Ops) { 9674 SDVTList VTs = getVTList(VT); 9675 return getMachineNode(Opcode, dl, VTs, Ops); 9676 } 9677 9678 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9679 EVT VT1, EVT VT2, SDValue Op1, 9680 SDValue Op2) { 9681 SDVTList VTs = getVTList(VT1, VT2); 9682 SDValue Ops[] = { Op1, Op2 }; 9683 return getMachineNode(Opcode, dl, VTs, Ops); 9684 } 9685 9686 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9687 EVT VT1, EVT VT2, SDValue Op1, 9688 SDValue Op2, SDValue Op3) { 9689 SDVTList VTs = getVTList(VT1, VT2); 9690 SDValue Ops[] = { Op1, Op2, Op3 }; 9691 return getMachineNode(Opcode, dl, VTs, Ops); 9692 } 9693 9694 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9695 EVT VT1, EVT VT2, 9696 ArrayRef<SDValue> Ops) { 9697 SDVTList VTs = getVTList(VT1, VT2); 9698 return getMachineNode(Opcode, dl, VTs, Ops); 9699 } 9700 9701 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9702 EVT VT1, EVT VT2, EVT VT3, 9703 SDValue Op1, SDValue Op2) { 9704 SDVTList VTs = getVTList(VT1, VT2, VT3); 9705 SDValue Ops[] = { Op1, Op2 }; 9706 return getMachineNode(Opcode, dl, VTs, Ops); 9707 } 9708 9709 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9710 EVT VT1, EVT VT2, EVT VT3, 9711 SDValue Op1, SDValue Op2, 9712 SDValue Op3) { 9713 SDVTList VTs = getVTList(VT1, VT2, VT3); 9714 SDValue Ops[] = { Op1, Op2, Op3 }; 9715 return getMachineNode(Opcode, dl, VTs, Ops); 9716 } 9717 9718 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9719 EVT VT1, EVT VT2, EVT VT3, 9720 ArrayRef<SDValue> Ops) { 9721 SDVTList VTs = getVTList(VT1, VT2, VT3); 9722 return getMachineNode(Opcode, dl, VTs, Ops); 9723 } 9724 9725 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9726 ArrayRef<EVT> ResultTys, 9727 ArrayRef<SDValue> Ops) { 9728 SDVTList VTs = getVTList(ResultTys); 9729 return getMachineNode(Opcode, dl, VTs, Ops); 9730 } 9731 9732 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9733 SDVTList VTs, 9734 ArrayRef<SDValue> Ops) { 9735 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9736 MachineSDNode *N; 9737 void *IP = nullptr; 9738 9739 if (DoCSE) { 9740 FoldingSetNodeID ID; 9741 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9742 IP = nullptr; 9743 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9744 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9745 } 9746 } 9747 9748 // Allocate a new MachineSDNode. 9749 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9750 createOperands(N, Ops); 9751 9752 if (DoCSE) 9753 CSEMap.InsertNode(N, IP); 9754 9755 InsertNode(N); 9756 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9757 return N; 9758 } 9759 9760 /// getTargetExtractSubreg - A convenience function for creating 9761 /// TargetOpcode::EXTRACT_SUBREG nodes. 9762 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9763 SDValue Operand) { 9764 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9765 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9766 VT, Operand, SRIdxVal); 9767 return SDValue(Subreg, 0); 9768 } 9769 9770 /// getTargetInsertSubreg - A convenience function for creating 9771 /// TargetOpcode::INSERT_SUBREG nodes. 9772 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9773 SDValue Operand, SDValue Subreg) { 9774 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9775 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9776 VT, Operand, Subreg, SRIdxVal); 9777 return SDValue(Result, 0); 9778 } 9779 9780 /// getNodeIfExists - Get the specified node if it's already available, or 9781 /// else return NULL. 9782 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9783 ArrayRef<SDValue> Ops) { 9784 SDNodeFlags Flags; 9785 if (Inserter) 9786 Flags = Inserter->getFlags(); 9787 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9788 } 9789 9790 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9791 ArrayRef<SDValue> Ops, 9792 const SDNodeFlags Flags) { 9793 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9794 FoldingSetNodeID ID; 9795 AddNodeIDNode(ID, Opcode, VTList, Ops); 9796 void *IP = nullptr; 9797 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9798 E->intersectFlagsWith(Flags); 9799 return E; 9800 } 9801 } 9802 return nullptr; 9803 } 9804 9805 /// doesNodeExist - Check if a node exists without modifying its flags. 9806 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9807 ArrayRef<SDValue> Ops) { 9808 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9809 FoldingSetNodeID ID; 9810 AddNodeIDNode(ID, Opcode, VTList, Ops); 9811 void *IP = nullptr; 9812 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9813 return true; 9814 } 9815 return false; 9816 } 9817 9818 /// getDbgValue - Creates a SDDbgValue node. 9819 /// 9820 /// SDNode 9821 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9822 SDNode *N, unsigned R, bool IsIndirect, 9823 const DebugLoc &DL, unsigned O) { 9824 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9825 "Expected inlined-at fields to agree"); 9826 return new (DbgInfo->getAlloc()) 9827 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9828 {}, IsIndirect, DL, O, 9829 /*IsVariadic=*/false); 9830 } 9831 9832 /// Constant 9833 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9834 DIExpression *Expr, 9835 const Value *C, 9836 const DebugLoc &DL, unsigned O) { 9837 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9838 "Expected inlined-at fields to agree"); 9839 return new (DbgInfo->getAlloc()) 9840 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9841 /*IsIndirect=*/false, DL, O, 9842 /*IsVariadic=*/false); 9843 } 9844 9845 /// FrameIndex 9846 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9847 DIExpression *Expr, unsigned FI, 9848 bool IsIndirect, 9849 const DebugLoc &DL, 9850 unsigned O) { 9851 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9852 "Expected inlined-at fields to agree"); 9853 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9854 } 9855 9856 /// FrameIndex with dependencies 9857 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9858 DIExpression *Expr, unsigned FI, 9859 ArrayRef<SDNode *> Dependencies, 9860 bool IsIndirect, 9861 const DebugLoc &DL, 9862 unsigned O) { 9863 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9864 "Expected inlined-at fields to agree"); 9865 return new (DbgInfo->getAlloc()) 9866 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9867 Dependencies, IsIndirect, DL, O, 9868 /*IsVariadic=*/false); 9869 } 9870 9871 /// VReg 9872 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9873 unsigned VReg, bool IsIndirect, 9874 const DebugLoc &DL, unsigned O) { 9875 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9876 "Expected inlined-at fields to agree"); 9877 return new (DbgInfo->getAlloc()) 9878 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9879 {}, IsIndirect, DL, O, 9880 /*IsVariadic=*/false); 9881 } 9882 9883 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9884 ArrayRef<SDDbgOperand> Locs, 9885 ArrayRef<SDNode *> Dependencies, 9886 bool IsIndirect, const DebugLoc &DL, 9887 unsigned O, bool IsVariadic) { 9888 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9889 "Expected inlined-at fields to agree"); 9890 return new (DbgInfo->getAlloc()) 9891 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9892 DL, O, IsVariadic); 9893 } 9894 9895 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9896 unsigned OffsetInBits, unsigned SizeInBits, 9897 bool InvalidateDbg) { 9898 SDNode *FromNode = From.getNode(); 9899 SDNode *ToNode = To.getNode(); 9900 assert(FromNode && ToNode && "Can't modify dbg values"); 9901 9902 // PR35338 9903 // TODO: assert(From != To && "Redundant dbg value transfer"); 9904 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9905 if (From == To || FromNode == ToNode) 9906 return; 9907 9908 if (!FromNode->getHasDebugValue()) 9909 return; 9910 9911 SDDbgOperand FromLocOp = 9912 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9913 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9914 9915 SmallVector<SDDbgValue *, 2> ClonedDVs; 9916 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9917 if (Dbg->isInvalidated()) 9918 continue; 9919 9920 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9921 9922 // Create a new location ops vector that is equal to the old vector, but 9923 // with each instance of FromLocOp replaced with ToLocOp. 9924 bool Changed = false; 9925 auto NewLocOps = Dbg->copyLocationOps(); 9926 std::replace_if( 9927 NewLocOps.begin(), NewLocOps.end(), 9928 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9929 bool Match = Op == FromLocOp; 9930 Changed |= Match; 9931 return Match; 9932 }, 9933 ToLocOp); 9934 // Ignore this SDDbgValue if we didn't find a matching location. 9935 if (!Changed) 9936 continue; 9937 9938 DIVariable *Var = Dbg->getVariable(); 9939 auto *Expr = Dbg->getExpression(); 9940 // If a fragment is requested, update the expression. 9941 if (SizeInBits) { 9942 // When splitting a larger (e.g., sign-extended) value whose 9943 // lower bits are described with an SDDbgValue, do not attempt 9944 // to transfer the SDDbgValue to the upper bits. 9945 if (auto FI = Expr->getFragmentInfo()) 9946 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9947 continue; 9948 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9949 SizeInBits); 9950 if (!Fragment) 9951 continue; 9952 Expr = *Fragment; 9953 } 9954 9955 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9956 // Clone the SDDbgValue and move it to To. 9957 SDDbgValue *Clone = getDbgValueList( 9958 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9959 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9960 Dbg->isVariadic()); 9961 ClonedDVs.push_back(Clone); 9962 9963 if (InvalidateDbg) { 9964 // Invalidate value and indicate the SDDbgValue should not be emitted. 9965 Dbg->setIsInvalidated(); 9966 Dbg->setIsEmitted(); 9967 } 9968 } 9969 9970 for (SDDbgValue *Dbg : ClonedDVs) { 9971 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9972 "Transferred DbgValues should depend on the new SDNode"); 9973 AddDbgValue(Dbg, false); 9974 } 9975 } 9976 9977 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9978 if (!N.getHasDebugValue()) 9979 return; 9980 9981 SmallVector<SDDbgValue *, 2> ClonedDVs; 9982 for (auto *DV : GetDbgValues(&N)) { 9983 if (DV->isInvalidated()) 9984 continue; 9985 switch (N.getOpcode()) { 9986 default: 9987 break; 9988 case ISD::ADD: 9989 SDValue N0 = N.getOperand(0); 9990 SDValue N1 = N.getOperand(1); 9991 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9992 isConstantIntBuildVectorOrConstantInt(N1)) { 9993 uint64_t Offset = N.getConstantOperandVal(1); 9994 9995 // Rewrite an ADD constant node into a DIExpression. Since we are 9996 // performing arithmetic to compute the variable's *value* in the 9997 // DIExpression, we need to mark the expression with a 9998 // DW_OP_stack_value. 9999 auto *DIExpr = DV->getExpression(); 10000 auto NewLocOps = DV->copyLocationOps(); 10001 bool Changed = false; 10002 for (size_t i = 0; i < NewLocOps.size(); ++i) { 10003 // We're not given a ResNo to compare against because the whole 10004 // node is going away. We know that any ISD::ADD only has one 10005 // result, so we can assume any node match is using the result. 10006 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 10007 NewLocOps[i].getSDNode() != &N) 10008 continue; 10009 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 10010 SmallVector<uint64_t, 3> ExprOps; 10011 DIExpression::appendOffset(ExprOps, Offset); 10012 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 10013 Changed = true; 10014 } 10015 (void)Changed; 10016 assert(Changed && "Salvage target doesn't use N"); 10017 10018 auto AdditionalDependencies = DV->getAdditionalDependencies(); 10019 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 10020 NewLocOps, AdditionalDependencies, 10021 DV->isIndirect(), DV->getDebugLoc(), 10022 DV->getOrder(), DV->isVariadic()); 10023 ClonedDVs.push_back(Clone); 10024 DV->setIsInvalidated(); 10025 DV->setIsEmitted(); 10026 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 10027 N0.getNode()->dumprFull(this); 10028 dbgs() << " into " << *DIExpr << '\n'); 10029 } 10030 } 10031 } 10032 10033 for (SDDbgValue *Dbg : ClonedDVs) { 10034 assert(!Dbg->getSDNodes().empty() && 10035 "Salvaged DbgValue should depend on a new SDNode"); 10036 AddDbgValue(Dbg, false); 10037 } 10038 } 10039 10040 /// Creates a SDDbgLabel node. 10041 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 10042 const DebugLoc &DL, unsigned O) { 10043 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 10044 "Expected inlined-at fields to agree"); 10045 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 10046 } 10047 10048 namespace { 10049 10050 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 10051 /// pointed to by a use iterator is deleted, increment the use iterator 10052 /// so that it doesn't dangle. 10053 /// 10054 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 10055 SDNode::use_iterator &UI; 10056 SDNode::use_iterator &UE; 10057 10058 void NodeDeleted(SDNode *N, SDNode *E) override { 10059 // Increment the iterator as needed. 10060 while (UI != UE && N == *UI) 10061 ++UI; 10062 } 10063 10064 public: 10065 RAUWUpdateListener(SelectionDAG &d, 10066 SDNode::use_iterator &ui, 10067 SDNode::use_iterator &ue) 10068 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 10069 }; 10070 10071 } // end anonymous namespace 10072 10073 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10074 /// This can cause recursive merging of nodes in the DAG. 10075 /// 10076 /// This version assumes From has a single result value. 10077 /// 10078 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 10079 SDNode *From = FromN.getNode(); 10080 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 10081 "Cannot replace with this method!"); 10082 assert(From != To.getNode() && "Cannot replace uses of with self"); 10083 10084 // Preserve Debug Values 10085 transferDbgValues(FromN, To); 10086 10087 // Iterate over all the existing uses of From. New uses will be added 10088 // to the beginning of the use list, which we avoid visiting. 10089 // This specifically avoids visiting uses of From that arise while the 10090 // replacement is happening, because any such uses would be the result 10091 // of CSE: If an existing node looks like From after one of its operands 10092 // is replaced by To, we don't want to replace of all its users with To 10093 // too. See PR3018 for more info. 10094 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10095 RAUWUpdateListener Listener(*this, UI, UE); 10096 while (UI != UE) { 10097 SDNode *User = *UI; 10098 10099 // This node is about to morph, remove its old self from the CSE maps. 10100 RemoveNodeFromCSEMaps(User); 10101 10102 // A user can appear in a use list multiple times, and when this 10103 // happens the uses are usually next to each other in the list. 10104 // To help reduce the number of CSE recomputations, process all 10105 // the uses of this user that we can find this way. 10106 do { 10107 SDUse &Use = UI.getUse(); 10108 ++UI; 10109 Use.set(To); 10110 if (To->isDivergent() != From->isDivergent()) 10111 updateDivergence(User); 10112 } while (UI != UE && *UI == User); 10113 // Now that we have modified User, add it back to the CSE maps. If it 10114 // already exists there, recursively merge the results together. 10115 AddModifiedNodeToCSEMaps(User); 10116 } 10117 10118 // If we just RAUW'd the root, take note. 10119 if (FromN == getRoot()) 10120 setRoot(To); 10121 } 10122 10123 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10124 /// This can cause recursive merging of nodes in the DAG. 10125 /// 10126 /// This version assumes that for each value of From, there is a 10127 /// corresponding value in To in the same position with the same type. 10128 /// 10129 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 10130 #ifndef NDEBUG 10131 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10132 assert((!From->hasAnyUseOfValue(i) || 10133 From->getValueType(i) == To->getValueType(i)) && 10134 "Cannot use this version of ReplaceAllUsesWith!"); 10135 #endif 10136 10137 // Handle the trivial case. 10138 if (From == To) 10139 return; 10140 10141 // Preserve Debug Info. Only do this if there's a use. 10142 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10143 if (From->hasAnyUseOfValue(i)) { 10144 assert((i < To->getNumValues()) && "Invalid To location"); 10145 transferDbgValues(SDValue(From, i), SDValue(To, i)); 10146 } 10147 10148 // Iterate over just the existing users of From. See the comments in 10149 // the ReplaceAllUsesWith above. 10150 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10151 RAUWUpdateListener Listener(*this, UI, UE); 10152 while (UI != UE) { 10153 SDNode *User = *UI; 10154 10155 // This node is about to morph, remove its old self from the CSE maps. 10156 RemoveNodeFromCSEMaps(User); 10157 10158 // A user can appear in a use list multiple times, and when this 10159 // happens the uses are usually next to each other in the list. 10160 // To help reduce the number of CSE recomputations, process all 10161 // the uses of this user that we can find this way. 10162 do { 10163 SDUse &Use = UI.getUse(); 10164 ++UI; 10165 Use.setNode(To); 10166 if (To->isDivergent() != From->isDivergent()) 10167 updateDivergence(User); 10168 } while (UI != UE && *UI == User); 10169 10170 // Now that we have modified User, add it back to the CSE maps. If it 10171 // already exists there, recursively merge the results together. 10172 AddModifiedNodeToCSEMaps(User); 10173 } 10174 10175 // If we just RAUW'd the root, take note. 10176 if (From == getRoot().getNode()) 10177 setRoot(SDValue(To, getRoot().getResNo())); 10178 } 10179 10180 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10181 /// This can cause recursive merging of nodes in the DAG. 10182 /// 10183 /// This version can replace From with any result values. To must match the 10184 /// number and types of values returned by From. 10185 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 10186 if (From->getNumValues() == 1) // Handle the simple case efficiently. 10187 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 10188 10189 // Preserve Debug Info. 10190 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10191 transferDbgValues(SDValue(From, i), To[i]); 10192 10193 // Iterate over just the existing users of From. See the comments in 10194 // the ReplaceAllUsesWith above. 10195 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10196 RAUWUpdateListener Listener(*this, UI, UE); 10197 while (UI != UE) { 10198 SDNode *User = *UI; 10199 10200 // This node is about to morph, remove its old self from the CSE maps. 10201 RemoveNodeFromCSEMaps(User); 10202 10203 // A user can appear in a use list multiple times, and when this happens the 10204 // uses are usually next to each other in the list. To help reduce the 10205 // number of CSE and divergence recomputations, process all the uses of this 10206 // user that we can find this way. 10207 bool To_IsDivergent = false; 10208 do { 10209 SDUse &Use = UI.getUse(); 10210 const SDValue &ToOp = To[Use.getResNo()]; 10211 ++UI; 10212 Use.set(ToOp); 10213 To_IsDivergent |= ToOp->isDivergent(); 10214 } while (UI != UE && *UI == User); 10215 10216 if (To_IsDivergent != From->isDivergent()) 10217 updateDivergence(User); 10218 10219 // Now that we have modified User, add it back to the CSE maps. If it 10220 // already exists there, recursively merge the results together. 10221 AddModifiedNodeToCSEMaps(User); 10222 } 10223 10224 // If we just RAUW'd the root, take note. 10225 if (From == getRoot().getNode()) 10226 setRoot(SDValue(To[getRoot().getResNo()])); 10227 } 10228 10229 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 10230 /// uses of other values produced by From.getNode() alone. The Deleted 10231 /// vector is handled the same way as for ReplaceAllUsesWith. 10232 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 10233 // Handle the really simple, really trivial case efficiently. 10234 if (From == To) return; 10235 10236 // Handle the simple, trivial, case efficiently. 10237 if (From.getNode()->getNumValues() == 1) { 10238 ReplaceAllUsesWith(From, To); 10239 return; 10240 } 10241 10242 // Preserve Debug Info. 10243 transferDbgValues(From, To); 10244 10245 // Iterate over just the existing users of From. See the comments in 10246 // the ReplaceAllUsesWith above. 10247 SDNode::use_iterator UI = From.getNode()->use_begin(), 10248 UE = From.getNode()->use_end(); 10249 RAUWUpdateListener Listener(*this, UI, UE); 10250 while (UI != UE) { 10251 SDNode *User = *UI; 10252 bool UserRemovedFromCSEMaps = false; 10253 10254 // A user can appear in a use list multiple times, and when this 10255 // happens the uses are usually next to each other in the list. 10256 // To help reduce the number of CSE recomputations, process all 10257 // the uses of this user that we can find this way. 10258 do { 10259 SDUse &Use = UI.getUse(); 10260 10261 // Skip uses of different values from the same node. 10262 if (Use.getResNo() != From.getResNo()) { 10263 ++UI; 10264 continue; 10265 } 10266 10267 // If this node hasn't been modified yet, it's still in the CSE maps, 10268 // so remove its old self from the CSE maps. 10269 if (!UserRemovedFromCSEMaps) { 10270 RemoveNodeFromCSEMaps(User); 10271 UserRemovedFromCSEMaps = true; 10272 } 10273 10274 ++UI; 10275 Use.set(To); 10276 if (To->isDivergent() != From->isDivergent()) 10277 updateDivergence(User); 10278 } while (UI != UE && *UI == User); 10279 // We are iterating over all uses of the From node, so if a use 10280 // doesn't use the specific value, no changes are made. 10281 if (!UserRemovedFromCSEMaps) 10282 continue; 10283 10284 // Now that we have modified User, add it back to the CSE maps. If it 10285 // already exists there, recursively merge the results together. 10286 AddModifiedNodeToCSEMaps(User); 10287 } 10288 10289 // If we just RAUW'd the root, take note. 10290 if (From == getRoot()) 10291 setRoot(To); 10292 } 10293 10294 namespace { 10295 10296 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10297 /// to record information about a use. 10298 struct UseMemo { 10299 SDNode *User; 10300 unsigned Index; 10301 SDUse *Use; 10302 }; 10303 10304 /// operator< - Sort Memos by User. 10305 bool operator<(const UseMemo &L, const UseMemo &R) { 10306 return (intptr_t)L.User < (intptr_t)R.User; 10307 } 10308 10309 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10310 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10311 /// the node already has been taken care of recursively. 10312 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10313 SmallVector<UseMemo, 4> &Uses; 10314 10315 void NodeDeleted(SDNode *N, SDNode *E) override { 10316 for (UseMemo &Memo : Uses) 10317 if (Memo.User == N) 10318 Memo.User = nullptr; 10319 } 10320 10321 public: 10322 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10323 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10324 }; 10325 10326 } // end anonymous namespace 10327 10328 bool SelectionDAG::calculateDivergence(SDNode *N) { 10329 if (TLI->isSDNodeAlwaysUniform(N)) { 10330 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 10331 "Conflicting divergence information!"); 10332 return false; 10333 } 10334 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 10335 return true; 10336 for (const auto &Op : N->ops()) { 10337 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10338 return true; 10339 } 10340 return false; 10341 } 10342 10343 void SelectionDAG::updateDivergence(SDNode *N) { 10344 SmallVector<SDNode *, 16> Worklist(1, N); 10345 do { 10346 N = Worklist.pop_back_val(); 10347 bool IsDivergent = calculateDivergence(N); 10348 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10349 N->SDNodeBits.IsDivergent = IsDivergent; 10350 llvm::append_range(Worklist, N->uses()); 10351 } 10352 } while (!Worklist.empty()); 10353 } 10354 10355 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10356 DenseMap<SDNode *, unsigned> Degree; 10357 Order.reserve(AllNodes.size()); 10358 for (auto &N : allnodes()) { 10359 unsigned NOps = N.getNumOperands(); 10360 Degree[&N] = NOps; 10361 if (0 == NOps) 10362 Order.push_back(&N); 10363 } 10364 for (size_t I = 0; I != Order.size(); ++I) { 10365 SDNode *N = Order[I]; 10366 for (auto *U : N->uses()) { 10367 unsigned &UnsortedOps = Degree[U]; 10368 if (0 == --UnsortedOps) 10369 Order.push_back(U); 10370 } 10371 } 10372 } 10373 10374 #ifndef NDEBUG 10375 void SelectionDAG::VerifyDAGDivergence() { 10376 std::vector<SDNode *> TopoOrder; 10377 CreateTopologicalOrder(TopoOrder); 10378 for (auto *N : TopoOrder) { 10379 assert(calculateDivergence(N) == N->isDivergent() && 10380 "Divergence bit inconsistency detected"); 10381 } 10382 } 10383 #endif 10384 10385 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10386 /// uses of other values produced by From.getNode() alone. The same value 10387 /// may appear in both the From and To list. The Deleted vector is 10388 /// handled the same way as for ReplaceAllUsesWith. 10389 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10390 const SDValue *To, 10391 unsigned Num){ 10392 // Handle the simple, trivial case efficiently. 10393 if (Num == 1) 10394 return ReplaceAllUsesOfValueWith(*From, *To); 10395 10396 transferDbgValues(*From, *To); 10397 10398 // Read up all the uses and make records of them. This helps 10399 // processing new uses that are introduced during the 10400 // replacement process. 10401 SmallVector<UseMemo, 4> Uses; 10402 for (unsigned i = 0; i != Num; ++i) { 10403 unsigned FromResNo = From[i].getResNo(); 10404 SDNode *FromNode = From[i].getNode(); 10405 for (SDNode::use_iterator UI = FromNode->use_begin(), 10406 E = FromNode->use_end(); UI != E; ++UI) { 10407 SDUse &Use = UI.getUse(); 10408 if (Use.getResNo() == FromResNo) { 10409 UseMemo Memo = { *UI, i, &Use }; 10410 Uses.push_back(Memo); 10411 } 10412 } 10413 } 10414 10415 // Sort the uses, so that all the uses from a given User are together. 10416 llvm::sort(Uses); 10417 RAUOVWUpdateListener Listener(*this, Uses); 10418 10419 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 10420 UseIndex != UseIndexEnd; ) { 10421 // We know that this user uses some value of From. If it is the right 10422 // value, update it. 10423 SDNode *User = Uses[UseIndex].User; 10424 // If the node has been deleted by recursive CSE updates when updating 10425 // another node, then just skip this entry. 10426 if (User == nullptr) { 10427 ++UseIndex; 10428 continue; 10429 } 10430 10431 // This node is about to morph, remove its old self from the CSE maps. 10432 RemoveNodeFromCSEMaps(User); 10433 10434 // The Uses array is sorted, so all the uses for a given User 10435 // are next to each other in the list. 10436 // To help reduce the number of CSE recomputations, process all 10437 // the uses of this user that we can find this way. 10438 do { 10439 unsigned i = Uses[UseIndex].Index; 10440 SDUse &Use = *Uses[UseIndex].Use; 10441 ++UseIndex; 10442 10443 Use.set(To[i]); 10444 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 10445 10446 // Now that we have modified User, add it back to the CSE maps. If it 10447 // already exists there, recursively merge the results together. 10448 AddModifiedNodeToCSEMaps(User); 10449 } 10450 } 10451 10452 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 10453 /// based on their topological order. It returns the maximum id and a vector 10454 /// of the SDNodes* in assigned order by reference. 10455 unsigned SelectionDAG::AssignTopologicalOrder() { 10456 unsigned DAGSize = 0; 10457 10458 // SortedPos tracks the progress of the algorithm. Nodes before it are 10459 // sorted, nodes after it are unsorted. When the algorithm completes 10460 // it is at the end of the list. 10461 allnodes_iterator SortedPos = allnodes_begin(); 10462 10463 // Visit all the nodes. Move nodes with no operands to the front of 10464 // the list immediately. Annotate nodes that do have operands with their 10465 // operand count. Before we do this, the Node Id fields of the nodes 10466 // may contain arbitrary values. After, the Node Id fields for nodes 10467 // before SortedPos will contain the topological sort index, and the 10468 // Node Id fields for nodes At SortedPos and after will contain the 10469 // count of outstanding operands. 10470 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 10471 checkForCycles(&N, this); 10472 unsigned Degree = N.getNumOperands(); 10473 if (Degree == 0) { 10474 // A node with no uses, add it to the result array immediately. 10475 N.setNodeId(DAGSize++); 10476 allnodes_iterator Q(&N); 10477 if (Q != SortedPos) 10478 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 10479 assert(SortedPos != AllNodes.end() && "Overran node list"); 10480 ++SortedPos; 10481 } else { 10482 // Temporarily use the Node Id as scratch space for the degree count. 10483 N.setNodeId(Degree); 10484 } 10485 } 10486 10487 // Visit all the nodes. As we iterate, move nodes into sorted order, 10488 // such that by the time the end is reached all nodes will be sorted. 10489 for (SDNode &Node : allnodes()) { 10490 SDNode *N = &Node; 10491 checkForCycles(N, this); 10492 // N is in sorted position, so all its uses have one less operand 10493 // that needs to be sorted. 10494 for (SDNode *P : N->uses()) { 10495 unsigned Degree = P->getNodeId(); 10496 assert(Degree != 0 && "Invalid node degree"); 10497 --Degree; 10498 if (Degree == 0) { 10499 // All of P's operands are sorted, so P may sorted now. 10500 P->setNodeId(DAGSize++); 10501 if (P->getIterator() != SortedPos) 10502 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 10503 assert(SortedPos != AllNodes.end() && "Overran node list"); 10504 ++SortedPos; 10505 } else { 10506 // Update P's outstanding operand count. 10507 P->setNodeId(Degree); 10508 } 10509 } 10510 if (Node.getIterator() == SortedPos) { 10511 #ifndef NDEBUG 10512 allnodes_iterator I(N); 10513 SDNode *S = &*++I; 10514 dbgs() << "Overran sorted position:\n"; 10515 S->dumprFull(this); dbgs() << "\n"; 10516 dbgs() << "Checking if this is due to cycles\n"; 10517 checkForCycles(this, true); 10518 #endif 10519 llvm_unreachable(nullptr); 10520 } 10521 } 10522 10523 assert(SortedPos == AllNodes.end() && 10524 "Topological sort incomplete!"); 10525 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 10526 "First node in topological sort is not the entry token!"); 10527 assert(AllNodes.front().getNodeId() == 0 && 10528 "First node in topological sort has non-zero id!"); 10529 assert(AllNodes.front().getNumOperands() == 0 && 10530 "First node in topological sort has operands!"); 10531 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 10532 "Last node in topologic sort has unexpected id!"); 10533 assert(AllNodes.back().use_empty() && 10534 "Last node in topologic sort has users!"); 10535 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 10536 return DAGSize; 10537 } 10538 10539 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 10540 /// value is produced by SD. 10541 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 10542 for (SDNode *SD : DB->getSDNodes()) { 10543 if (!SD) 10544 continue; 10545 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 10546 SD->setHasDebugValue(true); 10547 } 10548 DbgInfo->add(DB, isParameter); 10549 } 10550 10551 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 10552 10553 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 10554 SDValue NewMemOpChain) { 10555 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 10556 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 10557 // The new memory operation must have the same position as the old load in 10558 // terms of memory dependency. Create a TokenFactor for the old load and new 10559 // memory operation and update uses of the old load's output chain to use that 10560 // TokenFactor. 10561 if (OldChain == NewMemOpChain || OldChain.use_empty()) 10562 return NewMemOpChain; 10563 10564 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 10565 OldChain, NewMemOpChain); 10566 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 10567 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 10568 return TokenFactor; 10569 } 10570 10571 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 10572 SDValue NewMemOp) { 10573 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 10574 SDValue OldChain = SDValue(OldLoad, 1); 10575 SDValue NewMemOpChain = NewMemOp.getValue(1); 10576 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 10577 } 10578 10579 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 10580 Function **OutFunction) { 10581 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 10582 10583 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 10584 auto *Module = MF->getFunction().getParent(); 10585 auto *Function = Module->getFunction(Symbol); 10586 10587 if (OutFunction != nullptr) 10588 *OutFunction = Function; 10589 10590 if (Function != nullptr) { 10591 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 10592 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 10593 } 10594 10595 std::string ErrorStr; 10596 raw_string_ostream ErrorFormatter(ErrorStr); 10597 ErrorFormatter << "Undefined external symbol "; 10598 ErrorFormatter << '"' << Symbol << '"'; 10599 report_fatal_error(Twine(ErrorFormatter.str())); 10600 } 10601 10602 //===----------------------------------------------------------------------===// 10603 // SDNode Class 10604 //===----------------------------------------------------------------------===// 10605 10606 bool llvm::isNullConstant(SDValue V) { 10607 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10608 return Const != nullptr && Const->isZero(); 10609 } 10610 10611 bool llvm::isNullFPConstant(SDValue V) { 10612 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10613 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10614 } 10615 10616 bool llvm::isAllOnesConstant(SDValue V) { 10617 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10618 return Const != nullptr && Const->isAllOnes(); 10619 } 10620 10621 bool llvm::isOneConstant(SDValue V) { 10622 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10623 return Const != nullptr && Const->isOne(); 10624 } 10625 10626 bool llvm::isMinSignedConstant(SDValue V) { 10627 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10628 return Const != nullptr && Const->isMinSignedValue(); 10629 } 10630 10631 SDValue llvm::peekThroughBitcasts(SDValue V) { 10632 while (V.getOpcode() == ISD::BITCAST) 10633 V = V.getOperand(0); 10634 return V; 10635 } 10636 10637 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10638 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10639 V = V.getOperand(0); 10640 return V; 10641 } 10642 10643 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10644 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10645 V = V.getOperand(0); 10646 return V; 10647 } 10648 10649 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10650 if (V.getOpcode() != ISD::XOR) 10651 return false; 10652 V = peekThroughBitcasts(V.getOperand(1)); 10653 unsigned NumBits = V.getScalarValueSizeInBits(); 10654 ConstantSDNode *C = 10655 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10656 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10657 } 10658 10659 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10660 bool AllowTruncation) { 10661 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10662 return CN; 10663 10664 // SplatVectors can truncate their operands. Ignore that case here unless 10665 // AllowTruncation is set. 10666 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10667 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10668 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10669 EVT CVT = CN->getValueType(0); 10670 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10671 if (AllowTruncation || CVT == VecEltVT) 10672 return CN; 10673 } 10674 } 10675 10676 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10677 BitVector UndefElements; 10678 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10679 10680 // BuildVectors can truncate their operands. Ignore that case here unless 10681 // AllowTruncation is set. 10682 if (CN && (UndefElements.none() || AllowUndefs)) { 10683 EVT CVT = CN->getValueType(0); 10684 EVT NSVT = N.getValueType().getScalarType(); 10685 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10686 if (AllowTruncation || (CVT == NSVT)) 10687 return CN; 10688 } 10689 } 10690 10691 return nullptr; 10692 } 10693 10694 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10695 bool AllowUndefs, 10696 bool AllowTruncation) { 10697 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10698 return CN; 10699 10700 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10701 BitVector UndefElements; 10702 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10703 10704 // BuildVectors can truncate their operands. Ignore that case here unless 10705 // AllowTruncation is set. 10706 if (CN && (UndefElements.none() || AllowUndefs)) { 10707 EVT CVT = CN->getValueType(0); 10708 EVT NSVT = N.getValueType().getScalarType(); 10709 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10710 if (AllowTruncation || (CVT == NSVT)) 10711 return CN; 10712 } 10713 } 10714 10715 return nullptr; 10716 } 10717 10718 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10719 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10720 return CN; 10721 10722 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10723 BitVector UndefElements; 10724 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10725 if (CN && (UndefElements.none() || AllowUndefs)) 10726 return CN; 10727 } 10728 10729 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10730 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10731 return CN; 10732 10733 return nullptr; 10734 } 10735 10736 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10737 const APInt &DemandedElts, 10738 bool AllowUndefs) { 10739 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10740 return CN; 10741 10742 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10743 BitVector UndefElements; 10744 ConstantFPSDNode *CN = 10745 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10746 if (CN && (UndefElements.none() || AllowUndefs)) 10747 return CN; 10748 } 10749 10750 return nullptr; 10751 } 10752 10753 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10754 // TODO: may want to use peekThroughBitcast() here. 10755 ConstantSDNode *C = 10756 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10757 return C && C->isZero(); 10758 } 10759 10760 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10761 ConstantSDNode *C = 10762 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true); 10763 return C && C->isOne(); 10764 } 10765 10766 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10767 N = peekThroughBitcasts(N); 10768 unsigned BitWidth = N.getScalarValueSizeInBits(); 10769 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10770 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10771 } 10772 10773 HandleSDNode::~HandleSDNode() { 10774 DropOperands(); 10775 } 10776 10777 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10778 const DebugLoc &DL, 10779 const GlobalValue *GA, EVT VT, 10780 int64_t o, unsigned TF) 10781 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10782 TheGlobal = GA; 10783 } 10784 10785 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10786 EVT VT, unsigned SrcAS, 10787 unsigned DestAS) 10788 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10789 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10790 10791 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10792 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10793 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10794 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10795 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10796 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10797 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10798 10799 // We check here that the size of the memory operand fits within the size of 10800 // the MMO. This is because the MMO might indicate only a possible address 10801 // range instead of specifying the affected memory addresses precisely. 10802 // TODO: Make MachineMemOperands aware of scalable vectors. 10803 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10804 "Size mismatch!"); 10805 } 10806 10807 /// Profile - Gather unique data for the node. 10808 /// 10809 void SDNode::Profile(FoldingSetNodeID &ID) const { 10810 AddNodeIDNode(ID, this); 10811 } 10812 10813 namespace { 10814 10815 struct EVTArray { 10816 std::vector<EVT> VTs; 10817 10818 EVTArray() { 10819 VTs.reserve(MVT::VALUETYPE_SIZE); 10820 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10821 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10822 } 10823 }; 10824 10825 } // end anonymous namespace 10826 10827 /// getValueTypeList - Return a pointer to the specified value type. 10828 /// 10829 const EVT *SDNode::getValueTypeList(EVT VT) { 10830 static std::set<EVT, EVT::compareRawBits> EVTs; 10831 static EVTArray SimpleVTArray; 10832 static sys::SmartMutex<true> VTMutex; 10833 10834 if (VT.isExtended()) { 10835 sys::SmartScopedLock<true> Lock(VTMutex); 10836 return &(*EVTs.insert(VT).first); 10837 } 10838 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10839 return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy]; 10840 } 10841 10842 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10843 /// indicated value. This method ignores uses of other values defined by this 10844 /// operation. 10845 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10846 assert(Value < getNumValues() && "Bad value!"); 10847 10848 // TODO: Only iterate over uses of a given value of the node 10849 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10850 if (UI.getUse().getResNo() == Value) { 10851 if (NUses == 0) 10852 return false; 10853 --NUses; 10854 } 10855 } 10856 10857 // Found exactly the right number of uses? 10858 return NUses == 0; 10859 } 10860 10861 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10862 /// value. This method ignores uses of other values defined by this operation. 10863 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10864 assert(Value < getNumValues() && "Bad value!"); 10865 10866 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10867 if (UI.getUse().getResNo() == Value) 10868 return true; 10869 10870 return false; 10871 } 10872 10873 /// isOnlyUserOf - Return true if this node is the only use of N. 10874 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10875 bool Seen = false; 10876 for (const SDNode *User : N->uses()) { 10877 if (User == this) 10878 Seen = true; 10879 else 10880 return false; 10881 } 10882 10883 return Seen; 10884 } 10885 10886 /// Return true if the only users of N are contained in Nodes. 10887 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10888 bool Seen = false; 10889 for (const SDNode *User : N->uses()) { 10890 if (llvm::is_contained(Nodes, User)) 10891 Seen = true; 10892 else 10893 return false; 10894 } 10895 10896 return Seen; 10897 } 10898 10899 /// isOperand - Return true if this node is an operand of N. 10900 bool SDValue::isOperandOf(const SDNode *N) const { 10901 return is_contained(N->op_values(), *this); 10902 } 10903 10904 bool SDNode::isOperandOf(const SDNode *N) const { 10905 return any_of(N->op_values(), 10906 [this](SDValue Op) { return this == Op.getNode(); }); 10907 } 10908 10909 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10910 /// be a chain) reaches the specified operand without crossing any 10911 /// side-effecting instructions on any chain path. In practice, this looks 10912 /// through token factors and non-volatile loads. In order to remain efficient, 10913 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10914 /// 10915 /// Note that we only need to examine chains when we're searching for 10916 /// side-effects; SelectionDAG requires that all side-effects are represented 10917 /// by chains, even if another operand would force a specific ordering. This 10918 /// constraint is necessary to allow transformations like splitting loads. 10919 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10920 unsigned Depth) const { 10921 if (*this == Dest) return true; 10922 10923 // Don't search too deeply, we just want to be able to see through 10924 // TokenFactor's etc. 10925 if (Depth == 0) return false; 10926 10927 // If this is a token factor, all inputs to the TF happen in parallel. 10928 if (getOpcode() == ISD::TokenFactor) { 10929 // First, try a shallow search. 10930 if (is_contained((*this)->ops(), Dest)) { 10931 // We found the chain we want as an operand of this TokenFactor. 10932 // Essentially, we reach the chain without side-effects if we could 10933 // serialize the TokenFactor into a simple chain of operations with 10934 // Dest as the last operation. This is automatically true if the 10935 // chain has one use: there are no other ordering constraints. 10936 // If the chain has more than one use, we give up: some other 10937 // use of Dest might force a side-effect between Dest and the current 10938 // node. 10939 if (Dest.hasOneUse()) 10940 return true; 10941 } 10942 // Next, try a deep search: check whether every operand of the TokenFactor 10943 // reaches Dest. 10944 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10945 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10946 }); 10947 } 10948 10949 // Loads don't have side effects, look through them. 10950 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10951 if (Ld->isUnordered()) 10952 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10953 } 10954 return false; 10955 } 10956 10957 bool SDNode::hasPredecessor(const SDNode *N) const { 10958 SmallPtrSet<const SDNode *, 32> Visited; 10959 SmallVector<const SDNode *, 16> Worklist; 10960 Worklist.push_back(this); 10961 return hasPredecessorHelper(N, Visited, Worklist); 10962 } 10963 10964 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10965 this->Flags.intersectWith(Flags); 10966 } 10967 10968 SDValue 10969 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10970 ArrayRef<ISD::NodeType> CandidateBinOps, 10971 bool AllowPartials) { 10972 // The pattern must end in an extract from index 0. 10973 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10974 !isNullConstant(Extract->getOperand(1))) 10975 return SDValue(); 10976 10977 // Match against one of the candidate binary ops. 10978 SDValue Op = Extract->getOperand(0); 10979 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10980 return Op.getOpcode() == unsigned(BinOp); 10981 })) 10982 return SDValue(); 10983 10984 // Floating-point reductions may require relaxed constraints on the final step 10985 // of the reduction because they may reorder intermediate operations. 10986 unsigned CandidateBinOp = Op.getOpcode(); 10987 if (Op.getValueType().isFloatingPoint()) { 10988 SDNodeFlags Flags = Op->getFlags(); 10989 switch (CandidateBinOp) { 10990 case ISD::FADD: 10991 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10992 return SDValue(); 10993 break; 10994 default: 10995 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10996 } 10997 } 10998 10999 // Matching failed - attempt to see if we did enough stages that a partial 11000 // reduction from a subvector is possible. 11001 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 11002 if (!AllowPartials || !Op) 11003 return SDValue(); 11004 EVT OpVT = Op.getValueType(); 11005 EVT OpSVT = OpVT.getScalarType(); 11006 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 11007 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 11008 return SDValue(); 11009 BinOp = (ISD::NodeType)CandidateBinOp; 11010 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 11011 getVectorIdxConstant(0, SDLoc(Op))); 11012 }; 11013 11014 // At each stage, we're looking for something that looks like: 11015 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 11016 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 11017 // i32 undef, i32 undef, i32 undef, i32 undef> 11018 // %a = binop <8 x i32> %op, %s 11019 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 11020 // we expect something like: 11021 // <4,5,6,7,u,u,u,u> 11022 // <2,3,u,u,u,u,u,u> 11023 // <1,u,u,u,u,u,u,u> 11024 // While a partial reduction match would be: 11025 // <2,3,u,u,u,u,u,u> 11026 // <1,u,u,u,u,u,u,u> 11027 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 11028 SDValue PrevOp; 11029 for (unsigned i = 0; i < Stages; ++i) { 11030 unsigned MaskEnd = (1 << i); 11031 11032 if (Op.getOpcode() != CandidateBinOp) 11033 return PartialReduction(PrevOp, MaskEnd); 11034 11035 SDValue Op0 = Op.getOperand(0); 11036 SDValue Op1 = Op.getOperand(1); 11037 11038 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 11039 if (Shuffle) { 11040 Op = Op1; 11041 } else { 11042 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 11043 Op = Op0; 11044 } 11045 11046 // The first operand of the shuffle should be the same as the other operand 11047 // of the binop. 11048 if (!Shuffle || Shuffle->getOperand(0) != Op) 11049 return PartialReduction(PrevOp, MaskEnd); 11050 11051 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 11052 for (int Index = 0; Index < (int)MaskEnd; ++Index) 11053 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 11054 return PartialReduction(PrevOp, MaskEnd); 11055 11056 PrevOp = Op; 11057 } 11058 11059 // Handle subvector reductions, which tend to appear after the shuffle 11060 // reduction stages. 11061 while (Op.getOpcode() == CandidateBinOp) { 11062 unsigned NumElts = Op.getValueType().getVectorNumElements(); 11063 SDValue Op0 = Op.getOperand(0); 11064 SDValue Op1 = Op.getOperand(1); 11065 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 11066 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 11067 Op0.getOperand(0) != Op1.getOperand(0)) 11068 break; 11069 SDValue Src = Op0.getOperand(0); 11070 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 11071 if (NumSrcElts != (2 * NumElts)) 11072 break; 11073 if (!(Op0.getConstantOperandAPInt(1) == 0 && 11074 Op1.getConstantOperandAPInt(1) == NumElts) && 11075 !(Op1.getConstantOperandAPInt(1) == 0 && 11076 Op0.getConstantOperandAPInt(1) == NumElts)) 11077 break; 11078 Op = Src; 11079 } 11080 11081 BinOp = (ISD::NodeType)CandidateBinOp; 11082 return Op; 11083 } 11084 11085 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 11086 assert(N->getNumValues() == 1 && 11087 "Can't unroll a vector with multiple results!"); 11088 11089 EVT VT = N->getValueType(0); 11090 unsigned NE = VT.getVectorNumElements(); 11091 EVT EltVT = VT.getVectorElementType(); 11092 SDLoc dl(N); 11093 11094 SmallVector<SDValue, 8> Scalars; 11095 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 11096 11097 // If ResNE is 0, fully unroll the vector op. 11098 if (ResNE == 0) 11099 ResNE = NE; 11100 else if (NE > ResNE) 11101 NE = ResNE; 11102 11103 unsigned i; 11104 for (i= 0; i != NE; ++i) { 11105 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 11106 SDValue Operand = N->getOperand(j); 11107 EVT OperandVT = Operand.getValueType(); 11108 if (OperandVT.isVector()) { 11109 // A vector operand; extract a single element. 11110 EVT OperandEltVT = OperandVT.getVectorElementType(); 11111 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 11112 Operand, getVectorIdxConstant(i, dl)); 11113 } else { 11114 // A scalar operand; just use it as is. 11115 Operands[j] = Operand; 11116 } 11117 } 11118 11119 switch (N->getOpcode()) { 11120 default: { 11121 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 11122 N->getFlags())); 11123 break; 11124 } 11125 case ISD::VSELECT: 11126 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 11127 break; 11128 case ISD::SHL: 11129 case ISD::SRA: 11130 case ISD::SRL: 11131 case ISD::ROTL: 11132 case ISD::ROTR: 11133 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 11134 getShiftAmountOperand(Operands[0].getValueType(), 11135 Operands[1]))); 11136 break; 11137 case ISD::SIGN_EXTEND_INREG: { 11138 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 11139 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 11140 Operands[0], 11141 getValueType(ExtVT))); 11142 } 11143 } 11144 } 11145 11146 for (; i < ResNE; ++i) 11147 Scalars.push_back(getUNDEF(EltVT)); 11148 11149 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 11150 return getBuildVector(VecVT, dl, Scalars); 11151 } 11152 11153 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 11154 SDNode *N, unsigned ResNE) { 11155 unsigned Opcode = N->getOpcode(); 11156 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 11157 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 11158 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 11159 "Expected an overflow opcode"); 11160 11161 EVT ResVT = N->getValueType(0); 11162 EVT OvVT = N->getValueType(1); 11163 EVT ResEltVT = ResVT.getVectorElementType(); 11164 EVT OvEltVT = OvVT.getVectorElementType(); 11165 SDLoc dl(N); 11166 11167 // If ResNE is 0, fully unroll the vector op. 11168 unsigned NE = ResVT.getVectorNumElements(); 11169 if (ResNE == 0) 11170 ResNE = NE; 11171 else if (NE > ResNE) 11172 NE = ResNE; 11173 11174 SmallVector<SDValue, 8> LHSScalars; 11175 SmallVector<SDValue, 8> RHSScalars; 11176 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 11177 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 11178 11179 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 11180 SDVTList VTs = getVTList(ResEltVT, SVT); 11181 SmallVector<SDValue, 8> ResScalars; 11182 SmallVector<SDValue, 8> OvScalars; 11183 for (unsigned i = 0; i < NE; ++i) { 11184 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 11185 SDValue Ov = 11186 getSelect(dl, OvEltVT, Res.getValue(1), 11187 getBoolConstant(true, dl, OvEltVT, ResVT), 11188 getConstant(0, dl, OvEltVT)); 11189 11190 ResScalars.push_back(Res); 11191 OvScalars.push_back(Ov); 11192 } 11193 11194 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 11195 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 11196 11197 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 11198 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 11199 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 11200 getBuildVector(NewOvVT, dl, OvScalars)); 11201 } 11202 11203 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 11204 LoadSDNode *Base, 11205 unsigned Bytes, 11206 int Dist) const { 11207 if (LD->isVolatile() || Base->isVolatile()) 11208 return false; 11209 // TODO: probably too restrictive for atomics, revisit 11210 if (!LD->isSimple()) 11211 return false; 11212 if (LD->isIndexed() || Base->isIndexed()) 11213 return false; 11214 if (LD->getChain() != Base->getChain()) 11215 return false; 11216 EVT VT = LD->getValueType(0); 11217 if (VT.getSizeInBits() / 8 != Bytes) 11218 return false; 11219 11220 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 11221 auto LocDecomp = BaseIndexOffset::match(LD, *this); 11222 11223 int64_t Offset = 0; 11224 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 11225 return (Dist * Bytes == Offset); 11226 return false; 11227 } 11228 11229 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 11230 /// if it cannot be inferred. 11231 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 11232 // If this is a GlobalAddress + cst, return the alignment. 11233 const GlobalValue *GV = nullptr; 11234 int64_t GVOffset = 0; 11235 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 11236 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 11237 KnownBits Known(PtrWidth); 11238 llvm::computeKnownBits(GV, Known, getDataLayout()); 11239 unsigned AlignBits = Known.countMinTrailingZeros(); 11240 if (AlignBits) 11241 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11242 } 11243 11244 // If this is a direct reference to a stack slot, use information about the 11245 // stack slot's alignment. 11246 int FrameIdx = INT_MIN; 11247 int64_t FrameOffset = 0; 11248 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11249 FrameIdx = FI->getIndex(); 11250 } else if (isBaseWithConstantOffset(Ptr) && 11251 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11252 // Handle FI+Cst 11253 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11254 FrameOffset = Ptr.getConstantOperandVal(1); 11255 } 11256 11257 if (FrameIdx != INT_MIN) { 11258 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11259 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11260 } 11261 11262 return None; 11263 } 11264 11265 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11266 /// which is split (or expanded) into two not necessarily identical pieces. 11267 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11268 // Currently all types are split in half. 11269 EVT LoVT, HiVT; 11270 if (!VT.isVector()) 11271 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11272 else 11273 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11274 11275 return std::make_pair(LoVT, HiVT); 11276 } 11277 11278 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11279 /// type, dependent on an enveloping VT that has been split into two identical 11280 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11281 std::pair<EVT, EVT> 11282 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11283 bool *HiIsEmpty) const { 11284 EVT EltTp = VT.getVectorElementType(); 11285 // Examples: 11286 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11287 // custom VL=9 with enveloping VL=8/8 yields 8/1 11288 // custom VL=10 with enveloping VL=8/8 yields 8/2 11289 // etc. 11290 ElementCount VTNumElts = VT.getVectorElementCount(); 11291 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11292 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11293 "Mixing fixed width and scalable vectors when enveloping a type"); 11294 EVT LoVT, HiVT; 11295 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11296 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11297 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11298 *HiIsEmpty = false; 11299 } else { 11300 // Flag that hi type has zero storage size, but return split envelop type 11301 // (this would be easier if vector types with zero elements were allowed). 11302 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11303 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11304 *HiIsEmpty = true; 11305 } 11306 return std::make_pair(LoVT, HiVT); 11307 } 11308 11309 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11310 /// low/high part. 11311 std::pair<SDValue, SDValue> 11312 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11313 const EVT &HiVT) { 11314 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 11315 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 11316 "Splitting vector with an invalid mixture of fixed and scalable " 11317 "vector types"); 11318 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 11319 N.getValueType().getVectorMinNumElements() && 11320 "More vector elements requested than available!"); 11321 SDValue Lo, Hi; 11322 Lo = 11323 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 11324 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 11325 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 11326 // IDX with the runtime scaling factor of the result vector type. For 11327 // fixed-width result vectors, that runtime scaling factor is 1. 11328 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 11329 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 11330 return std::make_pair(Lo, Hi); 11331 } 11332 11333 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 11334 const SDLoc &DL) { 11335 // Split the vector length parameter. 11336 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 11337 EVT VT = N.getValueType(); 11338 assert(VecVT.getVectorElementCount().isKnownEven() && 11339 "Expecting the mask to be an evenly-sized vector"); 11340 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 11341 SDValue HalfNumElts = 11342 VecVT.isFixedLengthVector() 11343 ? getConstant(HalfMinNumElts, DL, VT) 11344 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 11345 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 11346 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 11347 return std::make_pair(Lo, Hi); 11348 } 11349 11350 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 11351 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 11352 EVT VT = N.getValueType(); 11353 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 11354 NextPowerOf2(VT.getVectorNumElements())); 11355 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 11356 getVectorIdxConstant(0, DL)); 11357 } 11358 11359 void SelectionDAG::ExtractVectorElements(SDValue Op, 11360 SmallVectorImpl<SDValue> &Args, 11361 unsigned Start, unsigned Count, 11362 EVT EltVT) { 11363 EVT VT = Op.getValueType(); 11364 if (Count == 0) 11365 Count = VT.getVectorNumElements(); 11366 if (EltVT == EVT()) 11367 EltVT = VT.getVectorElementType(); 11368 SDLoc SL(Op); 11369 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 11370 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 11371 getVectorIdxConstant(i, SL))); 11372 } 11373 } 11374 11375 // getAddressSpace - Return the address space this GlobalAddress belongs to. 11376 unsigned GlobalAddressSDNode::getAddressSpace() const { 11377 return getGlobal()->getType()->getAddressSpace(); 11378 } 11379 11380 Type *ConstantPoolSDNode::getType() const { 11381 if (isMachineConstantPoolEntry()) 11382 return Val.MachineCPVal->getType(); 11383 return Val.ConstVal->getType(); 11384 } 11385 11386 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 11387 unsigned &SplatBitSize, 11388 bool &HasAnyUndefs, 11389 unsigned MinSplatBits, 11390 bool IsBigEndian) const { 11391 EVT VT = getValueType(0); 11392 assert(VT.isVector() && "Expected a vector type"); 11393 unsigned VecWidth = VT.getSizeInBits(); 11394 if (MinSplatBits > VecWidth) 11395 return false; 11396 11397 // FIXME: The widths are based on this node's type, but build vectors can 11398 // truncate their operands. 11399 SplatValue = APInt(VecWidth, 0); 11400 SplatUndef = APInt(VecWidth, 0); 11401 11402 // Get the bits. Bits with undefined values (when the corresponding element 11403 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 11404 // in SplatValue. If any of the values are not constant, give up and return 11405 // false. 11406 unsigned int NumOps = getNumOperands(); 11407 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 11408 unsigned EltWidth = VT.getScalarSizeInBits(); 11409 11410 for (unsigned j = 0; j < NumOps; ++j) { 11411 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 11412 SDValue OpVal = getOperand(i); 11413 unsigned BitPos = j * EltWidth; 11414 11415 if (OpVal.isUndef()) 11416 SplatUndef.setBits(BitPos, BitPos + EltWidth); 11417 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 11418 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 11419 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 11420 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 11421 else 11422 return false; 11423 } 11424 11425 // The build_vector is all constants or undefs. Find the smallest element 11426 // size that splats the vector. 11427 HasAnyUndefs = (SplatUndef != 0); 11428 11429 // FIXME: This does not work for vectors with elements less than 8 bits. 11430 while (VecWidth > 8) { 11431 unsigned HalfSize = VecWidth / 2; 11432 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 11433 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 11434 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 11435 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 11436 11437 // If the two halves do not match (ignoring undef bits), stop here. 11438 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 11439 MinSplatBits > HalfSize) 11440 break; 11441 11442 SplatValue = HighValue | LowValue; 11443 SplatUndef = HighUndef & LowUndef; 11444 11445 VecWidth = HalfSize; 11446 } 11447 11448 SplatBitSize = VecWidth; 11449 return true; 11450 } 11451 11452 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 11453 BitVector *UndefElements) const { 11454 unsigned NumOps = getNumOperands(); 11455 if (UndefElements) { 11456 UndefElements->clear(); 11457 UndefElements->resize(NumOps); 11458 } 11459 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11460 if (!DemandedElts) 11461 return SDValue(); 11462 SDValue Splatted; 11463 for (unsigned i = 0; i != NumOps; ++i) { 11464 if (!DemandedElts[i]) 11465 continue; 11466 SDValue Op = getOperand(i); 11467 if (Op.isUndef()) { 11468 if (UndefElements) 11469 (*UndefElements)[i] = true; 11470 } else if (!Splatted) { 11471 Splatted = Op; 11472 } else if (Splatted != Op) { 11473 return SDValue(); 11474 } 11475 } 11476 11477 if (!Splatted) { 11478 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 11479 assert(getOperand(FirstDemandedIdx).isUndef() && 11480 "Can only have a splat without a constant for all undefs."); 11481 return getOperand(FirstDemandedIdx); 11482 } 11483 11484 return Splatted; 11485 } 11486 11487 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 11488 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11489 return getSplatValue(DemandedElts, UndefElements); 11490 } 11491 11492 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 11493 SmallVectorImpl<SDValue> &Sequence, 11494 BitVector *UndefElements) const { 11495 unsigned NumOps = getNumOperands(); 11496 Sequence.clear(); 11497 if (UndefElements) { 11498 UndefElements->clear(); 11499 UndefElements->resize(NumOps); 11500 } 11501 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11502 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 11503 return false; 11504 11505 // Set the undefs even if we don't find a sequence (like getSplatValue). 11506 if (UndefElements) 11507 for (unsigned I = 0; I != NumOps; ++I) 11508 if (DemandedElts[I] && getOperand(I).isUndef()) 11509 (*UndefElements)[I] = true; 11510 11511 // Iteratively widen the sequence length looking for repetitions. 11512 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 11513 Sequence.append(SeqLen, SDValue()); 11514 for (unsigned I = 0; I != NumOps; ++I) { 11515 if (!DemandedElts[I]) 11516 continue; 11517 SDValue &SeqOp = Sequence[I % SeqLen]; 11518 SDValue Op = getOperand(I); 11519 if (Op.isUndef()) { 11520 if (!SeqOp) 11521 SeqOp = Op; 11522 continue; 11523 } 11524 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 11525 Sequence.clear(); 11526 break; 11527 } 11528 SeqOp = Op; 11529 } 11530 if (!Sequence.empty()) 11531 return true; 11532 } 11533 11534 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 11535 return false; 11536 } 11537 11538 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 11539 BitVector *UndefElements) const { 11540 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11541 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 11542 } 11543 11544 ConstantSDNode * 11545 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 11546 BitVector *UndefElements) const { 11547 return dyn_cast_or_null<ConstantSDNode>( 11548 getSplatValue(DemandedElts, UndefElements)); 11549 } 11550 11551 ConstantSDNode * 11552 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 11553 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 11554 } 11555 11556 ConstantFPSDNode * 11557 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 11558 BitVector *UndefElements) const { 11559 return dyn_cast_or_null<ConstantFPSDNode>( 11560 getSplatValue(DemandedElts, UndefElements)); 11561 } 11562 11563 ConstantFPSDNode * 11564 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 11565 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 11566 } 11567 11568 int32_t 11569 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 11570 uint32_t BitWidth) const { 11571 if (ConstantFPSDNode *CN = 11572 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 11573 bool IsExact; 11574 APSInt IntVal(BitWidth); 11575 const APFloat &APF = CN->getValueAPF(); 11576 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 11577 APFloat::opOK || 11578 !IsExact) 11579 return -1; 11580 11581 return IntVal.exactLogBase2(); 11582 } 11583 return -1; 11584 } 11585 11586 bool BuildVectorSDNode::getConstantRawBits( 11587 bool IsLittleEndian, unsigned DstEltSizeInBits, 11588 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 11589 // Early-out if this contains anything but Undef/Constant/ConstantFP. 11590 if (!isConstant()) 11591 return false; 11592 11593 unsigned NumSrcOps = getNumOperands(); 11594 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 11595 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11596 "Invalid bitcast scale"); 11597 11598 // Extract raw src bits. 11599 SmallVector<APInt> SrcBitElements(NumSrcOps, 11600 APInt::getNullValue(SrcEltSizeInBits)); 11601 BitVector SrcUndeElements(NumSrcOps, false); 11602 11603 for (unsigned I = 0; I != NumSrcOps; ++I) { 11604 SDValue Op = getOperand(I); 11605 if (Op.isUndef()) { 11606 SrcUndeElements.set(I); 11607 continue; 11608 } 11609 auto *CInt = dyn_cast<ConstantSDNode>(Op); 11610 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 11611 assert((CInt || CFP) && "Unknown constant"); 11612 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits) 11613 : CFP->getValueAPF().bitcastToAPInt(); 11614 } 11615 11616 // Recast to dst width. 11617 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11618 SrcBitElements, UndefElements, SrcUndeElements); 11619 return true; 11620 } 11621 11622 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11623 unsigned DstEltSizeInBits, 11624 SmallVectorImpl<APInt> &DstBitElements, 11625 ArrayRef<APInt> SrcBitElements, 11626 BitVector &DstUndefElements, 11627 const BitVector &SrcUndefElements) { 11628 unsigned NumSrcOps = SrcBitElements.size(); 11629 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11630 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11631 "Invalid bitcast scale"); 11632 assert(NumSrcOps == SrcUndefElements.size() && 11633 "Vector size mismatch"); 11634 11635 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11636 DstUndefElements.clear(); 11637 DstUndefElements.resize(NumDstOps, false); 11638 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11639 11640 // Concatenate src elements constant bits together into dst element. 11641 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11642 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11643 for (unsigned I = 0; I != NumDstOps; ++I) { 11644 DstUndefElements.set(I); 11645 APInt &DstBits = DstBitElements[I]; 11646 for (unsigned J = 0; J != Scale; ++J) { 11647 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11648 if (SrcUndefElements[Idx]) 11649 continue; 11650 DstUndefElements.reset(I); 11651 const APInt &SrcBits = SrcBitElements[Idx]; 11652 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11653 "Illegal constant bitwidths"); 11654 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11655 } 11656 } 11657 return; 11658 } 11659 11660 // Split src element constant bits into dst elements. 11661 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11662 for (unsigned I = 0; I != NumSrcOps; ++I) { 11663 if (SrcUndefElements[I]) { 11664 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11665 continue; 11666 } 11667 const APInt &SrcBits = SrcBitElements[I]; 11668 for (unsigned J = 0; J != Scale; ++J) { 11669 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11670 APInt &DstBits = DstBitElements[Idx]; 11671 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11672 } 11673 } 11674 } 11675 11676 bool BuildVectorSDNode::isConstant() const { 11677 for (const SDValue &Op : op_values()) { 11678 unsigned Opc = Op.getOpcode(); 11679 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11680 return false; 11681 } 11682 return true; 11683 } 11684 11685 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11686 // Find the first non-undef value in the shuffle mask. 11687 unsigned i, e; 11688 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11689 /* search */; 11690 11691 // If all elements are undefined, this shuffle can be considered a splat 11692 // (although it should eventually get simplified away completely). 11693 if (i == e) 11694 return true; 11695 11696 // Make sure all remaining elements are either undef or the same as the first 11697 // non-undef value. 11698 for (int Idx = Mask[i]; i != e; ++i) 11699 if (Mask[i] >= 0 && Mask[i] != Idx) 11700 return false; 11701 return true; 11702 } 11703 11704 // Returns the SDNode if it is a constant integer BuildVector 11705 // or constant integer. 11706 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11707 if (isa<ConstantSDNode>(N)) 11708 return N.getNode(); 11709 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11710 return N.getNode(); 11711 // Treat a GlobalAddress supporting constant offset folding as a 11712 // constant integer. 11713 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11714 if (GA->getOpcode() == ISD::GlobalAddress && 11715 TLI->isOffsetFoldingLegal(GA)) 11716 return GA; 11717 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11718 isa<ConstantSDNode>(N.getOperand(0))) 11719 return N.getNode(); 11720 return nullptr; 11721 } 11722 11723 // Returns the SDNode if it is a constant float BuildVector 11724 // or constant float. 11725 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11726 if (isa<ConstantFPSDNode>(N)) 11727 return N.getNode(); 11728 11729 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11730 return N.getNode(); 11731 11732 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11733 isa<ConstantFPSDNode>(N.getOperand(0))) 11734 return N.getNode(); 11735 11736 return nullptr; 11737 } 11738 11739 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11740 assert(!Node->OperandList && "Node already has operands"); 11741 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11742 "too many operands to fit into SDNode"); 11743 SDUse *Ops = OperandRecycler.allocate( 11744 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11745 11746 bool IsDivergent = false; 11747 for (unsigned I = 0; I != Vals.size(); ++I) { 11748 Ops[I].setUser(Node); 11749 Ops[I].setInitial(Vals[I]); 11750 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11751 IsDivergent |= Ops[I].getNode()->isDivergent(); 11752 } 11753 Node->NumOperands = Vals.size(); 11754 Node->OperandList = Ops; 11755 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11756 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11757 Node->SDNodeBits.IsDivergent = IsDivergent; 11758 } 11759 checkForCycles(Node); 11760 } 11761 11762 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11763 SmallVectorImpl<SDValue> &Vals) { 11764 size_t Limit = SDNode::getMaxNumOperands(); 11765 while (Vals.size() > Limit) { 11766 unsigned SliceIdx = Vals.size() - Limit; 11767 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11768 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11769 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11770 Vals.emplace_back(NewTF); 11771 } 11772 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11773 } 11774 11775 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11776 EVT VT, SDNodeFlags Flags) { 11777 switch (Opcode) { 11778 default: 11779 return SDValue(); 11780 case ISD::ADD: 11781 case ISD::OR: 11782 case ISD::XOR: 11783 case ISD::UMAX: 11784 return getConstant(0, DL, VT); 11785 case ISD::MUL: 11786 return getConstant(1, DL, VT); 11787 case ISD::AND: 11788 case ISD::UMIN: 11789 return getAllOnesConstant(DL, VT); 11790 case ISD::SMAX: 11791 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11792 case ISD::SMIN: 11793 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11794 case ISD::FADD: 11795 return getConstantFP(-0.0, DL, VT); 11796 case ISD::FMUL: 11797 return getConstantFP(1.0, DL, VT); 11798 case ISD::FMINNUM: 11799 case ISD::FMAXNUM: { 11800 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11801 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11802 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11803 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11804 APFloat::getLargest(Semantics); 11805 if (Opcode == ISD::FMAXNUM) 11806 NeutralAF.changeSign(); 11807 11808 return getConstantFP(NeutralAF, DL, VT); 11809 } 11810 } 11811 } 11812 11813 #ifndef NDEBUG 11814 static void checkForCyclesHelper(const SDNode *N, 11815 SmallPtrSetImpl<const SDNode*> &Visited, 11816 SmallPtrSetImpl<const SDNode*> &Checked, 11817 const llvm::SelectionDAG *DAG) { 11818 // If this node has already been checked, don't check it again. 11819 if (Checked.count(N)) 11820 return; 11821 11822 // If a node has already been visited on this depth-first walk, reject it as 11823 // a cycle. 11824 if (!Visited.insert(N).second) { 11825 errs() << "Detected cycle in SelectionDAG\n"; 11826 dbgs() << "Offending node:\n"; 11827 N->dumprFull(DAG); dbgs() << "\n"; 11828 abort(); 11829 } 11830 11831 for (const SDValue &Op : N->op_values()) 11832 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11833 11834 Checked.insert(N); 11835 Visited.erase(N); 11836 } 11837 #endif 11838 11839 void llvm::checkForCycles(const llvm::SDNode *N, 11840 const llvm::SelectionDAG *DAG, 11841 bool force) { 11842 #ifndef NDEBUG 11843 bool check = force; 11844 #ifdef EXPENSIVE_CHECKS 11845 check = true; 11846 #endif // EXPENSIVE_CHECKS 11847 if (check) { 11848 assert(N && "Checking nonexistent SDNode"); 11849 SmallPtrSet<const SDNode*, 32> visited; 11850 SmallPtrSet<const SDNode*, 32> checked; 11851 checkForCyclesHelper(N, visited, checked, DAG); 11852 } 11853 #endif // !NDEBUG 11854 } 11855 11856 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11857 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11858 } 11859