1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements the SelectionDAG class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/SelectionDAG.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/APSInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/FoldingSet.h" 21 #include "llvm/ADT/None.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Triple.h" 26 #include "llvm/ADT/Twine.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/CodeGen/Analysis.h" 30 #include "llvm/CodeGen/FunctionLoweringInfo.h" 31 #include "llvm/CodeGen/ISDOpcodes.h" 32 #include "llvm/CodeGen/MachineBasicBlock.h" 33 #include "llvm/CodeGen/MachineConstantPool.h" 34 #include "llvm/CodeGen/MachineFrameInfo.h" 35 #include "llvm/CodeGen/MachineFunction.h" 36 #include "llvm/CodeGen/MachineMemOperand.h" 37 #include "llvm/CodeGen/RuntimeLibcalls.h" 38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 39 #include "llvm/CodeGen/SelectionDAGNodes.h" 40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 41 #include "llvm/CodeGen/TargetFrameLowering.h" 42 #include "llvm/CodeGen/TargetLowering.h" 43 #include "llvm/CodeGen/TargetRegisterInfo.h" 44 #include "llvm/CodeGen/TargetSubtargetInfo.h" 45 #include "llvm/CodeGen/ValueTypes.h" 46 #include "llvm/IR/Constant.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DebugInfoMetadata.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/IR/GlobalValue.h" 54 #include "llvm/IR/Metadata.h" 55 #include "llvm/IR/Type.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CodeGen.h" 58 #include "llvm/Support/Compiler.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/KnownBits.h" 62 #include "llvm/Support/MachineValueType.h" 63 #include "llvm/Support/ManagedStatic.h" 64 #include "llvm/Support/MathExtras.h" 65 #include "llvm/Support/Mutex.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include "llvm/Target/TargetOptions.h" 69 #include "llvm/Transforms/Utils/SizeOpts.h" 70 #include <algorithm> 71 #include <cassert> 72 #include <cstdint> 73 #include <cstdlib> 74 #include <limits> 75 #include <set> 76 #include <string> 77 #include <utility> 78 #include <vector> 79 80 using namespace llvm; 81 82 /// makeVTList - Return an instance of the SDVTList struct initialized with the 83 /// specified members. 84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 85 SDVTList Res = {VTs, NumVTs}; 86 return Res; 87 } 88 89 // Default null implementations of the callbacks. 90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 93 94 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 95 96 #define DEBUG_TYPE "selectiondag" 97 98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 99 cl::Hidden, cl::init(true), 100 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 101 102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 103 cl::desc("Number limit for gluing ld/st of memcpy."), 104 cl::Hidden, cl::init(0)); 105 106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 107 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 108 } 109 110 //===----------------------------------------------------------------------===// 111 // ConstantFPSDNode Class 112 //===----------------------------------------------------------------------===// 113 114 /// isExactlyValue - We don't rely on operator== working on double values, as 115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 116 /// As such, this method can be used to do an exact bit-for-bit comparison of 117 /// two floating point values. 118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 119 return getValueAPF().bitwiseIsEqual(V); 120 } 121 122 bool ConstantFPSDNode::isValueValidForType(EVT VT, 123 const APFloat& Val) { 124 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 125 126 // convert modifies in place, so make a copy. 127 APFloat Val2 = APFloat(Val); 128 bool losesInfo; 129 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 130 APFloat::rmNearestTiesToEven, 131 &losesInfo); 132 return !losesInfo; 133 } 134 135 //===----------------------------------------------------------------------===// 136 // ISD Namespace 137 //===----------------------------------------------------------------------===// 138 139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 140 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 141 unsigned EltSize = 142 N->getValueType(0).getVectorElementType().getSizeInBits(); 143 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 144 SplatVal = Op0->getAPIntValue().trunc(EltSize); 145 return true; 146 } 147 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 148 SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize); 149 return true; 150 } 151 } 152 153 auto *BV = dyn_cast<BuildVectorSDNode>(N); 154 if (!BV) 155 return false; 156 157 APInt SplatUndef; 158 unsigned SplatBitSize; 159 bool HasUndefs; 160 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 161 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 162 EltSize) && 163 EltSize == SplatBitSize; 164 } 165 166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 167 // specializations of the more general isConstantSplatVector()? 168 169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 170 // Look through a bit convert. 171 while (N->getOpcode() == ISD::BITCAST) 172 N = N->getOperand(0).getNode(); 173 174 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 175 APInt SplatVal; 176 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 177 } 178 179 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 180 181 unsigned i = 0, e = N->getNumOperands(); 182 183 // Skip over all of the undef values. 184 while (i != e && N->getOperand(i).isUndef()) 185 ++i; 186 187 // Do not accept an all-undef vector. 188 if (i == e) return false; 189 190 // Do not accept build_vectors that aren't all constants or which have non-~0 191 // elements. We have to be a bit careful here, as the type of the constant 192 // may not be the same as the type of the vector elements due to type 193 // legalization (the elements are promoted to a legal type for the target and 194 // a vector of a type may be legal when the base element type is not). 195 // We only want to check enough bits to cover the vector elements, because 196 // we care if the resultant vector is all ones, not whether the individual 197 // constants are. 198 SDValue NotZero = N->getOperand(i); 199 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 200 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 201 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 202 return false; 203 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 204 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 205 return false; 206 } else 207 return false; 208 209 // Okay, we have at least one ~0 value, check to see if the rest match or are 210 // undefs. Even with the above element type twiddling, this should be OK, as 211 // the same type legalization should have applied to all the elements. 212 for (++i; i != e; ++i) 213 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 214 return false; 215 return true; 216 } 217 218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 219 // Look through a bit convert. 220 while (N->getOpcode() == ISD::BITCAST) 221 N = N->getOperand(0).getNode(); 222 223 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 224 APInt SplatVal; 225 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 226 } 227 228 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 229 230 bool IsAllUndef = true; 231 for (const SDValue &Op : N->op_values()) { 232 if (Op.isUndef()) 233 continue; 234 IsAllUndef = false; 235 // Do not accept build_vectors that aren't all constants or which have non-0 236 // elements. We have to be a bit careful here, as the type of the constant 237 // may not be the same as the type of the vector elements due to type 238 // legalization (the elements are promoted to a legal type for the target 239 // and a vector of a type may be legal when the base element type is not). 240 // We only want to check enough bits to cover the vector elements, because 241 // we care if the resultant vector is all zeros, not whether the individual 242 // constants are. 243 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 244 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 245 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 246 return false; 247 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 248 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 249 return false; 250 } else 251 return false; 252 } 253 254 // Do not accept an all-undef vector. 255 if (IsAllUndef) 256 return false; 257 return true; 258 } 259 260 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 261 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 262 } 263 264 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 265 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 266 } 267 268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 269 if (N->getOpcode() != ISD::BUILD_VECTOR) 270 return false; 271 272 for (const SDValue &Op : N->op_values()) { 273 if (Op.isUndef()) 274 continue; 275 if (!isa<ConstantSDNode>(Op)) 276 return false; 277 } 278 return true; 279 } 280 281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 282 if (N->getOpcode() != ISD::BUILD_VECTOR) 283 return false; 284 285 for (const SDValue &Op : N->op_values()) { 286 if (Op.isUndef()) 287 continue; 288 if (!isa<ConstantFPSDNode>(Op)) 289 return false; 290 } 291 return true; 292 } 293 294 bool ISD::allOperandsUndef(const SDNode *N) { 295 // Return false if the node has no operands. 296 // This is "logically inconsistent" with the definition of "all" but 297 // is probably the desired behavior. 298 if (N->getNumOperands() == 0) 299 return false; 300 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 301 } 302 303 bool ISD::matchUnaryPredicate(SDValue Op, 304 std::function<bool(ConstantSDNode *)> Match, 305 bool AllowUndefs) { 306 // FIXME: Add support for scalar UNDEF cases? 307 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 308 return Match(Cst); 309 310 // FIXME: Add support for vector UNDEF cases? 311 if (ISD::BUILD_VECTOR != Op.getOpcode() && 312 ISD::SPLAT_VECTOR != Op.getOpcode()) 313 return false; 314 315 EVT SVT = Op.getValueType().getScalarType(); 316 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 317 if (AllowUndefs && Op.getOperand(i).isUndef()) { 318 if (!Match(nullptr)) 319 return false; 320 continue; 321 } 322 323 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 324 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 325 return false; 326 } 327 return true; 328 } 329 330 bool ISD::matchBinaryPredicate( 331 SDValue LHS, SDValue RHS, 332 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 333 bool AllowUndefs, bool AllowTypeMismatch) { 334 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 335 return false; 336 337 // TODO: Add support for scalar UNDEF cases? 338 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 339 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 340 return Match(LHSCst, RHSCst); 341 342 // TODO: Add support for vector UNDEF cases? 343 if (LHS.getOpcode() != RHS.getOpcode() || 344 (LHS.getOpcode() != ISD::BUILD_VECTOR && 345 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 346 return false; 347 348 EVT SVT = LHS.getValueType().getScalarType(); 349 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 350 SDValue LHSOp = LHS.getOperand(i); 351 SDValue RHSOp = RHS.getOperand(i); 352 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 353 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 354 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 355 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 356 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 357 return false; 358 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 359 LHSOp.getValueType() != RHSOp.getValueType())) 360 return false; 361 if (!Match(LHSCst, RHSCst)) 362 return false; 363 } 364 return true; 365 } 366 367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 368 switch (VecReduceOpcode) { 369 default: 370 llvm_unreachable("Expected VECREDUCE opcode"); 371 case ISD::VECREDUCE_FADD: 372 case ISD::VECREDUCE_SEQ_FADD: 373 case ISD::VP_REDUCE_FADD: 374 case ISD::VP_REDUCE_SEQ_FADD: 375 return ISD::FADD; 376 case ISD::VECREDUCE_FMUL: 377 case ISD::VECREDUCE_SEQ_FMUL: 378 case ISD::VP_REDUCE_FMUL: 379 case ISD::VP_REDUCE_SEQ_FMUL: 380 return ISD::FMUL; 381 case ISD::VECREDUCE_ADD: 382 case ISD::VP_REDUCE_ADD: 383 return ISD::ADD; 384 case ISD::VECREDUCE_MUL: 385 case ISD::VP_REDUCE_MUL: 386 return ISD::MUL; 387 case ISD::VECREDUCE_AND: 388 case ISD::VP_REDUCE_AND: 389 return ISD::AND; 390 case ISD::VECREDUCE_OR: 391 case ISD::VP_REDUCE_OR: 392 return ISD::OR; 393 case ISD::VECREDUCE_XOR: 394 case ISD::VP_REDUCE_XOR: 395 return ISD::XOR; 396 case ISD::VECREDUCE_SMAX: 397 case ISD::VP_REDUCE_SMAX: 398 return ISD::SMAX; 399 case ISD::VECREDUCE_SMIN: 400 case ISD::VP_REDUCE_SMIN: 401 return ISD::SMIN; 402 case ISD::VECREDUCE_UMAX: 403 case ISD::VP_REDUCE_UMAX: 404 return ISD::UMAX; 405 case ISD::VECREDUCE_UMIN: 406 case ISD::VP_REDUCE_UMIN: 407 return ISD::UMIN; 408 case ISD::VECREDUCE_FMAX: 409 case ISD::VP_REDUCE_FMAX: 410 return ISD::FMAXNUM; 411 case ISD::VECREDUCE_FMIN: 412 case ISD::VP_REDUCE_FMIN: 413 return ISD::FMINNUM; 414 } 415 } 416 417 bool ISD::isVPOpcode(unsigned Opcode) { 418 switch (Opcode) { 419 default: 420 return false; 421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 422 case ISD::VPSD: \ 423 return true; 424 #include "llvm/IR/VPIntrinsics.def" 425 } 426 } 427 428 bool ISD::isVPBinaryOp(unsigned Opcode) { 429 switch (Opcode) { 430 default: 431 break; 432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 433 #define VP_PROPERTY_BINARYOP return true; 434 #define END_REGISTER_VP_SDNODE(VPSD) break; 435 #include "llvm/IR/VPIntrinsics.def" 436 } 437 return false; 438 } 439 440 bool ISD::isVPReduction(unsigned Opcode) { 441 switch (Opcode) { 442 default: 443 break; 444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 446 #define END_REGISTER_VP_SDNODE(VPSD) break; 447 #include "llvm/IR/VPIntrinsics.def" 448 } 449 return false; 450 } 451 452 /// The operand position of the vector mask. 453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 454 switch (Opcode) { 455 default: 456 return None; 457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 458 case ISD::VPSD: \ 459 return MASKPOS; 460 #include "llvm/IR/VPIntrinsics.def" 461 } 462 } 463 464 /// The operand position of the explicit vector length parameter. 465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 466 switch (Opcode) { 467 default: 468 return None; 469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 470 case ISD::VPSD: \ 471 return EVLPOS; 472 #include "llvm/IR/VPIntrinsics.def" 473 } 474 } 475 476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 477 switch (ExtType) { 478 case ISD::EXTLOAD: 479 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 480 case ISD::SEXTLOAD: 481 return ISD::SIGN_EXTEND; 482 case ISD::ZEXTLOAD: 483 return ISD::ZERO_EXTEND; 484 default: 485 break; 486 } 487 488 llvm_unreachable("Invalid LoadExtType"); 489 } 490 491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 492 // To perform this operation, we just need to swap the L and G bits of the 493 // operation. 494 unsigned OldL = (Operation >> 2) & 1; 495 unsigned OldG = (Operation >> 1) & 1; 496 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 497 (OldL << 1) | // New G bit 498 (OldG << 2)); // New L bit. 499 } 500 501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 502 unsigned Operation = Op; 503 if (isIntegerLike) 504 Operation ^= 7; // Flip L, G, E bits, but not U. 505 else 506 Operation ^= 15; // Flip all of the condition bits. 507 508 if (Operation > ISD::SETTRUE2) 509 Operation &= ~8; // Don't let N and U bits get set. 510 511 return ISD::CondCode(Operation); 512 } 513 514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 515 return getSetCCInverseImpl(Op, Type.isInteger()); 516 } 517 518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 519 bool isIntegerLike) { 520 return getSetCCInverseImpl(Op, isIntegerLike); 521 } 522 523 /// For an integer comparison, return 1 if the comparison is a signed operation 524 /// and 2 if the result is an unsigned comparison. Return zero if the operation 525 /// does not depend on the sign of the input (setne and seteq). 526 static int isSignedOp(ISD::CondCode Opcode) { 527 switch (Opcode) { 528 default: llvm_unreachable("Illegal integer setcc operation!"); 529 case ISD::SETEQ: 530 case ISD::SETNE: return 0; 531 case ISD::SETLT: 532 case ISD::SETLE: 533 case ISD::SETGT: 534 case ISD::SETGE: return 1; 535 case ISD::SETULT: 536 case ISD::SETULE: 537 case ISD::SETUGT: 538 case ISD::SETUGE: return 2; 539 } 540 } 541 542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 543 EVT Type) { 544 bool IsInteger = Type.isInteger(); 545 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 546 // Cannot fold a signed integer setcc with an unsigned integer setcc. 547 return ISD::SETCC_INVALID; 548 549 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 550 551 // If the N and U bits get set, then the resultant comparison DOES suddenly 552 // care about orderedness, and it is true when ordered. 553 if (Op > ISD::SETTRUE2) 554 Op &= ~16; // Clear the U bit if the N bit is set. 555 556 // Canonicalize illegal integer setcc's. 557 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 558 Op = ISD::SETNE; 559 560 return ISD::CondCode(Op); 561 } 562 563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 564 EVT Type) { 565 bool IsInteger = Type.isInteger(); 566 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 567 // Cannot fold a signed setcc with an unsigned setcc. 568 return ISD::SETCC_INVALID; 569 570 // Combine all of the condition bits. 571 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 572 573 // Canonicalize illegal integer setcc's. 574 if (IsInteger) { 575 switch (Result) { 576 default: break; 577 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 578 case ISD::SETOEQ: // SETEQ & SETU[LG]E 579 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 580 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 581 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 582 } 583 } 584 585 return Result; 586 } 587 588 //===----------------------------------------------------------------------===// 589 // SDNode Profile Support 590 //===----------------------------------------------------------------------===// 591 592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 594 ID.AddInteger(OpC); 595 } 596 597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 598 /// solely with their pointer. 599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 600 ID.AddPointer(VTList.VTs); 601 } 602 603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 604 static void AddNodeIDOperands(FoldingSetNodeID &ID, 605 ArrayRef<SDValue> Ops) { 606 for (auto& Op : Ops) { 607 ID.AddPointer(Op.getNode()); 608 ID.AddInteger(Op.getResNo()); 609 } 610 } 611 612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 613 static void AddNodeIDOperands(FoldingSetNodeID &ID, 614 ArrayRef<SDUse> Ops) { 615 for (auto& Op : Ops) { 616 ID.AddPointer(Op.getNode()); 617 ID.AddInteger(Op.getResNo()); 618 } 619 } 620 621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 622 SDVTList VTList, ArrayRef<SDValue> OpList) { 623 AddNodeIDOpcode(ID, OpC); 624 AddNodeIDValueTypes(ID, VTList); 625 AddNodeIDOperands(ID, OpList); 626 } 627 628 /// If this is an SDNode with special info, add this info to the NodeID data. 629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 630 switch (N->getOpcode()) { 631 case ISD::TargetExternalSymbol: 632 case ISD::ExternalSymbol: 633 case ISD::MCSymbol: 634 llvm_unreachable("Should only be used on nodes with operands"); 635 default: break; // Normal nodes don't need extra info. 636 case ISD::TargetConstant: 637 case ISD::Constant: { 638 const ConstantSDNode *C = cast<ConstantSDNode>(N); 639 ID.AddPointer(C->getConstantIntValue()); 640 ID.AddBoolean(C->isOpaque()); 641 break; 642 } 643 case ISD::TargetConstantFP: 644 case ISD::ConstantFP: 645 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 646 break; 647 case ISD::TargetGlobalAddress: 648 case ISD::GlobalAddress: 649 case ISD::TargetGlobalTLSAddress: 650 case ISD::GlobalTLSAddress: { 651 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 652 ID.AddPointer(GA->getGlobal()); 653 ID.AddInteger(GA->getOffset()); 654 ID.AddInteger(GA->getTargetFlags()); 655 break; 656 } 657 case ISD::BasicBlock: 658 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 659 break; 660 case ISD::Register: 661 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 662 break; 663 case ISD::RegisterMask: 664 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 665 break; 666 case ISD::SRCVALUE: 667 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 668 break; 669 case ISD::FrameIndex: 670 case ISD::TargetFrameIndex: 671 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 672 break; 673 case ISD::LIFETIME_START: 674 case ISD::LIFETIME_END: 675 if (cast<LifetimeSDNode>(N)->hasOffset()) { 676 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 677 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 678 } 679 break; 680 case ISD::PSEUDO_PROBE: 681 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 682 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 683 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 684 break; 685 case ISD::JumpTable: 686 case ISD::TargetJumpTable: 687 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 688 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 689 break; 690 case ISD::ConstantPool: 691 case ISD::TargetConstantPool: { 692 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 693 ID.AddInteger(CP->getAlign().value()); 694 ID.AddInteger(CP->getOffset()); 695 if (CP->isMachineConstantPoolEntry()) 696 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 697 else 698 ID.AddPointer(CP->getConstVal()); 699 ID.AddInteger(CP->getTargetFlags()); 700 break; 701 } 702 case ISD::TargetIndex: { 703 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 704 ID.AddInteger(TI->getIndex()); 705 ID.AddInteger(TI->getOffset()); 706 ID.AddInteger(TI->getTargetFlags()); 707 break; 708 } 709 case ISD::LOAD: { 710 const LoadSDNode *LD = cast<LoadSDNode>(N); 711 ID.AddInteger(LD->getMemoryVT().getRawBits()); 712 ID.AddInteger(LD->getRawSubclassData()); 713 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 714 ID.AddInteger(LD->getMemOperand()->getFlags()); 715 break; 716 } 717 case ISD::STORE: { 718 const StoreSDNode *ST = cast<StoreSDNode>(N); 719 ID.AddInteger(ST->getMemoryVT().getRawBits()); 720 ID.AddInteger(ST->getRawSubclassData()); 721 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 722 ID.AddInteger(ST->getMemOperand()->getFlags()); 723 break; 724 } 725 case ISD::VP_LOAD: { 726 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 727 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 728 ID.AddInteger(ELD->getRawSubclassData()); 729 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 730 ID.AddInteger(ELD->getMemOperand()->getFlags()); 731 break; 732 } 733 case ISD::VP_STORE: { 734 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 735 ID.AddInteger(EST->getMemoryVT().getRawBits()); 736 ID.AddInteger(EST->getRawSubclassData()); 737 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 738 ID.AddInteger(EST->getMemOperand()->getFlags()); 739 break; 740 } 741 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: { 742 const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N); 743 ID.AddInteger(SLD->getMemoryVT().getRawBits()); 744 ID.AddInteger(SLD->getRawSubclassData()); 745 ID.AddInteger(SLD->getPointerInfo().getAddrSpace()); 746 break; 747 } 748 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: { 749 const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N); 750 ID.AddInteger(SST->getMemoryVT().getRawBits()); 751 ID.AddInteger(SST->getRawSubclassData()); 752 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 753 break; 754 } 755 case ISD::VP_GATHER: { 756 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 757 ID.AddInteger(EG->getMemoryVT().getRawBits()); 758 ID.AddInteger(EG->getRawSubclassData()); 759 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 760 ID.AddInteger(EG->getMemOperand()->getFlags()); 761 break; 762 } 763 case ISD::VP_SCATTER: { 764 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 765 ID.AddInteger(ES->getMemoryVT().getRawBits()); 766 ID.AddInteger(ES->getRawSubclassData()); 767 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 768 ID.AddInteger(ES->getMemOperand()->getFlags()); 769 break; 770 } 771 case ISD::MLOAD: { 772 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 773 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 774 ID.AddInteger(MLD->getRawSubclassData()); 775 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 776 ID.AddInteger(MLD->getMemOperand()->getFlags()); 777 break; 778 } 779 case ISD::MSTORE: { 780 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 781 ID.AddInteger(MST->getMemoryVT().getRawBits()); 782 ID.AddInteger(MST->getRawSubclassData()); 783 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 784 ID.AddInteger(MST->getMemOperand()->getFlags()); 785 break; 786 } 787 case ISD::MGATHER: { 788 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 789 ID.AddInteger(MG->getMemoryVT().getRawBits()); 790 ID.AddInteger(MG->getRawSubclassData()); 791 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 792 ID.AddInteger(MG->getMemOperand()->getFlags()); 793 break; 794 } 795 case ISD::MSCATTER: { 796 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 797 ID.AddInteger(MS->getMemoryVT().getRawBits()); 798 ID.AddInteger(MS->getRawSubclassData()); 799 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 800 ID.AddInteger(MS->getMemOperand()->getFlags()); 801 break; 802 } 803 case ISD::ATOMIC_CMP_SWAP: 804 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 805 case ISD::ATOMIC_SWAP: 806 case ISD::ATOMIC_LOAD_ADD: 807 case ISD::ATOMIC_LOAD_SUB: 808 case ISD::ATOMIC_LOAD_AND: 809 case ISD::ATOMIC_LOAD_CLR: 810 case ISD::ATOMIC_LOAD_OR: 811 case ISD::ATOMIC_LOAD_XOR: 812 case ISD::ATOMIC_LOAD_NAND: 813 case ISD::ATOMIC_LOAD_MIN: 814 case ISD::ATOMIC_LOAD_MAX: 815 case ISD::ATOMIC_LOAD_UMIN: 816 case ISD::ATOMIC_LOAD_UMAX: 817 case ISD::ATOMIC_LOAD: 818 case ISD::ATOMIC_STORE: { 819 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 820 ID.AddInteger(AT->getMemoryVT().getRawBits()); 821 ID.AddInteger(AT->getRawSubclassData()); 822 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 823 ID.AddInteger(AT->getMemOperand()->getFlags()); 824 break; 825 } 826 case ISD::PREFETCH: { 827 const MemSDNode *PF = cast<MemSDNode>(N); 828 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 829 ID.AddInteger(PF->getMemOperand()->getFlags()); 830 break; 831 } 832 case ISD::VECTOR_SHUFFLE: { 833 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 834 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 835 i != e; ++i) 836 ID.AddInteger(SVN->getMaskElt(i)); 837 break; 838 } 839 case ISD::TargetBlockAddress: 840 case ISD::BlockAddress: { 841 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 842 ID.AddPointer(BA->getBlockAddress()); 843 ID.AddInteger(BA->getOffset()); 844 ID.AddInteger(BA->getTargetFlags()); 845 break; 846 } 847 case ISD::AssertAlign: 848 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value()); 849 break; 850 } // end switch (N->getOpcode()) 851 852 // Target specific memory nodes could also have address spaces and flags 853 // to check. 854 if (N->isTargetMemoryOpcode()) { 855 const MemSDNode *MN = cast<MemSDNode>(N); 856 ID.AddInteger(MN->getPointerInfo().getAddrSpace()); 857 ID.AddInteger(MN->getMemOperand()->getFlags()); 858 } 859 } 860 861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 862 /// data. 863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 864 AddNodeIDOpcode(ID, N->getOpcode()); 865 // Add the return value info. 866 AddNodeIDValueTypes(ID, N->getVTList()); 867 // Add the operand info. 868 AddNodeIDOperands(ID, N->ops()); 869 870 // Handle SDNode leafs with special info. 871 AddNodeIDCustom(ID, N); 872 } 873 874 //===----------------------------------------------------------------------===// 875 // SelectionDAG Class 876 //===----------------------------------------------------------------------===// 877 878 /// doNotCSE - Return true if CSE should not be performed for this node. 879 static bool doNotCSE(SDNode *N) { 880 if (N->getValueType(0) == MVT::Glue) 881 return true; // Never CSE anything that produces a flag. 882 883 switch (N->getOpcode()) { 884 default: break; 885 case ISD::HANDLENODE: 886 case ISD::EH_LABEL: 887 return true; // Never CSE these nodes. 888 } 889 890 // Check that remaining values produced are not flags. 891 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 892 if (N->getValueType(i) == MVT::Glue) 893 return true; // Never CSE anything that produces a flag. 894 895 return false; 896 } 897 898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 899 /// SelectionDAG. 900 void SelectionDAG::RemoveDeadNodes() { 901 // Create a dummy node (which is not added to allnodes), that adds a reference 902 // to the root node, preventing it from being deleted. 903 HandleSDNode Dummy(getRoot()); 904 905 SmallVector<SDNode*, 128> DeadNodes; 906 907 // Add all obviously-dead nodes to the DeadNodes worklist. 908 for (SDNode &Node : allnodes()) 909 if (Node.use_empty()) 910 DeadNodes.push_back(&Node); 911 912 RemoveDeadNodes(DeadNodes); 913 914 // If the root changed (e.g. it was a dead load, update the root). 915 setRoot(Dummy.getValue()); 916 } 917 918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 919 /// given list, and any nodes that become unreachable as a result. 920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 921 922 // Process the worklist, deleting the nodes and adding their uses to the 923 // worklist. 924 while (!DeadNodes.empty()) { 925 SDNode *N = DeadNodes.pop_back_val(); 926 // Skip to next node if we've already managed to delete the node. This could 927 // happen if replacing a node causes a node previously added to the node to 928 // be deleted. 929 if (N->getOpcode() == ISD::DELETED_NODE) 930 continue; 931 932 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 933 DUL->NodeDeleted(N, nullptr); 934 935 // Take the node out of the appropriate CSE map. 936 RemoveNodeFromCSEMaps(N); 937 938 // Next, brutally remove the operand list. This is safe to do, as there are 939 // no cycles in the graph. 940 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 941 SDUse &Use = *I++; 942 SDNode *Operand = Use.getNode(); 943 Use.set(SDValue()); 944 945 // Now that we removed this operand, see if there are no uses of it left. 946 if (Operand->use_empty()) 947 DeadNodes.push_back(Operand); 948 } 949 950 DeallocateNode(N); 951 } 952 } 953 954 void SelectionDAG::RemoveDeadNode(SDNode *N){ 955 SmallVector<SDNode*, 16> DeadNodes(1, N); 956 957 // Create a dummy node that adds a reference to the root node, preventing 958 // it from being deleted. (This matters if the root is an operand of the 959 // dead node.) 960 HandleSDNode Dummy(getRoot()); 961 962 RemoveDeadNodes(DeadNodes); 963 } 964 965 void SelectionDAG::DeleteNode(SDNode *N) { 966 // First take this out of the appropriate CSE map. 967 RemoveNodeFromCSEMaps(N); 968 969 // Finally, remove uses due to operands of this node, remove from the 970 // AllNodes list, and delete the node. 971 DeleteNodeNotInCSEMaps(N); 972 } 973 974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 975 assert(N->getIterator() != AllNodes.begin() && 976 "Cannot delete the entry node!"); 977 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 978 979 // Drop all of the operands and decrement used node's use counts. 980 N->DropOperands(); 981 982 DeallocateNode(N); 983 } 984 985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 986 assert(!(V->isVariadic() && isParameter)); 987 if (isParameter) 988 ByvalParmDbgValues.push_back(V); 989 else 990 DbgValues.push_back(V); 991 for (const SDNode *Node : V->getSDNodes()) 992 if (Node) 993 DbgValMap[Node].push_back(V); 994 } 995 996 void SDDbgInfo::erase(const SDNode *Node) { 997 DbgValMapType::iterator I = DbgValMap.find(Node); 998 if (I == DbgValMap.end()) 999 return; 1000 for (auto &Val: I->second) 1001 Val->setIsInvalidated(); 1002 DbgValMap.erase(I); 1003 } 1004 1005 void SelectionDAG::DeallocateNode(SDNode *N) { 1006 // If we have operands, deallocate them. 1007 removeOperands(N); 1008 1009 NodeAllocator.Deallocate(AllNodes.remove(N)); 1010 1011 // Set the opcode to DELETED_NODE to help catch bugs when node 1012 // memory is reallocated. 1013 // FIXME: There are places in SDag that have grown a dependency on the opcode 1014 // value in the released node. 1015 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 1016 N->NodeType = ISD::DELETED_NODE; 1017 1018 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 1019 // them and forget about that node. 1020 DbgInfo->erase(N); 1021 } 1022 1023 #ifndef NDEBUG 1024 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 1025 static void VerifySDNode(SDNode *N) { 1026 switch (N->getOpcode()) { 1027 default: 1028 break; 1029 case ISD::BUILD_PAIR: { 1030 EVT VT = N->getValueType(0); 1031 assert(N->getNumValues() == 1 && "Too many results!"); 1032 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1033 "Wrong return type!"); 1034 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1035 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1036 "Mismatched operand types!"); 1037 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1038 "Wrong operand type!"); 1039 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1040 "Wrong return type size"); 1041 break; 1042 } 1043 case ISD::BUILD_VECTOR: { 1044 assert(N->getNumValues() == 1 && "Too many results!"); 1045 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1046 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1047 "Wrong number of operands!"); 1048 EVT EltVT = N->getValueType(0).getVectorElementType(); 1049 for (const SDUse &Op : N->ops()) { 1050 assert((Op.getValueType() == EltVT || 1051 (EltVT.isInteger() && Op.getValueType().isInteger() && 1052 EltVT.bitsLE(Op.getValueType()))) && 1053 "Wrong operand type!"); 1054 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1055 "Operands must all have the same type"); 1056 } 1057 break; 1058 } 1059 } 1060 } 1061 #endif // NDEBUG 1062 1063 /// Insert a newly allocated node into the DAG. 1064 /// 1065 /// Handles insertion into the all nodes list and CSE map, as well as 1066 /// verification and other common operations when a new node is allocated. 1067 void SelectionDAG::InsertNode(SDNode *N) { 1068 AllNodes.push_back(N); 1069 #ifndef NDEBUG 1070 N->PersistentId = NextPersistentId++; 1071 VerifySDNode(N); 1072 #endif 1073 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1074 DUL->NodeInserted(N); 1075 } 1076 1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1078 /// correspond to it. This is useful when we're about to delete or repurpose 1079 /// the node. We don't want future request for structurally identical nodes 1080 /// to return N anymore. 1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1082 bool Erased = false; 1083 switch (N->getOpcode()) { 1084 case ISD::HANDLENODE: return false; // noop. 1085 case ISD::CONDCODE: 1086 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1087 "Cond code doesn't exist!"); 1088 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1089 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1090 break; 1091 case ISD::ExternalSymbol: 1092 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1093 break; 1094 case ISD::TargetExternalSymbol: { 1095 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1096 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1097 ESN->getSymbol(), ESN->getTargetFlags())); 1098 break; 1099 } 1100 case ISD::MCSymbol: { 1101 auto *MCSN = cast<MCSymbolSDNode>(N); 1102 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1103 break; 1104 } 1105 case ISD::VALUETYPE: { 1106 EVT VT = cast<VTSDNode>(N)->getVT(); 1107 if (VT.isExtended()) { 1108 Erased = ExtendedValueTypeNodes.erase(VT); 1109 } else { 1110 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1111 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1112 } 1113 break; 1114 } 1115 default: 1116 // Remove it from the CSE Map. 1117 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1118 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1119 Erased = CSEMap.RemoveNode(N); 1120 break; 1121 } 1122 #ifndef NDEBUG 1123 // Verify that the node was actually in one of the CSE maps, unless it has a 1124 // flag result (which cannot be CSE'd) or is one of the special cases that are 1125 // not subject to CSE. 1126 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1127 !N->isMachineOpcode() && !doNotCSE(N)) { 1128 N->dump(this); 1129 dbgs() << "\n"; 1130 llvm_unreachable("Node is not in map!"); 1131 } 1132 #endif 1133 return Erased; 1134 } 1135 1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1138 /// node already exists, in which case transfer all its users to the existing 1139 /// node. This transfer can potentially trigger recursive merging. 1140 void 1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1142 // For node types that aren't CSE'd, just act as if no identical node 1143 // already exists. 1144 if (!doNotCSE(N)) { 1145 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1146 if (Existing != N) { 1147 // If there was already an existing matching node, use ReplaceAllUsesWith 1148 // to replace the dead one with the existing one. This can cause 1149 // recursive merging of other unrelated nodes down the line. 1150 ReplaceAllUsesWith(N, Existing); 1151 1152 // N is now dead. Inform the listeners and delete it. 1153 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1154 DUL->NodeDeleted(N, Existing); 1155 DeleteNodeNotInCSEMaps(N); 1156 return; 1157 } 1158 } 1159 1160 // If the node doesn't already exist, we updated it. Inform listeners. 1161 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1162 DUL->NodeUpdated(N); 1163 } 1164 1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1166 /// were replaced with those specified. If this node is never memoized, 1167 /// return null, otherwise return a pointer to the slot it would take. If a 1168 /// node already exists with these operands, the slot will be non-null. 1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1170 void *&InsertPos) { 1171 if (doNotCSE(N)) 1172 return nullptr; 1173 1174 SDValue Ops[] = { Op }; 1175 FoldingSetNodeID ID; 1176 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1177 AddNodeIDCustom(ID, N); 1178 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1179 if (Node) 1180 Node->intersectFlagsWith(N->getFlags()); 1181 return Node; 1182 } 1183 1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1185 /// were replaced with those specified. If this node is never memoized, 1186 /// return null, otherwise return a pointer to the slot it would take. If a 1187 /// node already exists with these operands, the slot will be non-null. 1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1189 SDValue Op1, SDValue Op2, 1190 void *&InsertPos) { 1191 if (doNotCSE(N)) 1192 return nullptr; 1193 1194 SDValue Ops[] = { Op1, Op2 }; 1195 FoldingSetNodeID ID; 1196 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1197 AddNodeIDCustom(ID, N); 1198 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1199 if (Node) 1200 Node->intersectFlagsWith(N->getFlags()); 1201 return Node; 1202 } 1203 1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1205 /// were replaced with those specified. If this node is never memoized, 1206 /// return null, otherwise return a pointer to the slot it would take. If a 1207 /// node already exists with these operands, the slot will be non-null. 1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1209 void *&InsertPos) { 1210 if (doNotCSE(N)) 1211 return nullptr; 1212 1213 FoldingSetNodeID ID; 1214 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1215 AddNodeIDCustom(ID, N); 1216 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1217 if (Node) 1218 Node->intersectFlagsWith(N->getFlags()); 1219 return Node; 1220 } 1221 1222 Align SelectionDAG::getEVTAlign(EVT VT) const { 1223 Type *Ty = VT == MVT::iPTR ? 1224 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1225 VT.getTypeForEVT(*getContext()); 1226 1227 return getDataLayout().getABITypeAlign(Ty); 1228 } 1229 1230 // EntryNode could meaningfully have debug info if we can find it... 1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1232 : TM(tm), OptLevel(OL), 1233 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1234 Root(getEntryNode()) { 1235 InsertNode(&EntryNode); 1236 DbgInfo = new SDDbgInfo(); 1237 } 1238 1239 void SelectionDAG::init(MachineFunction &NewMF, 1240 OptimizationRemarkEmitter &NewORE, 1241 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1242 LegacyDivergenceAnalysis * Divergence, 1243 ProfileSummaryInfo *PSIin, 1244 BlockFrequencyInfo *BFIin) { 1245 MF = &NewMF; 1246 SDAGISelPass = PassPtr; 1247 ORE = &NewORE; 1248 TLI = getSubtarget().getTargetLowering(); 1249 TSI = getSubtarget().getSelectionDAGInfo(); 1250 LibInfo = LibraryInfo; 1251 Context = &MF->getFunction().getContext(); 1252 DA = Divergence; 1253 PSI = PSIin; 1254 BFI = BFIin; 1255 } 1256 1257 SelectionDAG::~SelectionDAG() { 1258 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1259 allnodes_clear(); 1260 OperandRecycler.clear(OperandAllocator); 1261 delete DbgInfo; 1262 } 1263 1264 bool SelectionDAG::shouldOptForSize() const { 1265 return MF->getFunction().hasOptSize() || 1266 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1267 } 1268 1269 void SelectionDAG::allnodes_clear() { 1270 assert(&*AllNodes.begin() == &EntryNode); 1271 AllNodes.remove(AllNodes.begin()); 1272 while (!AllNodes.empty()) 1273 DeallocateNode(&AllNodes.front()); 1274 #ifndef NDEBUG 1275 NextPersistentId = 0; 1276 #endif 1277 } 1278 1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1280 void *&InsertPos) { 1281 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1282 if (N) { 1283 switch (N->getOpcode()) { 1284 default: break; 1285 case ISD::Constant: 1286 case ISD::ConstantFP: 1287 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1288 "debug location. Use another overload."); 1289 } 1290 } 1291 return N; 1292 } 1293 1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1295 const SDLoc &DL, void *&InsertPos) { 1296 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1297 if (N) { 1298 switch (N->getOpcode()) { 1299 case ISD::Constant: 1300 case ISD::ConstantFP: 1301 // Erase debug location from the node if the node is used at several 1302 // different places. Do not propagate one location to all uses as it 1303 // will cause a worse single stepping debugging experience. 1304 if (N->getDebugLoc() != DL.getDebugLoc()) 1305 N->setDebugLoc(DebugLoc()); 1306 break; 1307 default: 1308 // When the node's point of use is located earlier in the instruction 1309 // sequence than its prior point of use, update its debug info to the 1310 // earlier location. 1311 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1312 N->setDebugLoc(DL.getDebugLoc()); 1313 break; 1314 } 1315 } 1316 return N; 1317 } 1318 1319 void SelectionDAG::clear() { 1320 allnodes_clear(); 1321 OperandRecycler.clear(OperandAllocator); 1322 OperandAllocator.Reset(); 1323 CSEMap.clear(); 1324 1325 ExtendedValueTypeNodes.clear(); 1326 ExternalSymbols.clear(); 1327 TargetExternalSymbols.clear(); 1328 MCSymbols.clear(); 1329 SDCallSiteDbgInfo.clear(); 1330 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1331 static_cast<CondCodeSDNode*>(nullptr)); 1332 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1333 static_cast<SDNode*>(nullptr)); 1334 1335 EntryNode.UseList = nullptr; 1336 InsertNode(&EntryNode); 1337 Root = getEntryNode(); 1338 DbgInfo->clear(); 1339 } 1340 1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1342 return VT.bitsGT(Op.getValueType()) 1343 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1344 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1345 } 1346 1347 std::pair<SDValue, SDValue> 1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1349 const SDLoc &DL, EVT VT) { 1350 assert(!VT.bitsEq(Op.getValueType()) && 1351 "Strict no-op FP extend/round not allowed."); 1352 SDValue Res = 1353 VT.bitsGT(Op.getValueType()) 1354 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1355 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1356 {Chain, Op, getIntPtrConstant(0, DL)}); 1357 1358 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1359 } 1360 1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1362 return VT.bitsGT(Op.getValueType()) ? 1363 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1364 getNode(ISD::TRUNCATE, DL, VT, Op); 1365 } 1366 1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1368 return VT.bitsGT(Op.getValueType()) ? 1369 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1370 getNode(ISD::TRUNCATE, DL, VT, Op); 1371 } 1372 1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1374 return VT.bitsGT(Op.getValueType()) ? 1375 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1376 getNode(ISD::TRUNCATE, DL, VT, Op); 1377 } 1378 1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1380 EVT OpVT) { 1381 if (VT.bitsLE(Op.getValueType())) 1382 return getNode(ISD::TRUNCATE, SL, VT, Op); 1383 1384 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1385 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1386 } 1387 1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1389 EVT OpVT = Op.getValueType(); 1390 assert(VT.isInteger() && OpVT.isInteger() && 1391 "Cannot getZeroExtendInReg FP types"); 1392 assert(VT.isVector() == OpVT.isVector() && 1393 "getZeroExtendInReg type should be vector iff the operand " 1394 "type is vector!"); 1395 assert((!VT.isVector() || 1396 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1397 "Vector element counts must match in getZeroExtendInReg"); 1398 assert(VT.bitsLE(OpVT) && "Not extending!"); 1399 if (OpVT == VT) 1400 return Op; 1401 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1402 VT.getScalarSizeInBits()); 1403 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1404 } 1405 1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1407 // Only unsigned pointer semantics are supported right now. In the future this 1408 // might delegate to TLI to check pointer signedness. 1409 return getZExtOrTrunc(Op, DL, VT); 1410 } 1411 1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1413 // Only unsigned pointer semantics are supported right now. In the future this 1414 // might delegate to TLI to check pointer signedness. 1415 return getZeroExtendInReg(Op, DL, VT); 1416 } 1417 1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1420 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1421 } 1422 1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1424 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1425 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1426 } 1427 1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val, 1429 SDValue Mask, SDValue EVL, EVT VT) { 1430 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1431 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL); 1432 } 1433 1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1435 EVT OpVT) { 1436 if (!V) 1437 return getConstant(0, DL, VT); 1438 1439 switch (TLI->getBooleanContents(OpVT)) { 1440 case TargetLowering::ZeroOrOneBooleanContent: 1441 case TargetLowering::UndefinedBooleanContent: 1442 return getConstant(1, DL, VT); 1443 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1444 return getAllOnesConstant(DL, VT); 1445 } 1446 llvm_unreachable("Unexpected boolean content enum!"); 1447 } 1448 1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1450 bool isT, bool isO) { 1451 EVT EltVT = VT.getScalarType(); 1452 assert((EltVT.getSizeInBits() >= 64 || 1453 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1454 "getConstant with a uint64_t value that doesn't fit in the type!"); 1455 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1456 } 1457 1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1459 bool isT, bool isO) { 1460 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1461 } 1462 1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1464 EVT VT, bool isT, bool isO) { 1465 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1466 1467 EVT EltVT = VT.getScalarType(); 1468 const ConstantInt *Elt = &Val; 1469 1470 // In some cases the vector type is legal but the element type is illegal and 1471 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1472 // inserted value (the type does not need to match the vector element type). 1473 // Any extra bits introduced will be truncated away. 1474 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1475 TargetLowering::TypePromoteInteger) { 1476 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1477 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1478 Elt = ConstantInt::get(*getContext(), NewVal); 1479 } 1480 // In other cases the element type is illegal and needs to be expanded, for 1481 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1482 // the value into n parts and use a vector type with n-times the elements. 1483 // Then bitcast to the type requested. 1484 // Legalizing constants too early makes the DAGCombiner's job harder so we 1485 // only legalize if the DAG tells us we must produce legal types. 1486 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1487 TLI->getTypeAction(*getContext(), EltVT) == 1488 TargetLowering::TypeExpandInteger) { 1489 const APInt &NewVal = Elt->getValue(); 1490 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1491 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1492 1493 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1494 if (VT.isScalableVector()) { 1495 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1496 "Can only handle an even split!"); 1497 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1498 1499 SmallVector<SDValue, 2> ScalarParts; 1500 for (unsigned i = 0; i != Parts; ++i) 1501 ScalarParts.push_back(getConstant( 1502 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1503 ViaEltVT, isT, isO)); 1504 1505 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1506 } 1507 1508 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1509 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1510 1511 // Check the temporary vector is the correct size. If this fails then 1512 // getTypeToTransformTo() probably returned a type whose size (in bits) 1513 // isn't a power-of-2 factor of the requested type size. 1514 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1515 1516 SmallVector<SDValue, 2> EltParts; 1517 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1518 EltParts.push_back(getConstant( 1519 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1520 ViaEltVT, isT, isO)); 1521 1522 // EltParts is currently in little endian order. If we actually want 1523 // big-endian order then reverse it now. 1524 if (getDataLayout().isBigEndian()) 1525 std::reverse(EltParts.begin(), EltParts.end()); 1526 1527 // The elements must be reversed when the element order is different 1528 // to the endianness of the elements (because the BITCAST is itself a 1529 // vector shuffle in this situation). However, we do not need any code to 1530 // perform this reversal because getConstant() is producing a vector 1531 // splat. 1532 // This situation occurs in MIPS MSA. 1533 1534 SmallVector<SDValue, 8> Ops; 1535 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1536 llvm::append_range(Ops, EltParts); 1537 1538 SDValue V = 1539 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1540 return V; 1541 } 1542 1543 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1544 "APInt size does not match type size!"); 1545 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1546 FoldingSetNodeID ID; 1547 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1548 ID.AddPointer(Elt); 1549 ID.AddBoolean(isO); 1550 void *IP = nullptr; 1551 SDNode *N = nullptr; 1552 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1553 if (!VT.isVector()) 1554 return SDValue(N, 0); 1555 1556 if (!N) { 1557 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1558 CSEMap.InsertNode(N, IP); 1559 InsertNode(N); 1560 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1561 } 1562 1563 SDValue Result(N, 0); 1564 if (VT.isScalableVector()) 1565 Result = getSplatVector(VT, DL, Result); 1566 else if (VT.isVector()) 1567 Result = getSplatBuildVector(VT, DL, Result); 1568 1569 return Result; 1570 } 1571 1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1573 bool isTarget) { 1574 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1575 } 1576 1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1578 const SDLoc &DL, bool LegalTypes) { 1579 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1580 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1581 return getConstant(Val, DL, ShiftVT); 1582 } 1583 1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1585 bool isTarget) { 1586 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1587 } 1588 1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1590 bool isTarget) { 1591 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1592 } 1593 1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1595 EVT VT, bool isTarget) { 1596 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1597 1598 EVT EltVT = VT.getScalarType(); 1599 1600 // Do the map lookup using the actual bit pattern for the floating point 1601 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1602 // we don't have issues with SNANs. 1603 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1604 FoldingSetNodeID ID; 1605 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1606 ID.AddPointer(&V); 1607 void *IP = nullptr; 1608 SDNode *N = nullptr; 1609 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1610 if (!VT.isVector()) 1611 return SDValue(N, 0); 1612 1613 if (!N) { 1614 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1615 CSEMap.InsertNode(N, IP); 1616 InsertNode(N); 1617 } 1618 1619 SDValue Result(N, 0); 1620 if (VT.isScalableVector()) 1621 Result = getSplatVector(VT, DL, Result); 1622 else if (VT.isVector()) 1623 Result = getSplatBuildVector(VT, DL, Result); 1624 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1625 return Result; 1626 } 1627 1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1629 bool isTarget) { 1630 EVT EltVT = VT.getScalarType(); 1631 if (EltVT == MVT::f32) 1632 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1633 if (EltVT == MVT::f64) 1634 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1635 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1636 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1637 bool Ignored; 1638 APFloat APF = APFloat(Val); 1639 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1640 &Ignored); 1641 return getConstantFP(APF, DL, VT, isTarget); 1642 } 1643 llvm_unreachable("Unsupported type in getConstantFP"); 1644 } 1645 1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1647 EVT VT, int64_t Offset, bool isTargetGA, 1648 unsigned TargetFlags) { 1649 assert((TargetFlags == 0 || isTargetGA) && 1650 "Cannot set target flags on target-independent globals"); 1651 1652 // Truncate (with sign-extension) the offset value to the pointer size. 1653 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1654 if (BitWidth < 64) 1655 Offset = SignExtend64(Offset, BitWidth); 1656 1657 unsigned Opc; 1658 if (GV->isThreadLocal()) 1659 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1660 else 1661 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1662 1663 FoldingSetNodeID ID; 1664 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1665 ID.AddPointer(GV); 1666 ID.AddInteger(Offset); 1667 ID.AddInteger(TargetFlags); 1668 void *IP = nullptr; 1669 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1670 return SDValue(E, 0); 1671 1672 auto *N = newSDNode<GlobalAddressSDNode>( 1673 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1674 CSEMap.InsertNode(N, IP); 1675 InsertNode(N); 1676 return SDValue(N, 0); 1677 } 1678 1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1680 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1681 FoldingSetNodeID ID; 1682 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1683 ID.AddInteger(FI); 1684 void *IP = nullptr; 1685 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1686 return SDValue(E, 0); 1687 1688 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1689 CSEMap.InsertNode(N, IP); 1690 InsertNode(N); 1691 return SDValue(N, 0); 1692 } 1693 1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1695 unsigned TargetFlags) { 1696 assert((TargetFlags == 0 || isTarget) && 1697 "Cannot set target flags on target-independent jump tables"); 1698 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1699 FoldingSetNodeID ID; 1700 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1701 ID.AddInteger(JTI); 1702 ID.AddInteger(TargetFlags); 1703 void *IP = nullptr; 1704 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1705 return SDValue(E, 0); 1706 1707 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1708 CSEMap.InsertNode(N, IP); 1709 InsertNode(N); 1710 return SDValue(N, 0); 1711 } 1712 1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1714 MaybeAlign Alignment, int Offset, 1715 bool isTarget, unsigned TargetFlags) { 1716 assert((TargetFlags == 0 || isTarget) && 1717 "Cannot set target flags on target-independent globals"); 1718 if (!Alignment) 1719 Alignment = shouldOptForSize() 1720 ? getDataLayout().getABITypeAlign(C->getType()) 1721 : getDataLayout().getPrefTypeAlign(C->getType()); 1722 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1723 FoldingSetNodeID ID; 1724 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1725 ID.AddInteger(Alignment->value()); 1726 ID.AddInteger(Offset); 1727 ID.AddPointer(C); 1728 ID.AddInteger(TargetFlags); 1729 void *IP = nullptr; 1730 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1731 return SDValue(E, 0); 1732 1733 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1734 TargetFlags); 1735 CSEMap.InsertNode(N, IP); 1736 InsertNode(N); 1737 SDValue V = SDValue(N, 0); 1738 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1739 return V; 1740 } 1741 1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1743 MaybeAlign Alignment, int Offset, 1744 bool isTarget, unsigned TargetFlags) { 1745 assert((TargetFlags == 0 || isTarget) && 1746 "Cannot set target flags on target-independent globals"); 1747 if (!Alignment) 1748 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1749 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1750 FoldingSetNodeID ID; 1751 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1752 ID.AddInteger(Alignment->value()); 1753 ID.AddInteger(Offset); 1754 C->addSelectionDAGCSEId(ID); 1755 ID.AddInteger(TargetFlags); 1756 void *IP = nullptr; 1757 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1758 return SDValue(E, 0); 1759 1760 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1761 TargetFlags); 1762 CSEMap.InsertNode(N, IP); 1763 InsertNode(N); 1764 return SDValue(N, 0); 1765 } 1766 1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1768 unsigned TargetFlags) { 1769 FoldingSetNodeID ID; 1770 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1771 ID.AddInteger(Index); 1772 ID.AddInteger(Offset); 1773 ID.AddInteger(TargetFlags); 1774 void *IP = nullptr; 1775 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1776 return SDValue(E, 0); 1777 1778 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1779 CSEMap.InsertNode(N, IP); 1780 InsertNode(N); 1781 return SDValue(N, 0); 1782 } 1783 1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1785 FoldingSetNodeID ID; 1786 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1787 ID.AddPointer(MBB); 1788 void *IP = nullptr; 1789 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1790 return SDValue(E, 0); 1791 1792 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1793 CSEMap.InsertNode(N, IP); 1794 InsertNode(N); 1795 return SDValue(N, 0); 1796 } 1797 1798 SDValue SelectionDAG::getValueType(EVT VT) { 1799 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1800 ValueTypeNodes.size()) 1801 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1802 1803 SDNode *&N = VT.isExtended() ? 1804 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1805 1806 if (N) return SDValue(N, 0); 1807 N = newSDNode<VTSDNode>(VT); 1808 InsertNode(N); 1809 return SDValue(N, 0); 1810 } 1811 1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1813 SDNode *&N = ExternalSymbols[Sym]; 1814 if (N) return SDValue(N, 0); 1815 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1816 InsertNode(N); 1817 return SDValue(N, 0); 1818 } 1819 1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1821 SDNode *&N = MCSymbols[Sym]; 1822 if (N) 1823 return SDValue(N, 0); 1824 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1825 InsertNode(N); 1826 return SDValue(N, 0); 1827 } 1828 1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1830 unsigned TargetFlags) { 1831 SDNode *&N = 1832 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1833 if (N) return SDValue(N, 0); 1834 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1835 InsertNode(N); 1836 return SDValue(N, 0); 1837 } 1838 1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1840 if ((unsigned)Cond >= CondCodeNodes.size()) 1841 CondCodeNodes.resize(Cond+1); 1842 1843 if (!CondCodeNodes[Cond]) { 1844 auto *N = newSDNode<CondCodeSDNode>(Cond); 1845 CondCodeNodes[Cond] = N; 1846 InsertNode(N); 1847 } 1848 1849 return SDValue(CondCodeNodes[Cond], 0); 1850 } 1851 1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1853 APInt One(ResVT.getScalarSizeInBits(), 1); 1854 return getStepVector(DL, ResVT, One); 1855 } 1856 1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1858 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1859 if (ResVT.isScalableVector()) 1860 return getNode( 1861 ISD::STEP_VECTOR, DL, ResVT, 1862 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1863 1864 SmallVector<SDValue, 16> OpsStepConstants; 1865 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1866 OpsStepConstants.push_back( 1867 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1868 return getBuildVector(ResVT, DL, OpsStepConstants); 1869 } 1870 1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1874 std::swap(N1, N2); 1875 ShuffleVectorSDNode::commuteMask(M); 1876 } 1877 1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1879 SDValue N2, ArrayRef<int> Mask) { 1880 assert(VT.getVectorNumElements() == Mask.size() && 1881 "Must have the same number of vector elements as mask elements!"); 1882 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1883 "Invalid VECTOR_SHUFFLE"); 1884 1885 // Canonicalize shuffle undef, undef -> undef 1886 if (N1.isUndef() && N2.isUndef()) 1887 return getUNDEF(VT); 1888 1889 // Validate that all indices in Mask are within the range of the elements 1890 // input to the shuffle. 1891 int NElts = Mask.size(); 1892 assert(llvm::all_of(Mask, 1893 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1894 "Index out of range"); 1895 1896 // Copy the mask so we can do any needed cleanup. 1897 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1898 1899 // Canonicalize shuffle v, v -> v, undef 1900 if (N1 == N2) { 1901 N2 = getUNDEF(VT); 1902 for (int i = 0; i != NElts; ++i) 1903 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1904 } 1905 1906 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1907 if (N1.isUndef()) 1908 commuteShuffle(N1, N2, MaskVec); 1909 1910 if (TLI->hasVectorBlend()) { 1911 // If shuffling a splat, try to blend the splat instead. We do this here so 1912 // that even when this arises during lowering we don't have to re-handle it. 1913 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1914 BitVector UndefElements; 1915 SDValue Splat = BV->getSplatValue(&UndefElements); 1916 if (!Splat) 1917 return; 1918 1919 for (int i = 0; i < NElts; ++i) { 1920 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1921 continue; 1922 1923 // If this input comes from undef, mark it as such. 1924 if (UndefElements[MaskVec[i] - Offset]) { 1925 MaskVec[i] = -1; 1926 continue; 1927 } 1928 1929 // If we can blend a non-undef lane, use that instead. 1930 if (!UndefElements[i]) 1931 MaskVec[i] = i + Offset; 1932 } 1933 }; 1934 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1935 BlendSplat(N1BV, 0); 1936 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1937 BlendSplat(N2BV, NElts); 1938 } 1939 1940 // Canonicalize all index into lhs, -> shuffle lhs, undef 1941 // Canonicalize all index into rhs, -> shuffle rhs, undef 1942 bool AllLHS = true, AllRHS = true; 1943 bool N2Undef = N2.isUndef(); 1944 for (int i = 0; i != NElts; ++i) { 1945 if (MaskVec[i] >= NElts) { 1946 if (N2Undef) 1947 MaskVec[i] = -1; 1948 else 1949 AllLHS = false; 1950 } else if (MaskVec[i] >= 0) { 1951 AllRHS = false; 1952 } 1953 } 1954 if (AllLHS && AllRHS) 1955 return getUNDEF(VT); 1956 if (AllLHS && !N2Undef) 1957 N2 = getUNDEF(VT); 1958 if (AllRHS) { 1959 N1 = getUNDEF(VT); 1960 commuteShuffle(N1, N2, MaskVec); 1961 } 1962 // Reset our undef status after accounting for the mask. 1963 N2Undef = N2.isUndef(); 1964 // Re-check whether both sides ended up undef. 1965 if (N1.isUndef() && N2Undef) 1966 return getUNDEF(VT); 1967 1968 // If Identity shuffle return that node. 1969 bool Identity = true, AllSame = true; 1970 for (int i = 0; i != NElts; ++i) { 1971 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1972 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1973 } 1974 if (Identity && NElts) 1975 return N1; 1976 1977 // Shuffling a constant splat doesn't change the result. 1978 if (N2Undef) { 1979 SDValue V = N1; 1980 1981 // Look through any bitcasts. We check that these don't change the number 1982 // (and size) of elements and just changes their types. 1983 while (V.getOpcode() == ISD::BITCAST) 1984 V = V->getOperand(0); 1985 1986 // A splat should always show up as a build vector node. 1987 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1988 BitVector UndefElements; 1989 SDValue Splat = BV->getSplatValue(&UndefElements); 1990 // If this is a splat of an undef, shuffling it is also undef. 1991 if (Splat && Splat.isUndef()) 1992 return getUNDEF(VT); 1993 1994 bool SameNumElts = 1995 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1996 1997 // We only have a splat which can skip shuffles if there is a splatted 1998 // value and no undef lanes rearranged by the shuffle. 1999 if (Splat && UndefElements.none()) { 2000 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 2001 // number of elements match or the value splatted is a zero constant. 2002 if (SameNumElts) 2003 return N1; 2004 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 2005 if (C->isZero()) 2006 return N1; 2007 } 2008 2009 // If the shuffle itself creates a splat, build the vector directly. 2010 if (AllSame && SameNumElts) { 2011 EVT BuildVT = BV->getValueType(0); 2012 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2013 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2014 2015 // We may have jumped through bitcasts, so the type of the 2016 // BUILD_VECTOR may not match the type of the shuffle. 2017 if (BuildVT != VT) 2018 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2019 return NewBV; 2020 } 2021 } 2022 } 2023 2024 FoldingSetNodeID ID; 2025 SDValue Ops[2] = { N1, N2 }; 2026 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2027 for (int i = 0; i != NElts; ++i) 2028 ID.AddInteger(MaskVec[i]); 2029 2030 void* IP = nullptr; 2031 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2032 return SDValue(E, 0); 2033 2034 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2035 // SDNode doesn't have access to it. This memory will be "leaked" when 2036 // the node is deallocated, but recovered when the NodeAllocator is released. 2037 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2038 llvm::copy(MaskVec, MaskAlloc); 2039 2040 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2041 dl.getDebugLoc(), MaskAlloc); 2042 createOperands(N, Ops); 2043 2044 CSEMap.InsertNode(N, IP); 2045 InsertNode(N); 2046 SDValue V = SDValue(N, 0); 2047 NewSDValueDbgMsg(V, "Creating new node: ", this); 2048 return V; 2049 } 2050 2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2052 EVT VT = SV.getValueType(0); 2053 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2054 ShuffleVectorSDNode::commuteMask(MaskVec); 2055 2056 SDValue Op0 = SV.getOperand(0); 2057 SDValue Op1 = SV.getOperand(1); 2058 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2059 } 2060 2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2062 FoldingSetNodeID ID; 2063 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2064 ID.AddInteger(RegNo); 2065 void *IP = nullptr; 2066 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2067 return SDValue(E, 0); 2068 2069 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2070 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2071 CSEMap.InsertNode(N, IP); 2072 InsertNode(N); 2073 return SDValue(N, 0); 2074 } 2075 2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2077 FoldingSetNodeID ID; 2078 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2079 ID.AddPointer(RegMask); 2080 void *IP = nullptr; 2081 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2082 return SDValue(E, 0); 2083 2084 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2085 CSEMap.InsertNode(N, IP); 2086 InsertNode(N); 2087 return SDValue(N, 0); 2088 } 2089 2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2091 MCSymbol *Label) { 2092 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2093 } 2094 2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2096 SDValue Root, MCSymbol *Label) { 2097 FoldingSetNodeID ID; 2098 SDValue Ops[] = { Root }; 2099 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2100 ID.AddPointer(Label); 2101 void *IP = nullptr; 2102 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2103 return SDValue(E, 0); 2104 2105 auto *N = 2106 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2107 createOperands(N, Ops); 2108 2109 CSEMap.InsertNode(N, IP); 2110 InsertNode(N); 2111 return SDValue(N, 0); 2112 } 2113 2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2115 int64_t Offset, bool isTarget, 2116 unsigned TargetFlags) { 2117 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2118 2119 FoldingSetNodeID ID; 2120 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2121 ID.AddPointer(BA); 2122 ID.AddInteger(Offset); 2123 ID.AddInteger(TargetFlags); 2124 void *IP = nullptr; 2125 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2126 return SDValue(E, 0); 2127 2128 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2129 CSEMap.InsertNode(N, IP); 2130 InsertNode(N); 2131 return SDValue(N, 0); 2132 } 2133 2134 SDValue SelectionDAG::getSrcValue(const Value *V) { 2135 FoldingSetNodeID ID; 2136 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2137 ID.AddPointer(V); 2138 2139 void *IP = nullptr; 2140 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2141 return SDValue(E, 0); 2142 2143 auto *N = newSDNode<SrcValueSDNode>(V); 2144 CSEMap.InsertNode(N, IP); 2145 InsertNode(N); 2146 return SDValue(N, 0); 2147 } 2148 2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2150 FoldingSetNodeID ID; 2151 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2152 ID.AddPointer(MD); 2153 2154 void *IP = nullptr; 2155 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2156 return SDValue(E, 0); 2157 2158 auto *N = newSDNode<MDNodeSDNode>(MD); 2159 CSEMap.InsertNode(N, IP); 2160 InsertNode(N); 2161 return SDValue(N, 0); 2162 } 2163 2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2165 if (VT == V.getValueType()) 2166 return V; 2167 2168 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2169 } 2170 2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2172 unsigned SrcAS, unsigned DestAS) { 2173 SDValue Ops[] = {Ptr}; 2174 FoldingSetNodeID ID; 2175 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2176 ID.AddInteger(SrcAS); 2177 ID.AddInteger(DestAS); 2178 2179 void *IP = nullptr; 2180 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2181 return SDValue(E, 0); 2182 2183 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2184 VT, SrcAS, DestAS); 2185 createOperands(N, Ops); 2186 2187 CSEMap.InsertNode(N, IP); 2188 InsertNode(N); 2189 return SDValue(N, 0); 2190 } 2191 2192 SDValue SelectionDAG::getFreeze(SDValue V) { 2193 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2194 } 2195 2196 /// getShiftAmountOperand - Return the specified value casted to 2197 /// the target's desired shift amount type. 2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2199 EVT OpTy = Op.getValueType(); 2200 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2201 if (OpTy == ShTy || OpTy.isVector()) return Op; 2202 2203 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2204 } 2205 2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2207 SDLoc dl(Node); 2208 const TargetLowering &TLI = getTargetLoweringInfo(); 2209 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2210 EVT VT = Node->getValueType(0); 2211 SDValue Tmp1 = Node->getOperand(0); 2212 SDValue Tmp2 = Node->getOperand(1); 2213 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2214 2215 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2216 Tmp2, MachinePointerInfo(V)); 2217 SDValue VAList = VAListLoad; 2218 2219 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2220 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2221 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2222 2223 VAList = 2224 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2225 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2226 } 2227 2228 // Increment the pointer, VAList, to the next vaarg 2229 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2230 getConstant(getDataLayout().getTypeAllocSize( 2231 VT.getTypeForEVT(*getContext())), 2232 dl, VAList.getValueType())); 2233 // Store the incremented VAList to the legalized pointer 2234 Tmp1 = 2235 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2236 // Load the actual argument out of the pointer VAList 2237 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2238 } 2239 2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2241 SDLoc dl(Node); 2242 const TargetLowering &TLI = getTargetLoweringInfo(); 2243 // This defaults to loading a pointer from the input and storing it to the 2244 // output, returning the chain. 2245 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2246 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2247 SDValue Tmp1 = 2248 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2249 Node->getOperand(2), MachinePointerInfo(VS)); 2250 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2251 MachinePointerInfo(VD)); 2252 } 2253 2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2255 const DataLayout &DL = getDataLayout(); 2256 Type *Ty = VT.getTypeForEVT(*getContext()); 2257 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2258 2259 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2260 return RedAlign; 2261 2262 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2263 const Align StackAlign = TFI->getStackAlign(); 2264 2265 // See if we can choose a smaller ABI alignment in cases where it's an 2266 // illegal vector type that will get broken down. 2267 if (RedAlign > StackAlign) { 2268 EVT IntermediateVT; 2269 MVT RegisterVT; 2270 unsigned NumIntermediates; 2271 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2272 NumIntermediates, RegisterVT); 2273 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2274 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2275 if (RedAlign2 < RedAlign) 2276 RedAlign = RedAlign2; 2277 } 2278 2279 return RedAlign; 2280 } 2281 2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2283 MachineFrameInfo &MFI = MF->getFrameInfo(); 2284 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2285 int StackID = 0; 2286 if (Bytes.isScalable()) 2287 StackID = TFI->getStackIDForScalableVectors(); 2288 // The stack id gives an indication of whether the object is scalable or 2289 // not, so it's safe to pass in the minimum size here. 2290 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2291 false, nullptr, StackID); 2292 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2293 } 2294 2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2296 Type *Ty = VT.getTypeForEVT(*getContext()); 2297 Align StackAlign = 2298 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2299 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2300 } 2301 2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2303 TypeSize VT1Size = VT1.getStoreSize(); 2304 TypeSize VT2Size = VT2.getStoreSize(); 2305 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2306 "Don't know how to choose the maximum size when creating a stack " 2307 "temporary"); 2308 TypeSize Bytes = 2309 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2310 2311 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2312 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2313 const DataLayout &DL = getDataLayout(); 2314 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2315 return CreateStackTemporary(Bytes, Align); 2316 } 2317 2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2319 ISD::CondCode Cond, const SDLoc &dl) { 2320 EVT OpVT = N1.getValueType(); 2321 2322 // These setcc operations always fold. 2323 switch (Cond) { 2324 default: break; 2325 case ISD::SETFALSE: 2326 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2327 case ISD::SETTRUE: 2328 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2329 2330 case ISD::SETOEQ: 2331 case ISD::SETOGT: 2332 case ISD::SETOGE: 2333 case ISD::SETOLT: 2334 case ISD::SETOLE: 2335 case ISD::SETONE: 2336 case ISD::SETO: 2337 case ISD::SETUO: 2338 case ISD::SETUEQ: 2339 case ISD::SETUNE: 2340 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2341 break; 2342 } 2343 2344 if (OpVT.isInteger()) { 2345 // For EQ and NE, we can always pick a value for the undef to make the 2346 // predicate pass or fail, so we can return undef. 2347 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2348 // icmp eq/ne X, undef -> undef. 2349 if ((N1.isUndef() || N2.isUndef()) && 2350 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2351 return getUNDEF(VT); 2352 2353 // If both operands are undef, we can return undef for int comparison. 2354 // icmp undef, undef -> undef. 2355 if (N1.isUndef() && N2.isUndef()) 2356 return getUNDEF(VT); 2357 2358 // icmp X, X -> true/false 2359 // icmp X, undef -> true/false because undef could be X. 2360 if (N1 == N2) 2361 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2362 } 2363 2364 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2365 const APInt &C2 = N2C->getAPIntValue(); 2366 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2367 const APInt &C1 = N1C->getAPIntValue(); 2368 2369 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2370 dl, VT, OpVT); 2371 } 2372 } 2373 2374 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2375 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2376 2377 if (N1CFP && N2CFP) { 2378 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2379 switch (Cond) { 2380 default: break; 2381 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2382 return getUNDEF(VT); 2383 LLVM_FALLTHROUGH; 2384 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2385 OpVT); 2386 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2387 return getUNDEF(VT); 2388 LLVM_FALLTHROUGH; 2389 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2390 R==APFloat::cmpLessThan, dl, VT, 2391 OpVT); 2392 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2393 return getUNDEF(VT); 2394 LLVM_FALLTHROUGH; 2395 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2396 OpVT); 2397 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2398 return getUNDEF(VT); 2399 LLVM_FALLTHROUGH; 2400 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2401 VT, OpVT); 2402 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2403 return getUNDEF(VT); 2404 LLVM_FALLTHROUGH; 2405 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2406 R==APFloat::cmpEqual, dl, VT, 2407 OpVT); 2408 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2409 return getUNDEF(VT); 2410 LLVM_FALLTHROUGH; 2411 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2412 R==APFloat::cmpEqual, dl, VT, OpVT); 2413 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2414 OpVT); 2415 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2416 OpVT); 2417 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2418 R==APFloat::cmpEqual, dl, VT, 2419 OpVT); 2420 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2421 OpVT); 2422 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2423 R==APFloat::cmpLessThan, dl, VT, 2424 OpVT); 2425 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2426 R==APFloat::cmpUnordered, dl, VT, 2427 OpVT); 2428 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2429 VT, OpVT); 2430 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2431 OpVT); 2432 } 2433 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2434 // Ensure that the constant occurs on the RHS. 2435 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2436 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2437 return SDValue(); 2438 return getSetCC(dl, VT, N2, N1, SwappedCond); 2439 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2440 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2441 // If an operand is known to be a nan (or undef that could be a nan), we can 2442 // fold it. 2443 // Choosing NaN for the undef will always make unordered comparison succeed 2444 // and ordered comparison fails. 2445 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2446 switch (ISD::getUnorderedFlavor(Cond)) { 2447 default: 2448 llvm_unreachable("Unknown flavor!"); 2449 case 0: // Known false. 2450 return getBoolConstant(false, dl, VT, OpVT); 2451 case 1: // Known true. 2452 return getBoolConstant(true, dl, VT, OpVT); 2453 case 2: // Undefined. 2454 return getUNDEF(VT); 2455 } 2456 } 2457 2458 // Could not fold it. 2459 return SDValue(); 2460 } 2461 2462 /// See if the specified operand can be simplified with the knowledge that only 2463 /// the bits specified by DemandedBits are used. 2464 /// TODO: really we should be making this into the DAG equivalent of 2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2467 EVT VT = V.getValueType(); 2468 2469 if (VT.isScalableVector()) 2470 return SDValue(); 2471 2472 APInt DemandedElts = VT.isVector() 2473 ? APInt::getAllOnes(VT.getVectorNumElements()) 2474 : APInt(1, 1); 2475 return GetDemandedBits(V, DemandedBits, DemandedElts); 2476 } 2477 2478 /// See if the specified operand can be simplified with the knowledge that only 2479 /// the bits specified by DemandedBits are used in the elements specified by 2480 /// DemandedElts. 2481 /// TODO: really we should be making this into the DAG equivalent of 2482 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2483 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2484 const APInt &DemandedElts) { 2485 switch (V.getOpcode()) { 2486 default: 2487 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2488 *this); 2489 case ISD::Constant: { 2490 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2491 APInt NewVal = CVal & DemandedBits; 2492 if (NewVal != CVal) 2493 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2494 break; 2495 } 2496 case ISD::SRL: 2497 // Only look at single-use SRLs. 2498 if (!V.getNode()->hasOneUse()) 2499 break; 2500 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2501 // See if we can recursively simplify the LHS. 2502 unsigned Amt = RHSC->getZExtValue(); 2503 2504 // Watch out for shift count overflow though. 2505 if (Amt >= DemandedBits.getBitWidth()) 2506 break; 2507 APInt SrcDemandedBits = DemandedBits << Amt; 2508 if (SDValue SimplifyLHS = 2509 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2510 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2511 V.getOperand(1)); 2512 } 2513 break; 2514 } 2515 return SDValue(); 2516 } 2517 2518 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2519 /// use this predicate to simplify operations downstream. 2520 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2521 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2522 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2523 } 2524 2525 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2526 /// this predicate to simplify operations downstream. Mask is known to be zero 2527 /// for bits that V cannot have. 2528 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2529 unsigned Depth) const { 2530 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2531 } 2532 2533 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2534 /// DemandedElts. We use this predicate to simplify operations downstream. 2535 /// Mask is known to be zero for bits that V cannot have. 2536 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2537 const APInt &DemandedElts, 2538 unsigned Depth) const { 2539 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2540 } 2541 2542 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2543 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2544 unsigned Depth) const { 2545 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2546 } 2547 2548 /// isSplatValue - Return true if the vector V has the same value 2549 /// across all DemandedElts. For scalable vectors it does not make 2550 /// sense to specify which elements are demanded or undefined, therefore 2551 /// they are simply ignored. 2552 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2553 APInt &UndefElts, unsigned Depth) const { 2554 unsigned Opcode = V.getOpcode(); 2555 EVT VT = V.getValueType(); 2556 assert(VT.isVector() && "Vector type expected"); 2557 2558 if (!VT.isScalableVector() && !DemandedElts) 2559 return false; // No demanded elts, better to assume we don't know anything. 2560 2561 if (Depth >= MaxRecursionDepth) 2562 return false; // Limit search depth. 2563 2564 // Deal with some common cases here that work for both fixed and scalable 2565 // vector types. 2566 switch (Opcode) { 2567 case ISD::SPLAT_VECTOR: 2568 UndefElts = V.getOperand(0).isUndef() 2569 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2570 : APInt(DemandedElts.getBitWidth(), 0); 2571 return true; 2572 case ISD::ADD: 2573 case ISD::SUB: 2574 case ISD::AND: 2575 case ISD::XOR: 2576 case ISD::OR: { 2577 APInt UndefLHS, UndefRHS; 2578 SDValue LHS = V.getOperand(0); 2579 SDValue RHS = V.getOperand(1); 2580 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2581 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2582 UndefElts = UndefLHS | UndefRHS; 2583 return true; 2584 } 2585 return false; 2586 } 2587 case ISD::ABS: 2588 case ISD::TRUNCATE: 2589 case ISD::SIGN_EXTEND: 2590 case ISD::ZERO_EXTEND: 2591 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2592 default: 2593 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2594 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2595 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth); 2596 break; 2597 } 2598 2599 // We don't support other cases than those above for scalable vectors at 2600 // the moment. 2601 if (VT.isScalableVector()) 2602 return false; 2603 2604 unsigned NumElts = VT.getVectorNumElements(); 2605 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2606 UndefElts = APInt::getZero(NumElts); 2607 2608 switch (Opcode) { 2609 case ISD::BUILD_VECTOR: { 2610 SDValue Scl; 2611 for (unsigned i = 0; i != NumElts; ++i) { 2612 SDValue Op = V.getOperand(i); 2613 if (Op.isUndef()) { 2614 UndefElts.setBit(i); 2615 continue; 2616 } 2617 if (!DemandedElts[i]) 2618 continue; 2619 if (Scl && Scl != Op) 2620 return false; 2621 Scl = Op; 2622 } 2623 return true; 2624 } 2625 case ISD::VECTOR_SHUFFLE: { 2626 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2627 APInt DemandedLHS = APInt::getNullValue(NumElts); 2628 APInt DemandedRHS = APInt::getNullValue(NumElts); 2629 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2630 for (int i = 0; i != (int)NumElts; ++i) { 2631 int M = Mask[i]; 2632 if (M < 0) { 2633 UndefElts.setBit(i); 2634 continue; 2635 } 2636 if (!DemandedElts[i]) 2637 continue; 2638 if (M < (int)NumElts) 2639 DemandedLHS.setBit(M); 2640 else 2641 DemandedRHS.setBit(M - NumElts); 2642 } 2643 2644 // If we aren't demanding either op, assume there's no splat. 2645 // If we are demanding both ops, assume there's no splat. 2646 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2647 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2648 return false; 2649 2650 // See if the demanded elts of the source op is a splat or we only demand 2651 // one element, which should always be a splat. 2652 // TODO: Handle source ops splats with undefs. 2653 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2654 APInt SrcUndefs; 2655 return (SrcElts.countPopulation() == 1) || 2656 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2657 (SrcElts & SrcUndefs).isZero()); 2658 }; 2659 if (!DemandedLHS.isZero()) 2660 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2661 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2662 } 2663 case ISD::EXTRACT_SUBVECTOR: { 2664 // Offset the demanded elts by the subvector index. 2665 SDValue Src = V.getOperand(0); 2666 // We don't support scalable vectors at the moment. 2667 if (Src.getValueType().isScalableVector()) 2668 return false; 2669 uint64_t Idx = V.getConstantOperandVal(1); 2670 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2671 APInt UndefSrcElts; 2672 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 2673 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2674 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2675 return true; 2676 } 2677 break; 2678 } 2679 case ISD::ANY_EXTEND_VECTOR_INREG: 2680 case ISD::SIGN_EXTEND_VECTOR_INREG: 2681 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2682 // Widen the demanded elts by the src element count. 2683 SDValue Src = V.getOperand(0); 2684 // We don't support scalable vectors at the moment. 2685 if (Src.getValueType().isScalableVector()) 2686 return false; 2687 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2688 APInt UndefSrcElts; 2689 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 2690 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2691 UndefElts = UndefSrcElts.trunc(NumElts); 2692 return true; 2693 } 2694 break; 2695 } 2696 case ISD::BITCAST: { 2697 SDValue Src = V.getOperand(0); 2698 EVT SrcVT = Src.getValueType(); 2699 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2700 unsigned BitWidth = VT.getScalarSizeInBits(); 2701 2702 // Ignore bitcasts from unsupported types. 2703 // TODO: Add fp support? 2704 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2705 break; 2706 2707 // Bitcast 'small element' vector to 'large element' vector. 2708 if ((BitWidth % SrcBitWidth) == 0) { 2709 // See if each sub element is a splat. 2710 unsigned Scale = BitWidth / SrcBitWidth; 2711 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2712 APInt ScaledDemandedElts = 2713 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2714 for (unsigned I = 0; I != Scale; ++I) { 2715 APInt SubUndefElts; 2716 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2717 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2718 SubDemandedElts &= ScaledDemandedElts; 2719 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2720 return false; 2721 // TODO: Add support for merging sub undef elements. 2722 if (SubDemandedElts.isSubsetOf(SubUndefElts)) 2723 return false; 2724 } 2725 return true; 2726 } 2727 break; 2728 } 2729 } 2730 2731 return false; 2732 } 2733 2734 /// Helper wrapper to main isSplatValue function. 2735 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2736 EVT VT = V.getValueType(); 2737 assert(VT.isVector() && "Vector type expected"); 2738 2739 APInt UndefElts; 2740 APInt DemandedElts; 2741 2742 // For now we don't support this with scalable vectors. 2743 if (!VT.isScalableVector()) 2744 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2745 return isSplatValue(V, DemandedElts, UndefElts) && 2746 (AllowUndefs || !UndefElts); 2747 } 2748 2749 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2750 V = peekThroughExtractSubvectors(V); 2751 2752 EVT VT = V.getValueType(); 2753 unsigned Opcode = V.getOpcode(); 2754 switch (Opcode) { 2755 default: { 2756 APInt UndefElts; 2757 APInt DemandedElts; 2758 2759 if (!VT.isScalableVector()) 2760 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2761 2762 if (isSplatValue(V, DemandedElts, UndefElts)) { 2763 if (VT.isScalableVector()) { 2764 // DemandedElts and UndefElts are ignored for scalable vectors, since 2765 // the only supported cases are SPLAT_VECTOR nodes. 2766 SplatIdx = 0; 2767 } else { 2768 // Handle case where all demanded elements are UNDEF. 2769 if (DemandedElts.isSubsetOf(UndefElts)) { 2770 SplatIdx = 0; 2771 return getUNDEF(VT); 2772 } 2773 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2774 } 2775 return V; 2776 } 2777 break; 2778 } 2779 case ISD::SPLAT_VECTOR: 2780 SplatIdx = 0; 2781 return V; 2782 case ISD::VECTOR_SHUFFLE: { 2783 if (VT.isScalableVector()) 2784 return SDValue(); 2785 2786 // Check if this is a shuffle node doing a splat. 2787 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2788 // getTargetVShiftNode currently struggles without the splat source. 2789 auto *SVN = cast<ShuffleVectorSDNode>(V); 2790 if (!SVN->isSplat()) 2791 break; 2792 int Idx = SVN->getSplatIndex(); 2793 int NumElts = V.getValueType().getVectorNumElements(); 2794 SplatIdx = Idx % NumElts; 2795 return V.getOperand(Idx / NumElts); 2796 } 2797 } 2798 2799 return SDValue(); 2800 } 2801 2802 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2803 int SplatIdx; 2804 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2805 EVT SVT = SrcVector.getValueType().getScalarType(); 2806 EVT LegalSVT = SVT; 2807 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2808 if (!SVT.isInteger()) 2809 return SDValue(); 2810 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2811 if (LegalSVT.bitsLT(SVT)) 2812 return SDValue(); 2813 } 2814 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2815 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2816 } 2817 return SDValue(); 2818 } 2819 2820 const APInt * 2821 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2822 const APInt &DemandedElts) const { 2823 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2824 V.getOpcode() == ISD::SRA) && 2825 "Unknown shift node"); 2826 unsigned BitWidth = V.getScalarValueSizeInBits(); 2827 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2828 // Shifting more than the bitwidth is not valid. 2829 const APInt &ShAmt = SA->getAPIntValue(); 2830 if (ShAmt.ult(BitWidth)) 2831 return &ShAmt; 2832 } 2833 return nullptr; 2834 } 2835 2836 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2837 SDValue V, const APInt &DemandedElts) const { 2838 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2839 V.getOpcode() == ISD::SRA) && 2840 "Unknown shift node"); 2841 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2842 return ValidAmt; 2843 unsigned BitWidth = V.getScalarValueSizeInBits(); 2844 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2845 if (!BV) 2846 return nullptr; 2847 const APInt *MinShAmt = nullptr; 2848 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2849 if (!DemandedElts[i]) 2850 continue; 2851 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2852 if (!SA) 2853 return nullptr; 2854 // Shifting more than the bitwidth is not valid. 2855 const APInt &ShAmt = SA->getAPIntValue(); 2856 if (ShAmt.uge(BitWidth)) 2857 return nullptr; 2858 if (MinShAmt && MinShAmt->ule(ShAmt)) 2859 continue; 2860 MinShAmt = &ShAmt; 2861 } 2862 return MinShAmt; 2863 } 2864 2865 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2866 SDValue V, const APInt &DemandedElts) const { 2867 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2868 V.getOpcode() == ISD::SRA) && 2869 "Unknown shift node"); 2870 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2871 return ValidAmt; 2872 unsigned BitWidth = V.getScalarValueSizeInBits(); 2873 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2874 if (!BV) 2875 return nullptr; 2876 const APInt *MaxShAmt = nullptr; 2877 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2878 if (!DemandedElts[i]) 2879 continue; 2880 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2881 if (!SA) 2882 return nullptr; 2883 // Shifting more than the bitwidth is not valid. 2884 const APInt &ShAmt = SA->getAPIntValue(); 2885 if (ShAmt.uge(BitWidth)) 2886 return nullptr; 2887 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2888 continue; 2889 MaxShAmt = &ShAmt; 2890 } 2891 return MaxShAmt; 2892 } 2893 2894 /// Determine which bits of Op are known to be either zero or one and return 2895 /// them in Known. For vectors, the known bits are those that are shared by 2896 /// every vector element. 2897 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2898 EVT VT = Op.getValueType(); 2899 2900 // TOOD: Until we have a plan for how to represent demanded elements for 2901 // scalable vectors, we can just bail out for now. 2902 if (Op.getValueType().isScalableVector()) { 2903 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2904 return KnownBits(BitWidth); 2905 } 2906 2907 APInt DemandedElts = VT.isVector() 2908 ? APInt::getAllOnes(VT.getVectorNumElements()) 2909 : APInt(1, 1); 2910 return computeKnownBits(Op, DemandedElts, Depth); 2911 } 2912 2913 /// Determine which bits of Op are known to be either zero or one and return 2914 /// them in Known. The DemandedElts argument allows us to only collect the known 2915 /// bits that are shared by the requested vector elements. 2916 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2917 unsigned Depth) const { 2918 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2919 2920 KnownBits Known(BitWidth); // Don't know anything. 2921 2922 // TOOD: Until we have a plan for how to represent demanded elements for 2923 // scalable vectors, we can just bail out for now. 2924 if (Op.getValueType().isScalableVector()) 2925 return Known; 2926 2927 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2928 // We know all of the bits for a constant! 2929 return KnownBits::makeConstant(C->getAPIntValue()); 2930 } 2931 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2932 // We know all of the bits for a constant fp! 2933 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2934 } 2935 2936 if (Depth >= MaxRecursionDepth) 2937 return Known; // Limit search depth. 2938 2939 KnownBits Known2; 2940 unsigned NumElts = DemandedElts.getBitWidth(); 2941 assert((!Op.getValueType().isVector() || 2942 NumElts == Op.getValueType().getVectorNumElements()) && 2943 "Unexpected vector size"); 2944 2945 if (!DemandedElts) 2946 return Known; // No demanded elts, better to assume we don't know anything. 2947 2948 unsigned Opcode = Op.getOpcode(); 2949 switch (Opcode) { 2950 case ISD::BUILD_VECTOR: 2951 // Collect the known bits that are shared by every demanded vector element. 2952 Known.Zero.setAllBits(); Known.One.setAllBits(); 2953 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2954 if (!DemandedElts[i]) 2955 continue; 2956 2957 SDValue SrcOp = Op.getOperand(i); 2958 Known2 = computeKnownBits(SrcOp, Depth + 1); 2959 2960 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2961 if (SrcOp.getValueSizeInBits() != BitWidth) { 2962 assert(SrcOp.getValueSizeInBits() > BitWidth && 2963 "Expected BUILD_VECTOR implicit truncation"); 2964 Known2 = Known2.trunc(BitWidth); 2965 } 2966 2967 // Known bits are the values that are shared by every demanded element. 2968 Known = KnownBits::commonBits(Known, Known2); 2969 2970 // If we don't know any bits, early out. 2971 if (Known.isUnknown()) 2972 break; 2973 } 2974 break; 2975 case ISD::VECTOR_SHUFFLE: { 2976 // Collect the known bits that are shared by every vector element referenced 2977 // by the shuffle. 2978 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2979 Known.Zero.setAllBits(); Known.One.setAllBits(); 2980 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2981 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2982 for (unsigned i = 0; i != NumElts; ++i) { 2983 if (!DemandedElts[i]) 2984 continue; 2985 2986 int M = SVN->getMaskElt(i); 2987 if (M < 0) { 2988 // For UNDEF elements, we don't know anything about the common state of 2989 // the shuffle result. 2990 Known.resetAll(); 2991 DemandedLHS.clearAllBits(); 2992 DemandedRHS.clearAllBits(); 2993 break; 2994 } 2995 2996 if ((unsigned)M < NumElts) 2997 DemandedLHS.setBit((unsigned)M % NumElts); 2998 else 2999 DemandedRHS.setBit((unsigned)M % NumElts); 3000 } 3001 // Known bits are the values that are shared by every demanded element. 3002 if (!!DemandedLHS) { 3003 SDValue LHS = Op.getOperand(0); 3004 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 3005 Known = KnownBits::commonBits(Known, Known2); 3006 } 3007 // If we don't know any bits, early out. 3008 if (Known.isUnknown()) 3009 break; 3010 if (!!DemandedRHS) { 3011 SDValue RHS = Op.getOperand(1); 3012 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3013 Known = KnownBits::commonBits(Known, Known2); 3014 } 3015 break; 3016 } 3017 case ISD::CONCAT_VECTORS: { 3018 // Split DemandedElts and test each of the demanded subvectors. 3019 Known.Zero.setAllBits(); Known.One.setAllBits(); 3020 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3021 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3022 unsigned NumSubVectors = Op.getNumOperands(); 3023 for (unsigned i = 0; i != NumSubVectors; ++i) { 3024 APInt DemandedSub = 3025 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3026 if (!!DemandedSub) { 3027 SDValue Sub = Op.getOperand(i); 3028 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3029 Known = KnownBits::commonBits(Known, Known2); 3030 } 3031 // If we don't know any bits, early out. 3032 if (Known.isUnknown()) 3033 break; 3034 } 3035 break; 3036 } 3037 case ISD::INSERT_SUBVECTOR: { 3038 // Demand any elements from the subvector and the remainder from the src its 3039 // inserted into. 3040 SDValue Src = Op.getOperand(0); 3041 SDValue Sub = Op.getOperand(1); 3042 uint64_t Idx = Op.getConstantOperandVal(2); 3043 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3044 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3045 APInt DemandedSrcElts = DemandedElts; 3046 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3047 3048 Known.One.setAllBits(); 3049 Known.Zero.setAllBits(); 3050 if (!!DemandedSubElts) { 3051 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3052 if (Known.isUnknown()) 3053 break; // early-out. 3054 } 3055 if (!!DemandedSrcElts) { 3056 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3057 Known = KnownBits::commonBits(Known, Known2); 3058 } 3059 break; 3060 } 3061 case ISD::EXTRACT_SUBVECTOR: { 3062 // Offset the demanded elts by the subvector index. 3063 SDValue Src = Op.getOperand(0); 3064 // Bail until we can represent demanded elements for scalable vectors. 3065 if (Src.getValueType().isScalableVector()) 3066 break; 3067 uint64_t Idx = Op.getConstantOperandVal(1); 3068 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3069 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3070 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3071 break; 3072 } 3073 case ISD::SCALAR_TO_VECTOR: { 3074 // We know about scalar_to_vector as much as we know about it source, 3075 // which becomes the first element of otherwise unknown vector. 3076 if (DemandedElts != 1) 3077 break; 3078 3079 SDValue N0 = Op.getOperand(0); 3080 Known = computeKnownBits(N0, Depth + 1); 3081 if (N0.getValueSizeInBits() != BitWidth) 3082 Known = Known.trunc(BitWidth); 3083 3084 break; 3085 } 3086 case ISD::BITCAST: { 3087 SDValue N0 = Op.getOperand(0); 3088 EVT SubVT = N0.getValueType(); 3089 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3090 3091 // Ignore bitcasts from unsupported types. 3092 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3093 break; 3094 3095 // Fast handling of 'identity' bitcasts. 3096 if (BitWidth == SubBitWidth) { 3097 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3098 break; 3099 } 3100 3101 bool IsLE = getDataLayout().isLittleEndian(); 3102 3103 // Bitcast 'small element' vector to 'large element' scalar/vector. 3104 if ((BitWidth % SubBitWidth) == 0) { 3105 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3106 3107 // Collect known bits for the (larger) output by collecting the known 3108 // bits from each set of sub elements and shift these into place. 3109 // We need to separately call computeKnownBits for each set of 3110 // sub elements as the knownbits for each is likely to be different. 3111 unsigned SubScale = BitWidth / SubBitWidth; 3112 APInt SubDemandedElts(NumElts * SubScale, 0); 3113 for (unsigned i = 0; i != NumElts; ++i) 3114 if (DemandedElts[i]) 3115 SubDemandedElts.setBit(i * SubScale); 3116 3117 for (unsigned i = 0; i != SubScale; ++i) { 3118 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3119 Depth + 1); 3120 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3121 Known.insertBits(Known2, SubBitWidth * Shifts); 3122 } 3123 } 3124 3125 // Bitcast 'large element' scalar/vector to 'small element' vector. 3126 if ((SubBitWidth % BitWidth) == 0) { 3127 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3128 3129 // Collect known bits for the (smaller) output by collecting the known 3130 // bits from the overlapping larger input elements and extracting the 3131 // sub sections we actually care about. 3132 unsigned SubScale = SubBitWidth / BitWidth; 3133 APInt SubDemandedElts = 3134 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3135 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3136 3137 Known.Zero.setAllBits(); Known.One.setAllBits(); 3138 for (unsigned i = 0; i != NumElts; ++i) 3139 if (DemandedElts[i]) { 3140 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3141 unsigned Offset = (Shifts % SubScale) * BitWidth; 3142 Known = KnownBits::commonBits(Known, 3143 Known2.extractBits(BitWidth, Offset)); 3144 // If we don't know any bits, early out. 3145 if (Known.isUnknown()) 3146 break; 3147 } 3148 } 3149 break; 3150 } 3151 case ISD::AND: 3152 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3153 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3154 3155 Known &= Known2; 3156 break; 3157 case ISD::OR: 3158 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3159 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3160 3161 Known |= Known2; 3162 break; 3163 case ISD::XOR: 3164 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3165 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3166 3167 Known ^= Known2; 3168 break; 3169 case ISD::MUL: { 3170 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3171 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3172 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3173 // TODO: SelfMultiply can be poison, but not undef. 3174 if (SelfMultiply) 3175 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3176 Op.getOperand(0), DemandedElts, false, Depth + 1); 3177 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3178 break; 3179 } 3180 case ISD::MULHU: { 3181 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3182 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3183 Known = KnownBits::mulhu(Known, Known2); 3184 break; 3185 } 3186 case ISD::MULHS: { 3187 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3188 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3189 Known = KnownBits::mulhs(Known, Known2); 3190 break; 3191 } 3192 case ISD::UMUL_LOHI: { 3193 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3194 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3195 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3196 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3197 if (Op.getResNo() == 0) 3198 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3199 else 3200 Known = KnownBits::mulhu(Known, Known2); 3201 break; 3202 } 3203 case ISD::SMUL_LOHI: { 3204 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3205 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3206 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3207 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3208 if (Op.getResNo() == 0) 3209 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3210 else 3211 Known = KnownBits::mulhs(Known, Known2); 3212 break; 3213 } 3214 case ISD::UDIV: { 3215 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3216 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3217 Known = KnownBits::udiv(Known, Known2); 3218 break; 3219 } 3220 case ISD::AVGCEILU: { 3221 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3222 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3223 Known = Known.zext(BitWidth + 1); 3224 Known2 = Known2.zext(BitWidth + 1); 3225 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3226 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3227 Known = Known.extractBits(BitWidth, 1); 3228 break; 3229 } 3230 case ISD::SELECT: 3231 case ISD::VSELECT: 3232 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3233 // If we don't know any bits, early out. 3234 if (Known.isUnknown()) 3235 break; 3236 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3237 3238 // Only known if known in both the LHS and RHS. 3239 Known = KnownBits::commonBits(Known, Known2); 3240 break; 3241 case ISD::SELECT_CC: 3242 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3243 // If we don't know any bits, early out. 3244 if (Known.isUnknown()) 3245 break; 3246 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3247 3248 // Only known if known in both the LHS and RHS. 3249 Known = KnownBits::commonBits(Known, Known2); 3250 break; 3251 case ISD::SMULO: 3252 case ISD::UMULO: 3253 if (Op.getResNo() != 1) 3254 break; 3255 // The boolean result conforms to getBooleanContents. 3256 // If we know the result of a setcc has the top bits zero, use this info. 3257 // We know that we have an integer-based boolean since these operations 3258 // are only available for integer. 3259 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3260 TargetLowering::ZeroOrOneBooleanContent && 3261 BitWidth > 1) 3262 Known.Zero.setBitsFrom(1); 3263 break; 3264 case ISD::SETCC: 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::SIGN_EXTEND_INREG: { 3334 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3335 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3336 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3337 break; 3338 } 3339 case ISD::CTTZ: 3340 case ISD::CTTZ_ZERO_UNDEF: { 3341 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3342 // If we have a known 1, its position is our upper bound. 3343 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3344 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3345 Known.Zero.setBitsFrom(LowBits); 3346 break; 3347 } 3348 case ISD::CTLZ: 3349 case ISD::CTLZ_ZERO_UNDEF: { 3350 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3351 // If we have a known 1, its position is our upper bound. 3352 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3353 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3354 Known.Zero.setBitsFrom(LowBits); 3355 break; 3356 } 3357 case ISD::CTPOP: { 3358 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3359 // If we know some of the bits are zero, they can't be one. 3360 unsigned PossibleOnes = Known2.countMaxPopulation(); 3361 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3362 break; 3363 } 3364 case ISD::PARITY: { 3365 // Parity returns 0 everywhere but the LSB. 3366 Known.Zero.setBitsFrom(1); 3367 break; 3368 } 3369 case ISD::LOAD: { 3370 LoadSDNode *LD = cast<LoadSDNode>(Op); 3371 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3372 if (ISD::isNON_EXTLoad(LD) && Cst) { 3373 // Determine any common known bits from the loaded constant pool value. 3374 Type *CstTy = Cst->getType(); 3375 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3376 // If its a vector splat, then we can (quickly) reuse the scalar path. 3377 // NOTE: We assume all elements match and none are UNDEF. 3378 if (CstTy->isVectorTy()) { 3379 if (const Constant *Splat = Cst->getSplatValue()) { 3380 Cst = Splat; 3381 CstTy = Cst->getType(); 3382 } 3383 } 3384 // TODO - do we need to handle different bitwidths? 3385 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3386 // Iterate across all vector elements finding common known bits. 3387 Known.One.setAllBits(); 3388 Known.Zero.setAllBits(); 3389 for (unsigned i = 0; i != NumElts; ++i) { 3390 if (!DemandedElts[i]) 3391 continue; 3392 if (Constant *Elt = Cst->getAggregateElement(i)) { 3393 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3394 const APInt &Value = CInt->getValue(); 3395 Known.One &= Value; 3396 Known.Zero &= ~Value; 3397 continue; 3398 } 3399 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3400 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3401 Known.One &= Value; 3402 Known.Zero &= ~Value; 3403 continue; 3404 } 3405 } 3406 Known.One.clearAllBits(); 3407 Known.Zero.clearAllBits(); 3408 break; 3409 } 3410 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3411 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3412 Known = KnownBits::makeConstant(CInt->getValue()); 3413 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3414 Known = 3415 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3416 } 3417 } 3418 } 3419 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3420 // If this is a ZEXTLoad and we are looking at the loaded value. 3421 EVT VT = LD->getMemoryVT(); 3422 unsigned MemBits = VT.getScalarSizeInBits(); 3423 Known.Zero.setBitsFrom(MemBits); 3424 } else if (const MDNode *Ranges = LD->getRanges()) { 3425 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3426 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3427 } 3428 break; 3429 } 3430 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3431 EVT InVT = Op.getOperand(0).getValueType(); 3432 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3433 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3434 Known = Known.zext(BitWidth); 3435 break; 3436 } 3437 case ISD::ZERO_EXTEND: { 3438 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3439 Known = Known.zext(BitWidth); 3440 break; 3441 } 3442 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3443 EVT InVT = Op.getOperand(0).getValueType(); 3444 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3445 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3446 // If the sign bit is known to be zero or one, then sext will extend 3447 // it to the top bits, else it will just zext. 3448 Known = Known.sext(BitWidth); 3449 break; 3450 } 3451 case ISD::SIGN_EXTEND: { 3452 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3453 // If the sign bit is known to be zero or one, then sext will extend 3454 // it to the top bits, else it will just zext. 3455 Known = Known.sext(BitWidth); 3456 break; 3457 } 3458 case ISD::ANY_EXTEND_VECTOR_INREG: { 3459 EVT InVT = Op.getOperand(0).getValueType(); 3460 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3461 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3462 Known = Known.anyext(BitWidth); 3463 break; 3464 } 3465 case ISD::ANY_EXTEND: { 3466 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3467 Known = Known.anyext(BitWidth); 3468 break; 3469 } 3470 case ISD::TRUNCATE: { 3471 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3472 Known = Known.trunc(BitWidth); 3473 break; 3474 } 3475 case ISD::AssertZext: { 3476 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3477 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3478 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3479 Known.Zero |= (~InMask); 3480 Known.One &= (~Known.Zero); 3481 break; 3482 } 3483 case ISD::AssertAlign: { 3484 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3485 assert(LogOfAlign != 0); 3486 3487 // TODO: Should use maximum with source 3488 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3489 // well as clearing one bits. 3490 Known.Zero.setLowBits(LogOfAlign); 3491 Known.One.clearLowBits(LogOfAlign); 3492 break; 3493 } 3494 case ISD::FGETSIGN: 3495 // All bits are zero except the low bit. 3496 Known.Zero.setBitsFrom(1); 3497 break; 3498 case ISD::USUBO: 3499 case ISD::SSUBO: 3500 if (Op.getResNo() == 1) { 3501 // If we know the result of a setcc has the top bits zero, use this info. 3502 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3503 TargetLowering::ZeroOrOneBooleanContent && 3504 BitWidth > 1) 3505 Known.Zero.setBitsFrom(1); 3506 break; 3507 } 3508 LLVM_FALLTHROUGH; 3509 case ISD::SUB: 3510 case ISD::SUBC: { 3511 assert(Op.getResNo() == 0 && 3512 "We only compute knownbits for the difference here."); 3513 3514 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3515 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3516 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3517 Known, Known2); 3518 break; 3519 } 3520 case ISD::UADDO: 3521 case ISD::SADDO: 3522 case ISD::ADDCARRY: 3523 if (Op.getResNo() == 1) { 3524 // If we know the result of a setcc has the top bits zero, use this info. 3525 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3526 TargetLowering::ZeroOrOneBooleanContent && 3527 BitWidth > 1) 3528 Known.Zero.setBitsFrom(1); 3529 break; 3530 } 3531 LLVM_FALLTHROUGH; 3532 case ISD::ADD: 3533 case ISD::ADDC: 3534 case ISD::ADDE: { 3535 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3536 3537 // With ADDE and ADDCARRY, a carry bit may be added in. 3538 KnownBits Carry(1); 3539 if (Opcode == ISD::ADDE) 3540 // Can't track carry from glue, set carry to unknown. 3541 Carry.resetAll(); 3542 else if (Opcode == ISD::ADDCARRY) 3543 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3544 // the trouble (how often will we find a known carry bit). And I haven't 3545 // tested this very much yet, but something like this might work: 3546 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3547 // Carry = Carry.zextOrTrunc(1, false); 3548 Carry.resetAll(); 3549 else 3550 Carry.setAllZero(); 3551 3552 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3553 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3554 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3555 break; 3556 } 3557 case ISD::SREM: { 3558 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3559 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3560 Known = KnownBits::srem(Known, Known2); 3561 break; 3562 } 3563 case ISD::UREM: { 3564 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3565 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3566 Known = KnownBits::urem(Known, Known2); 3567 break; 3568 } 3569 case ISD::EXTRACT_ELEMENT: { 3570 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3571 const unsigned Index = Op.getConstantOperandVal(1); 3572 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3573 3574 // Remove low part of known bits mask 3575 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3576 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3577 3578 // Remove high part of known bit mask 3579 Known = Known.trunc(EltBitWidth); 3580 break; 3581 } 3582 case ISD::EXTRACT_VECTOR_ELT: { 3583 SDValue InVec = Op.getOperand(0); 3584 SDValue EltNo = Op.getOperand(1); 3585 EVT VecVT = InVec.getValueType(); 3586 // computeKnownBits not yet implemented for scalable vectors. 3587 if (VecVT.isScalableVector()) 3588 break; 3589 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3590 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3591 3592 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3593 // anything about the extended bits. 3594 if (BitWidth > EltBitWidth) 3595 Known = Known.trunc(EltBitWidth); 3596 3597 // If we know the element index, just demand that vector element, else for 3598 // an unknown element index, ignore DemandedElts and demand them all. 3599 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3600 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3601 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3602 DemandedSrcElts = 3603 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3604 3605 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3606 if (BitWidth > EltBitWidth) 3607 Known = Known.anyext(BitWidth); 3608 break; 3609 } 3610 case ISD::INSERT_VECTOR_ELT: { 3611 // If we know the element index, split the demand between the 3612 // source vector and the inserted element, otherwise assume we need 3613 // the original demanded vector elements and the value. 3614 SDValue InVec = Op.getOperand(0); 3615 SDValue InVal = Op.getOperand(1); 3616 SDValue EltNo = Op.getOperand(2); 3617 bool DemandedVal = true; 3618 APInt DemandedVecElts = DemandedElts; 3619 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3620 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3621 unsigned EltIdx = CEltNo->getZExtValue(); 3622 DemandedVal = !!DemandedElts[EltIdx]; 3623 DemandedVecElts.clearBit(EltIdx); 3624 } 3625 Known.One.setAllBits(); 3626 Known.Zero.setAllBits(); 3627 if (DemandedVal) { 3628 Known2 = computeKnownBits(InVal, Depth + 1); 3629 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3630 } 3631 if (!!DemandedVecElts) { 3632 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3633 Known = KnownBits::commonBits(Known, Known2); 3634 } 3635 break; 3636 } 3637 case ISD::BITREVERSE: { 3638 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3639 Known = Known2.reverseBits(); 3640 break; 3641 } 3642 case ISD::BSWAP: { 3643 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3644 Known = Known2.byteSwap(); 3645 break; 3646 } 3647 case ISD::ABS: { 3648 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3649 Known = Known2.abs(); 3650 break; 3651 } 3652 case ISD::USUBSAT: { 3653 // The result of usubsat will never be larger than the LHS. 3654 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3655 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3656 break; 3657 } 3658 case ISD::UMIN: { 3659 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3660 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3661 Known = KnownBits::umin(Known, Known2); 3662 break; 3663 } 3664 case ISD::UMAX: { 3665 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3666 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3667 Known = KnownBits::umax(Known, Known2); 3668 break; 3669 } 3670 case ISD::SMIN: 3671 case ISD::SMAX: { 3672 // If we have a clamp pattern, we know that the number of sign bits will be 3673 // the minimum of the clamp min/max range. 3674 bool IsMax = (Opcode == ISD::SMAX); 3675 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3676 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3677 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3678 CstHigh = 3679 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3680 if (CstLow && CstHigh) { 3681 if (!IsMax) 3682 std::swap(CstLow, CstHigh); 3683 3684 const APInt &ValueLow = CstLow->getAPIntValue(); 3685 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3686 if (ValueLow.sle(ValueHigh)) { 3687 unsigned LowSignBits = ValueLow.getNumSignBits(); 3688 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3689 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3690 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3691 Known.One.setHighBits(MinSignBits); 3692 break; 3693 } 3694 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3695 Known.Zero.setHighBits(MinSignBits); 3696 break; 3697 } 3698 } 3699 } 3700 3701 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3702 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3703 if (IsMax) 3704 Known = KnownBits::smax(Known, Known2); 3705 else 3706 Known = KnownBits::smin(Known, Known2); 3707 break; 3708 } 3709 case ISD::FP_TO_UINT_SAT: { 3710 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3711 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3712 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3713 break; 3714 } 3715 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3716 if (Op.getResNo() == 1) { 3717 // The boolean result conforms to getBooleanContents. 3718 // If we know the result of a setcc has the top bits zero, use this info. 3719 // We know that we have an integer-based boolean since these operations 3720 // are only available for integer. 3721 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3722 TargetLowering::ZeroOrOneBooleanContent && 3723 BitWidth > 1) 3724 Known.Zero.setBitsFrom(1); 3725 break; 3726 } 3727 LLVM_FALLTHROUGH; 3728 case ISD::ATOMIC_CMP_SWAP: 3729 case ISD::ATOMIC_SWAP: 3730 case ISD::ATOMIC_LOAD_ADD: 3731 case ISD::ATOMIC_LOAD_SUB: 3732 case ISD::ATOMIC_LOAD_AND: 3733 case ISD::ATOMIC_LOAD_CLR: 3734 case ISD::ATOMIC_LOAD_OR: 3735 case ISD::ATOMIC_LOAD_XOR: 3736 case ISD::ATOMIC_LOAD_NAND: 3737 case ISD::ATOMIC_LOAD_MIN: 3738 case ISD::ATOMIC_LOAD_MAX: 3739 case ISD::ATOMIC_LOAD_UMIN: 3740 case ISD::ATOMIC_LOAD_UMAX: 3741 case ISD::ATOMIC_LOAD: { 3742 unsigned MemBits = 3743 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3744 // If we are looking at the loaded value. 3745 if (Op.getResNo() == 0) { 3746 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3747 Known.Zero.setBitsFrom(MemBits); 3748 } 3749 break; 3750 } 3751 case ISD::FrameIndex: 3752 case ISD::TargetFrameIndex: 3753 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3754 Known, getMachineFunction()); 3755 break; 3756 3757 default: 3758 if (Opcode < ISD::BUILTIN_OP_END) 3759 break; 3760 LLVM_FALLTHROUGH; 3761 case ISD::INTRINSIC_WO_CHAIN: 3762 case ISD::INTRINSIC_W_CHAIN: 3763 case ISD::INTRINSIC_VOID: 3764 // Allow the target to implement this method for its nodes. 3765 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3766 break; 3767 } 3768 3769 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3770 return Known; 3771 } 3772 3773 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3774 SDValue N1) const { 3775 // X + 0 never overflow 3776 if (isNullConstant(N1)) 3777 return OFK_Never; 3778 3779 KnownBits N1Known = computeKnownBits(N1); 3780 if (N1Known.Zero.getBoolValue()) { 3781 KnownBits N0Known = computeKnownBits(N0); 3782 3783 bool overflow; 3784 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3785 if (!overflow) 3786 return OFK_Never; 3787 } 3788 3789 // mulhi + 1 never overflow 3790 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3791 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3792 return OFK_Never; 3793 3794 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3795 KnownBits N0Known = computeKnownBits(N0); 3796 3797 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3798 return OFK_Never; 3799 } 3800 3801 return OFK_Sometime; 3802 } 3803 3804 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3805 EVT OpVT = Val.getValueType(); 3806 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3807 3808 // Is the constant a known power of 2? 3809 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3810 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3811 3812 // A left-shift of a constant one will have exactly one bit set because 3813 // shifting the bit off the end is undefined. 3814 if (Val.getOpcode() == ISD::SHL) { 3815 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3816 if (C && C->getAPIntValue() == 1) 3817 return true; 3818 } 3819 3820 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3821 // one bit set. 3822 if (Val.getOpcode() == ISD::SRL) { 3823 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3824 if (C && C->getAPIntValue().isSignMask()) 3825 return true; 3826 } 3827 3828 // Are all operands of a build vector constant powers of two? 3829 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3830 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3831 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3832 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3833 return false; 3834 })) 3835 return true; 3836 3837 // Is the operand of a splat vector a constant power of two? 3838 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3839 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3840 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3841 return true; 3842 3843 // More could be done here, though the above checks are enough 3844 // to handle some common cases. 3845 3846 // Fall back to computeKnownBits to catch other known cases. 3847 KnownBits Known = computeKnownBits(Val); 3848 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3849 } 3850 3851 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3852 EVT VT = Op.getValueType(); 3853 3854 // TODO: Assume we don't know anything for now. 3855 if (VT.isScalableVector()) 3856 return 1; 3857 3858 APInt DemandedElts = VT.isVector() 3859 ? APInt::getAllOnes(VT.getVectorNumElements()) 3860 : APInt(1, 1); 3861 return ComputeNumSignBits(Op, DemandedElts, Depth); 3862 } 3863 3864 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3865 unsigned Depth) const { 3866 EVT VT = Op.getValueType(); 3867 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3868 unsigned VTBits = VT.getScalarSizeInBits(); 3869 unsigned NumElts = DemandedElts.getBitWidth(); 3870 unsigned Tmp, Tmp2; 3871 unsigned FirstAnswer = 1; 3872 3873 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3874 const APInt &Val = C->getAPIntValue(); 3875 return Val.getNumSignBits(); 3876 } 3877 3878 if (Depth >= MaxRecursionDepth) 3879 return 1; // Limit search depth. 3880 3881 if (!DemandedElts || VT.isScalableVector()) 3882 return 1; // No demanded elts, better to assume we don't know anything. 3883 3884 unsigned Opcode = Op.getOpcode(); 3885 switch (Opcode) { 3886 default: break; 3887 case ISD::AssertSext: 3888 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3889 return VTBits-Tmp+1; 3890 case ISD::AssertZext: 3891 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3892 return VTBits-Tmp; 3893 3894 case ISD::BUILD_VECTOR: 3895 Tmp = VTBits; 3896 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3897 if (!DemandedElts[i]) 3898 continue; 3899 3900 SDValue SrcOp = Op.getOperand(i); 3901 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3902 3903 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3904 if (SrcOp.getValueSizeInBits() != VTBits) { 3905 assert(SrcOp.getValueSizeInBits() > VTBits && 3906 "Expected BUILD_VECTOR implicit truncation"); 3907 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3908 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3909 } 3910 Tmp = std::min(Tmp, Tmp2); 3911 } 3912 return Tmp; 3913 3914 case ISD::VECTOR_SHUFFLE: { 3915 // Collect the minimum number of sign bits that are shared by every vector 3916 // element referenced by the shuffle. 3917 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3918 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3919 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3920 for (unsigned i = 0; i != NumElts; ++i) { 3921 int M = SVN->getMaskElt(i); 3922 if (!DemandedElts[i]) 3923 continue; 3924 // For UNDEF elements, we don't know anything about the common state of 3925 // the shuffle result. 3926 if (M < 0) 3927 return 1; 3928 if ((unsigned)M < NumElts) 3929 DemandedLHS.setBit((unsigned)M % NumElts); 3930 else 3931 DemandedRHS.setBit((unsigned)M % NumElts); 3932 } 3933 Tmp = std::numeric_limits<unsigned>::max(); 3934 if (!!DemandedLHS) 3935 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3936 if (!!DemandedRHS) { 3937 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3938 Tmp = std::min(Tmp, Tmp2); 3939 } 3940 // If we don't know anything, early out and try computeKnownBits fall-back. 3941 if (Tmp == 1) 3942 break; 3943 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3944 return Tmp; 3945 } 3946 3947 case ISD::BITCAST: { 3948 SDValue N0 = Op.getOperand(0); 3949 EVT SrcVT = N0.getValueType(); 3950 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3951 3952 // Ignore bitcasts from unsupported types.. 3953 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3954 break; 3955 3956 // Fast handling of 'identity' bitcasts. 3957 if (VTBits == SrcBits) 3958 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3959 3960 bool IsLE = getDataLayout().isLittleEndian(); 3961 3962 // Bitcast 'large element' scalar/vector to 'small element' vector. 3963 if ((SrcBits % VTBits) == 0) { 3964 assert(VT.isVector() && "Expected bitcast to vector"); 3965 3966 unsigned Scale = SrcBits / VTBits; 3967 APInt SrcDemandedElts = 3968 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3969 3970 // Fast case - sign splat can be simply split across the small elements. 3971 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3972 if (Tmp == SrcBits) 3973 return VTBits; 3974 3975 // Slow case - determine how far the sign extends into each sub-element. 3976 Tmp2 = VTBits; 3977 for (unsigned i = 0; i != NumElts; ++i) 3978 if (DemandedElts[i]) { 3979 unsigned SubOffset = i % Scale; 3980 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3981 SubOffset = SubOffset * VTBits; 3982 if (Tmp <= SubOffset) 3983 return 1; 3984 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3985 } 3986 return Tmp2; 3987 } 3988 break; 3989 } 3990 3991 case ISD::FP_TO_SINT_SAT: 3992 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 3993 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3994 return VTBits - Tmp + 1; 3995 case ISD::SIGN_EXTEND: 3996 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3997 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3998 case ISD::SIGN_EXTEND_INREG: 3999 // Max of the input and what this extends. 4000 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4001 Tmp = VTBits-Tmp+1; 4002 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4003 return std::max(Tmp, Tmp2); 4004 case ISD::SIGN_EXTEND_VECTOR_INREG: { 4005 SDValue Src = Op.getOperand(0); 4006 EVT SrcVT = Src.getValueType(); 4007 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements()); 4008 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4009 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4010 } 4011 case ISD::SRA: 4012 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4013 // SRA X, C -> adds C sign bits. 4014 if (const APInt *ShAmt = 4015 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4016 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4017 return Tmp; 4018 case ISD::SHL: 4019 if (const APInt *ShAmt = 4020 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4021 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4022 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4023 if (ShAmt->ult(Tmp)) 4024 return Tmp - ShAmt->getZExtValue(); 4025 } 4026 break; 4027 case ISD::AND: 4028 case ISD::OR: 4029 case ISD::XOR: // NOT is handled here. 4030 // Logical binary ops preserve the number of sign bits at the worst. 4031 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4032 if (Tmp != 1) { 4033 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4034 FirstAnswer = std::min(Tmp, Tmp2); 4035 // We computed what we know about the sign bits as our first 4036 // answer. Now proceed to the generic code that uses 4037 // computeKnownBits, and pick whichever answer is better. 4038 } 4039 break; 4040 4041 case ISD::SELECT: 4042 case ISD::VSELECT: 4043 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4044 if (Tmp == 1) return 1; // Early out. 4045 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4046 return std::min(Tmp, Tmp2); 4047 case ISD::SELECT_CC: 4048 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4049 if (Tmp == 1) return 1; // Early out. 4050 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4051 return std::min(Tmp, Tmp2); 4052 4053 case ISD::SMIN: 4054 case ISD::SMAX: { 4055 // If we have a clamp pattern, we know that the number of sign bits will be 4056 // the minimum of the clamp min/max range. 4057 bool IsMax = (Opcode == ISD::SMAX); 4058 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4059 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4060 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4061 CstHigh = 4062 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4063 if (CstLow && CstHigh) { 4064 if (!IsMax) 4065 std::swap(CstLow, CstHigh); 4066 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4067 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4068 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4069 return std::min(Tmp, Tmp2); 4070 } 4071 } 4072 4073 // Fallback - just get the minimum number of sign bits of the operands. 4074 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4075 if (Tmp == 1) 4076 return 1; // Early out. 4077 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4078 return std::min(Tmp, Tmp2); 4079 } 4080 case ISD::UMIN: 4081 case ISD::UMAX: 4082 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4083 if (Tmp == 1) 4084 return 1; // Early out. 4085 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4086 return std::min(Tmp, Tmp2); 4087 case ISD::SADDO: 4088 case ISD::UADDO: 4089 case ISD::SSUBO: 4090 case ISD::USUBO: 4091 case ISD::SMULO: 4092 case ISD::UMULO: 4093 if (Op.getResNo() != 1) 4094 break; 4095 // The boolean result conforms to getBooleanContents. Fall through. 4096 // If setcc returns 0/-1, all bits are sign bits. 4097 // We know that we have an integer-based boolean since these operations 4098 // are only available for integer. 4099 if (TLI->getBooleanContents(VT.isVector(), false) == 4100 TargetLowering::ZeroOrNegativeOneBooleanContent) 4101 return VTBits; 4102 break; 4103 case ISD::SETCC: 4104 case ISD::STRICT_FSETCC: 4105 case ISD::STRICT_FSETCCS: { 4106 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4107 // If setcc returns 0/-1, all bits are sign bits. 4108 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4109 TargetLowering::ZeroOrNegativeOneBooleanContent) 4110 return VTBits; 4111 break; 4112 } 4113 case ISD::ROTL: 4114 case ISD::ROTR: 4115 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4116 4117 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4118 if (Tmp == VTBits) 4119 return VTBits; 4120 4121 if (ConstantSDNode *C = 4122 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4123 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4124 4125 // Handle rotate right by N like a rotate left by 32-N. 4126 if (Opcode == ISD::ROTR) 4127 RotAmt = (VTBits - RotAmt) % VTBits; 4128 4129 // If we aren't rotating out all of the known-in sign bits, return the 4130 // number that are left. This handles rotl(sext(x), 1) for example. 4131 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4132 } 4133 break; 4134 case ISD::ADD: 4135 case ISD::ADDC: 4136 // Add can have at most one carry bit. Thus we know that the output 4137 // is, at worst, one more bit than the inputs. 4138 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4139 if (Tmp == 1) return 1; // Early out. 4140 4141 // Special case decrementing a value (ADD X, -1): 4142 if (ConstantSDNode *CRHS = 4143 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4144 if (CRHS->isAllOnes()) { 4145 KnownBits Known = 4146 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4147 4148 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4149 // sign bits set. 4150 if ((Known.Zero | 1).isAllOnes()) 4151 return VTBits; 4152 4153 // If we are subtracting one from a positive number, there is no carry 4154 // out of the result. 4155 if (Known.isNonNegative()) 4156 return Tmp; 4157 } 4158 4159 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4160 if (Tmp2 == 1) return 1; // Early out. 4161 return std::min(Tmp, Tmp2) - 1; 4162 case ISD::SUB: 4163 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4164 if (Tmp2 == 1) return 1; // Early out. 4165 4166 // Handle NEG. 4167 if (ConstantSDNode *CLHS = 4168 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4169 if (CLHS->isZero()) { 4170 KnownBits Known = 4171 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4172 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4173 // sign bits set. 4174 if ((Known.Zero | 1).isAllOnes()) 4175 return VTBits; 4176 4177 // If the input is known to be positive (the sign bit is known clear), 4178 // the output of the NEG has the same number of sign bits as the input. 4179 if (Known.isNonNegative()) 4180 return Tmp2; 4181 4182 // Otherwise, we treat this like a SUB. 4183 } 4184 4185 // Sub can have at most one carry bit. Thus we know that the output 4186 // is, at worst, one more bit than the inputs. 4187 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4188 if (Tmp == 1) return 1; // Early out. 4189 return std::min(Tmp, Tmp2) - 1; 4190 case ISD::MUL: { 4191 // The output of the Mul can be at most twice the valid bits in the inputs. 4192 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4193 if (SignBitsOp0 == 1) 4194 break; 4195 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4196 if (SignBitsOp1 == 1) 4197 break; 4198 unsigned OutValidBits = 4199 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4200 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4201 } 4202 case ISD::SREM: 4203 // The sign bit is the LHS's sign bit, except when the result of the 4204 // remainder is zero. The magnitude of the result should be less than or 4205 // equal to the magnitude of the LHS. Therefore, the result should have 4206 // at least as many sign bits as the left hand side. 4207 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4208 case ISD::TRUNCATE: { 4209 // Check if the sign bits of source go down as far as the truncated value. 4210 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4211 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4212 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4213 return NumSrcSignBits - (NumSrcBits - VTBits); 4214 break; 4215 } 4216 case ISD::EXTRACT_ELEMENT: { 4217 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4218 const int BitWidth = Op.getValueSizeInBits(); 4219 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4220 4221 // Get reverse index (starting from 1), Op1 value indexes elements from 4222 // little end. Sign starts at big end. 4223 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4224 4225 // If the sign portion ends in our element the subtraction gives correct 4226 // result. Otherwise it gives either negative or > bitwidth result 4227 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4228 } 4229 case ISD::INSERT_VECTOR_ELT: { 4230 // If we know the element index, split the demand between the 4231 // source vector and the inserted element, otherwise assume we need 4232 // the original demanded vector elements and the value. 4233 SDValue InVec = Op.getOperand(0); 4234 SDValue InVal = Op.getOperand(1); 4235 SDValue EltNo = Op.getOperand(2); 4236 bool DemandedVal = true; 4237 APInt DemandedVecElts = DemandedElts; 4238 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4239 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4240 unsigned EltIdx = CEltNo->getZExtValue(); 4241 DemandedVal = !!DemandedElts[EltIdx]; 4242 DemandedVecElts.clearBit(EltIdx); 4243 } 4244 Tmp = std::numeric_limits<unsigned>::max(); 4245 if (DemandedVal) { 4246 // TODO - handle implicit truncation of inserted elements. 4247 if (InVal.getScalarValueSizeInBits() != VTBits) 4248 break; 4249 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4250 Tmp = std::min(Tmp, Tmp2); 4251 } 4252 if (!!DemandedVecElts) { 4253 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4254 Tmp = std::min(Tmp, Tmp2); 4255 } 4256 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4257 return Tmp; 4258 } 4259 case ISD::EXTRACT_VECTOR_ELT: { 4260 SDValue InVec = Op.getOperand(0); 4261 SDValue EltNo = Op.getOperand(1); 4262 EVT VecVT = InVec.getValueType(); 4263 // ComputeNumSignBits not yet implemented for scalable vectors. 4264 if (VecVT.isScalableVector()) 4265 break; 4266 const unsigned BitWidth = Op.getValueSizeInBits(); 4267 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4268 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4269 4270 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4271 // anything about sign bits. But if the sizes match we can derive knowledge 4272 // about sign bits from the vector operand. 4273 if (BitWidth != EltBitWidth) 4274 break; 4275 4276 // If we know the element index, just demand that vector element, else for 4277 // an unknown element index, ignore DemandedElts and demand them all. 4278 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4279 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4280 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4281 DemandedSrcElts = 4282 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4283 4284 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4285 } 4286 case ISD::EXTRACT_SUBVECTOR: { 4287 // Offset the demanded elts by the subvector index. 4288 SDValue Src = Op.getOperand(0); 4289 // Bail until we can represent demanded elements for scalable vectors. 4290 if (Src.getValueType().isScalableVector()) 4291 break; 4292 uint64_t Idx = Op.getConstantOperandVal(1); 4293 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4294 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 4295 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4296 } 4297 case ISD::CONCAT_VECTORS: { 4298 // Determine the minimum number of sign bits across all demanded 4299 // elts of the input vectors. Early out if the result is already 1. 4300 Tmp = std::numeric_limits<unsigned>::max(); 4301 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4302 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4303 unsigned NumSubVectors = Op.getNumOperands(); 4304 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4305 APInt DemandedSub = 4306 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4307 if (!DemandedSub) 4308 continue; 4309 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4310 Tmp = std::min(Tmp, Tmp2); 4311 } 4312 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4313 return Tmp; 4314 } 4315 case ISD::INSERT_SUBVECTOR: { 4316 // Demand any elements from the subvector and the remainder from the src its 4317 // inserted into. 4318 SDValue Src = Op.getOperand(0); 4319 SDValue Sub = Op.getOperand(1); 4320 uint64_t Idx = Op.getConstantOperandVal(2); 4321 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4322 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4323 APInt DemandedSrcElts = DemandedElts; 4324 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4325 4326 Tmp = std::numeric_limits<unsigned>::max(); 4327 if (!!DemandedSubElts) { 4328 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4329 if (Tmp == 1) 4330 return 1; // early-out 4331 } 4332 if (!!DemandedSrcElts) { 4333 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4334 Tmp = std::min(Tmp, Tmp2); 4335 } 4336 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4337 return Tmp; 4338 } 4339 case ISD::ATOMIC_CMP_SWAP: 4340 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4341 case ISD::ATOMIC_SWAP: 4342 case ISD::ATOMIC_LOAD_ADD: 4343 case ISD::ATOMIC_LOAD_SUB: 4344 case ISD::ATOMIC_LOAD_AND: 4345 case ISD::ATOMIC_LOAD_CLR: 4346 case ISD::ATOMIC_LOAD_OR: 4347 case ISD::ATOMIC_LOAD_XOR: 4348 case ISD::ATOMIC_LOAD_NAND: 4349 case ISD::ATOMIC_LOAD_MIN: 4350 case ISD::ATOMIC_LOAD_MAX: 4351 case ISD::ATOMIC_LOAD_UMIN: 4352 case ISD::ATOMIC_LOAD_UMAX: 4353 case ISD::ATOMIC_LOAD: { 4354 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4355 // If we are looking at the loaded value. 4356 if (Op.getResNo() == 0) { 4357 if (Tmp == VTBits) 4358 return 1; // early-out 4359 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4360 return VTBits - Tmp + 1; 4361 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4362 return VTBits - Tmp; 4363 } 4364 break; 4365 } 4366 } 4367 4368 // If we are looking at the loaded value of the SDNode. 4369 if (Op.getResNo() == 0) { 4370 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4371 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4372 unsigned ExtType = LD->getExtensionType(); 4373 switch (ExtType) { 4374 default: break; 4375 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4376 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4377 return VTBits - Tmp + 1; 4378 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4379 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4380 return VTBits - Tmp; 4381 case ISD::NON_EXTLOAD: 4382 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4383 // We only need to handle vectors - computeKnownBits should handle 4384 // scalar cases. 4385 Type *CstTy = Cst->getType(); 4386 if (CstTy->isVectorTy() && 4387 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4388 VTBits == CstTy->getScalarSizeInBits()) { 4389 Tmp = VTBits; 4390 for (unsigned i = 0; i != NumElts; ++i) { 4391 if (!DemandedElts[i]) 4392 continue; 4393 if (Constant *Elt = Cst->getAggregateElement(i)) { 4394 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4395 const APInt &Value = CInt->getValue(); 4396 Tmp = std::min(Tmp, Value.getNumSignBits()); 4397 continue; 4398 } 4399 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4400 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4401 Tmp = std::min(Tmp, Value.getNumSignBits()); 4402 continue; 4403 } 4404 } 4405 // Unknown type. Conservatively assume no bits match sign bit. 4406 return 1; 4407 } 4408 return Tmp; 4409 } 4410 } 4411 break; 4412 } 4413 } 4414 } 4415 4416 // Allow the target to implement this method for its nodes. 4417 if (Opcode >= ISD::BUILTIN_OP_END || 4418 Opcode == ISD::INTRINSIC_WO_CHAIN || 4419 Opcode == ISD::INTRINSIC_W_CHAIN || 4420 Opcode == ISD::INTRINSIC_VOID) { 4421 unsigned NumBits = 4422 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4423 if (NumBits > 1) 4424 FirstAnswer = std::max(FirstAnswer, NumBits); 4425 } 4426 4427 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4428 // use this information. 4429 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4430 return std::max(FirstAnswer, Known.countMinSignBits()); 4431 } 4432 4433 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4434 unsigned Depth) const { 4435 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4436 return Op.getScalarValueSizeInBits() - SignBits + 1; 4437 } 4438 4439 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4440 const APInt &DemandedElts, 4441 unsigned Depth) const { 4442 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4443 return Op.getScalarValueSizeInBits() - SignBits + 1; 4444 } 4445 4446 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4447 unsigned Depth) const { 4448 // Early out for FREEZE. 4449 if (Op.getOpcode() == ISD::FREEZE) 4450 return true; 4451 4452 // TODO: Assume we don't know anything for now. 4453 EVT VT = Op.getValueType(); 4454 if (VT.isScalableVector()) 4455 return false; 4456 4457 APInt DemandedElts = VT.isVector() 4458 ? APInt::getAllOnes(VT.getVectorNumElements()) 4459 : APInt(1, 1); 4460 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4461 } 4462 4463 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4464 const APInt &DemandedElts, 4465 bool PoisonOnly, 4466 unsigned Depth) const { 4467 unsigned Opcode = Op.getOpcode(); 4468 4469 // Early out for FREEZE. 4470 if (Opcode == ISD::FREEZE) 4471 return true; 4472 4473 if (Depth >= MaxRecursionDepth) 4474 return false; // Limit search depth. 4475 4476 if (isIntOrFPConstant(Op)) 4477 return true; 4478 4479 switch (Opcode) { 4480 case ISD::UNDEF: 4481 return PoisonOnly; 4482 4483 case ISD::BUILD_VECTOR: 4484 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4485 // this shouldn't affect the result. 4486 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4487 if (!DemandedElts[i]) 4488 continue; 4489 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4490 Depth + 1)) 4491 return false; 4492 } 4493 return true; 4494 4495 // TODO: Search for noundef attributes from library functions. 4496 4497 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4498 4499 default: 4500 // Allow the target to implement this method for its nodes. 4501 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4502 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4503 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4504 Op, DemandedElts, *this, PoisonOnly, Depth); 4505 break; 4506 } 4507 4508 return false; 4509 } 4510 4511 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4512 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4513 !isa<ConstantSDNode>(Op.getOperand(1))) 4514 return false; 4515 4516 if (Op.getOpcode() == ISD::OR && 4517 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4518 return false; 4519 4520 return true; 4521 } 4522 4523 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4524 // If we're told that NaNs won't happen, assume they won't. 4525 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4526 return true; 4527 4528 if (Depth >= MaxRecursionDepth) 4529 return false; // Limit search depth. 4530 4531 // TODO: Handle vectors. 4532 // If the value is a constant, we can obviously see if it is a NaN or not. 4533 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4534 return !C->getValueAPF().isNaN() || 4535 (SNaN && !C->getValueAPF().isSignaling()); 4536 } 4537 4538 unsigned Opcode = Op.getOpcode(); 4539 switch (Opcode) { 4540 case ISD::FADD: 4541 case ISD::FSUB: 4542 case ISD::FMUL: 4543 case ISD::FDIV: 4544 case ISD::FREM: 4545 case ISD::FSIN: 4546 case ISD::FCOS: { 4547 if (SNaN) 4548 return true; 4549 // TODO: Need isKnownNeverInfinity 4550 return false; 4551 } 4552 case ISD::FCANONICALIZE: 4553 case ISD::FEXP: 4554 case ISD::FEXP2: 4555 case ISD::FTRUNC: 4556 case ISD::FFLOOR: 4557 case ISD::FCEIL: 4558 case ISD::FROUND: 4559 case ISD::FROUNDEVEN: 4560 case ISD::FRINT: 4561 case ISD::FNEARBYINT: { 4562 if (SNaN) 4563 return true; 4564 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4565 } 4566 case ISD::FABS: 4567 case ISD::FNEG: 4568 case ISD::FCOPYSIGN: { 4569 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4570 } 4571 case ISD::SELECT: 4572 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4573 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4574 case ISD::FP_EXTEND: 4575 case ISD::FP_ROUND: { 4576 if (SNaN) 4577 return true; 4578 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4579 } 4580 case ISD::SINT_TO_FP: 4581 case ISD::UINT_TO_FP: 4582 return true; 4583 case ISD::FMA: 4584 case ISD::FMAD: { 4585 if (SNaN) 4586 return true; 4587 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4588 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4589 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4590 } 4591 case ISD::FSQRT: // Need is known positive 4592 case ISD::FLOG: 4593 case ISD::FLOG2: 4594 case ISD::FLOG10: 4595 case ISD::FPOWI: 4596 case ISD::FPOW: { 4597 if (SNaN) 4598 return true; 4599 // TODO: Refine on operand 4600 return false; 4601 } 4602 case ISD::FMINNUM: 4603 case ISD::FMAXNUM: { 4604 // Only one needs to be known not-nan, since it will be returned if the 4605 // other ends up being one. 4606 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4607 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4608 } 4609 case ISD::FMINNUM_IEEE: 4610 case ISD::FMAXNUM_IEEE: { 4611 if (SNaN) 4612 return true; 4613 // This can return a NaN if either operand is an sNaN, or if both operands 4614 // are NaN. 4615 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4616 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4617 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4618 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4619 } 4620 case ISD::FMINIMUM: 4621 case ISD::FMAXIMUM: { 4622 // TODO: Does this quiet or return the origina NaN as-is? 4623 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4624 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4625 } 4626 case ISD::EXTRACT_VECTOR_ELT: { 4627 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4628 } 4629 default: 4630 if (Opcode >= ISD::BUILTIN_OP_END || 4631 Opcode == ISD::INTRINSIC_WO_CHAIN || 4632 Opcode == ISD::INTRINSIC_W_CHAIN || 4633 Opcode == ISD::INTRINSIC_VOID) { 4634 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4635 } 4636 4637 return false; 4638 } 4639 } 4640 4641 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4642 assert(Op.getValueType().isFloatingPoint() && 4643 "Floating point type expected"); 4644 4645 // If the value is a constant, we can obviously see if it is a zero or not. 4646 // TODO: Add BuildVector support. 4647 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4648 return !C->isZero(); 4649 return false; 4650 } 4651 4652 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4653 assert(!Op.getValueType().isFloatingPoint() && 4654 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4655 4656 // If the value is a constant, we can obviously see if it is a zero or not. 4657 if (ISD::matchUnaryPredicate(Op, 4658 [](ConstantSDNode *C) { return !C->isZero(); })) 4659 return true; 4660 4661 // TODO: Recognize more cases here. 4662 switch (Op.getOpcode()) { 4663 default: break; 4664 case ISD::OR: 4665 if (isKnownNeverZero(Op.getOperand(1)) || 4666 isKnownNeverZero(Op.getOperand(0))) 4667 return true; 4668 break; 4669 } 4670 4671 return false; 4672 } 4673 4674 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4675 // Check the obvious case. 4676 if (A == B) return true; 4677 4678 // For for negative and positive zero. 4679 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4680 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4681 if (CA->isZero() && CB->isZero()) return true; 4682 4683 // Otherwise they may not be equal. 4684 return false; 4685 } 4686 4687 // Only bits set in Mask must be negated, other bits may be arbitrary. 4688 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) { 4689 if (isBitwiseNot(V, AllowUndefs)) 4690 return V.getOperand(0); 4691 4692 // Handle any_extend (not (truncate X)) pattern, where Mask only sets 4693 // bits in the non-extended part. 4694 ConstantSDNode *MaskC = isConstOrConstSplat(Mask); 4695 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND) 4696 return SDValue(); 4697 SDValue ExtArg = V.getOperand(0); 4698 if (ExtArg.getScalarValueSizeInBits() >= 4699 MaskC->getAPIntValue().getActiveBits() && 4700 isBitwiseNot(ExtArg, AllowUndefs) && 4701 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE && 4702 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType()) 4703 return ExtArg.getOperand(0).getOperand(0); 4704 return SDValue(); 4705 } 4706 4707 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) { 4708 // Match masked merge pattern (X & ~M) op (Y & M) 4709 // Including degenerate case (X & ~M) op M 4710 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask, 4711 SDValue Other) { 4712 if (SDValue NotOperand = 4713 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) { 4714 if (Other == NotOperand) 4715 return true; 4716 if (Other->getOpcode() == ISD::AND) 4717 return NotOperand == Other->getOperand(0) || 4718 NotOperand == Other->getOperand(1); 4719 } 4720 return false; 4721 }; 4722 if (A->getOpcode() == ISD::AND) 4723 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) || 4724 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B); 4725 return false; 4726 } 4727 4728 // FIXME: unify with llvm::haveNoCommonBitsSet. 4729 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4730 assert(A.getValueType() == B.getValueType() && 4731 "Values must have the same type"); 4732 if (haveNoCommonBitsSetCommutative(A, B) || 4733 haveNoCommonBitsSetCommutative(B, A)) 4734 return true; 4735 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4736 computeKnownBits(B)); 4737 } 4738 4739 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4740 SelectionDAG &DAG) { 4741 if (cast<ConstantSDNode>(Step)->isZero()) 4742 return DAG.getConstant(0, DL, VT); 4743 4744 return SDValue(); 4745 } 4746 4747 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4748 ArrayRef<SDValue> Ops, 4749 SelectionDAG &DAG) { 4750 int NumOps = Ops.size(); 4751 assert(NumOps != 0 && "Can't build an empty vector!"); 4752 assert(!VT.isScalableVector() && 4753 "BUILD_VECTOR cannot be used with scalable types"); 4754 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4755 "Incorrect element count in BUILD_VECTOR!"); 4756 4757 // BUILD_VECTOR of UNDEFs is UNDEF. 4758 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4759 return DAG.getUNDEF(VT); 4760 4761 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4762 SDValue IdentitySrc; 4763 bool IsIdentity = true; 4764 for (int i = 0; i != NumOps; ++i) { 4765 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4766 Ops[i].getOperand(0).getValueType() != VT || 4767 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4768 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4769 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4770 IsIdentity = false; 4771 break; 4772 } 4773 IdentitySrc = Ops[i].getOperand(0); 4774 } 4775 if (IsIdentity) 4776 return IdentitySrc; 4777 4778 return SDValue(); 4779 } 4780 4781 /// Try to simplify vector concatenation to an input value, undef, or build 4782 /// vector. 4783 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4784 ArrayRef<SDValue> Ops, 4785 SelectionDAG &DAG) { 4786 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4787 assert(llvm::all_of(Ops, 4788 [Ops](SDValue Op) { 4789 return Ops[0].getValueType() == Op.getValueType(); 4790 }) && 4791 "Concatenation of vectors with inconsistent value types!"); 4792 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4793 VT.getVectorElementCount() && 4794 "Incorrect element count in vector concatenation!"); 4795 4796 if (Ops.size() == 1) 4797 return Ops[0]; 4798 4799 // Concat of UNDEFs is UNDEF. 4800 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4801 return DAG.getUNDEF(VT); 4802 4803 // Scan the operands and look for extract operations from a single source 4804 // that correspond to insertion at the same location via this concatenation: 4805 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4806 SDValue IdentitySrc; 4807 bool IsIdentity = true; 4808 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4809 SDValue Op = Ops[i]; 4810 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4811 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4812 Op.getOperand(0).getValueType() != VT || 4813 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4814 Op.getConstantOperandVal(1) != IdentityIndex) { 4815 IsIdentity = false; 4816 break; 4817 } 4818 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4819 "Unexpected identity source vector for concat of extracts"); 4820 IdentitySrc = Op.getOperand(0); 4821 } 4822 if (IsIdentity) { 4823 assert(IdentitySrc && "Failed to set source vector of extracts"); 4824 return IdentitySrc; 4825 } 4826 4827 // The code below this point is only designed to work for fixed width 4828 // vectors, so we bail out for now. 4829 if (VT.isScalableVector()) 4830 return SDValue(); 4831 4832 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4833 // simplified to one big BUILD_VECTOR. 4834 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4835 EVT SVT = VT.getScalarType(); 4836 SmallVector<SDValue, 16> Elts; 4837 for (SDValue Op : Ops) { 4838 EVT OpVT = Op.getValueType(); 4839 if (Op.isUndef()) 4840 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4841 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4842 Elts.append(Op->op_begin(), Op->op_end()); 4843 else 4844 return SDValue(); 4845 } 4846 4847 // BUILD_VECTOR requires all inputs to be of the same type, find the 4848 // maximum type and extend them all. 4849 for (SDValue Op : Elts) 4850 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4851 4852 if (SVT.bitsGT(VT.getScalarType())) { 4853 for (SDValue &Op : Elts) { 4854 if (Op.isUndef()) 4855 Op = DAG.getUNDEF(SVT); 4856 else 4857 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4858 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4859 : DAG.getSExtOrTrunc(Op, DL, SVT); 4860 } 4861 } 4862 4863 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4864 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4865 return V; 4866 } 4867 4868 /// Gets or creates the specified node. 4869 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4870 FoldingSetNodeID ID; 4871 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4872 void *IP = nullptr; 4873 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4874 return SDValue(E, 0); 4875 4876 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4877 getVTList(VT)); 4878 CSEMap.InsertNode(N, IP); 4879 4880 InsertNode(N); 4881 SDValue V = SDValue(N, 0); 4882 NewSDValueDbgMsg(V, "Creating new node: ", this); 4883 return V; 4884 } 4885 4886 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4887 SDValue Operand) { 4888 SDNodeFlags Flags; 4889 if (Inserter) 4890 Flags = Inserter->getFlags(); 4891 return getNode(Opcode, DL, VT, Operand, Flags); 4892 } 4893 4894 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4895 SDValue Operand, const SDNodeFlags Flags) { 4896 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4897 "Operand is DELETED_NODE!"); 4898 // Constant fold unary operations with an integer constant operand. Even 4899 // opaque constant will be folded, because the folding of unary operations 4900 // doesn't create new constants with different values. Nevertheless, the 4901 // opaque flag is preserved during folding to prevent future folding with 4902 // other constants. 4903 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4904 const APInt &Val = C->getAPIntValue(); 4905 switch (Opcode) { 4906 default: break; 4907 case ISD::SIGN_EXTEND: 4908 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4909 C->isTargetOpcode(), C->isOpaque()); 4910 case ISD::TRUNCATE: 4911 if (C->isOpaque()) 4912 break; 4913 LLVM_FALLTHROUGH; 4914 case ISD::ZERO_EXTEND: 4915 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4916 C->isTargetOpcode(), C->isOpaque()); 4917 case ISD::ANY_EXTEND: 4918 // Some targets like RISCV prefer to sign extend some types. 4919 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4920 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4921 C->isTargetOpcode(), C->isOpaque()); 4922 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4923 C->isTargetOpcode(), C->isOpaque()); 4924 case ISD::UINT_TO_FP: 4925 case ISD::SINT_TO_FP: { 4926 APFloat apf(EVTToAPFloatSemantics(VT), 4927 APInt::getZero(VT.getSizeInBits())); 4928 (void)apf.convertFromAPInt(Val, 4929 Opcode==ISD::SINT_TO_FP, 4930 APFloat::rmNearestTiesToEven); 4931 return getConstantFP(apf, DL, VT); 4932 } 4933 case ISD::BITCAST: 4934 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4935 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4936 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4937 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4938 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4939 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4940 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4941 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4942 break; 4943 case ISD::ABS: 4944 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4945 C->isOpaque()); 4946 case ISD::BITREVERSE: 4947 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4948 C->isOpaque()); 4949 case ISD::BSWAP: 4950 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4951 C->isOpaque()); 4952 case ISD::CTPOP: 4953 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4954 C->isOpaque()); 4955 case ISD::CTLZ: 4956 case ISD::CTLZ_ZERO_UNDEF: 4957 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4958 C->isOpaque()); 4959 case ISD::CTTZ: 4960 case ISD::CTTZ_ZERO_UNDEF: 4961 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4962 C->isOpaque()); 4963 case ISD::FP16_TO_FP: { 4964 bool Ignored; 4965 APFloat FPV(APFloat::IEEEhalf(), 4966 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4967 4968 // This can return overflow, underflow, or inexact; we don't care. 4969 // FIXME need to be more flexible about rounding mode. 4970 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4971 APFloat::rmNearestTiesToEven, &Ignored); 4972 return getConstantFP(FPV, DL, VT); 4973 } 4974 case ISD::STEP_VECTOR: { 4975 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4976 return V; 4977 break; 4978 } 4979 } 4980 } 4981 4982 // Constant fold unary operations with a floating point constant operand. 4983 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4984 APFloat V = C->getValueAPF(); // make copy 4985 switch (Opcode) { 4986 case ISD::FNEG: 4987 V.changeSign(); 4988 return getConstantFP(V, DL, VT); 4989 case ISD::FABS: 4990 V.clearSign(); 4991 return getConstantFP(V, DL, VT); 4992 case ISD::FCEIL: { 4993 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4994 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4995 return getConstantFP(V, DL, VT); 4996 break; 4997 } 4998 case ISD::FTRUNC: { 4999 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 5000 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5001 return getConstantFP(V, DL, VT); 5002 break; 5003 } 5004 case ISD::FFLOOR: { 5005 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 5006 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5007 return getConstantFP(V, DL, VT); 5008 break; 5009 } 5010 case ISD::FP_EXTEND: { 5011 bool ignored; 5012 // This can return overflow, underflow, or inexact; we don't care. 5013 // FIXME need to be more flexible about rounding mode. 5014 (void)V.convert(EVTToAPFloatSemantics(VT), 5015 APFloat::rmNearestTiesToEven, &ignored); 5016 return getConstantFP(V, DL, VT); 5017 } 5018 case ISD::FP_TO_SINT: 5019 case ISD::FP_TO_UINT: { 5020 bool ignored; 5021 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 5022 // FIXME need to be more flexible about rounding mode. 5023 APFloat::opStatus s = 5024 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 5025 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 5026 break; 5027 return getConstant(IntVal, DL, VT); 5028 } 5029 case ISD::BITCAST: 5030 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 5031 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5032 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 5033 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5034 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 5035 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5036 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 5037 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5038 break; 5039 case ISD::FP_TO_FP16: { 5040 bool Ignored; 5041 // This can return overflow, underflow, or inexact; we don't care. 5042 // FIXME need to be more flexible about rounding mode. 5043 (void)V.convert(APFloat::IEEEhalf(), 5044 APFloat::rmNearestTiesToEven, &Ignored); 5045 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5046 } 5047 } 5048 } 5049 5050 // Constant fold unary operations with a vector integer or float operand. 5051 switch (Opcode) { 5052 default: 5053 // FIXME: Entirely reasonable to perform folding of other unary 5054 // operations here as the need arises. 5055 break; 5056 case ISD::FNEG: 5057 case ISD::FABS: 5058 case ISD::FCEIL: 5059 case ISD::FTRUNC: 5060 case ISD::FFLOOR: 5061 case ISD::FP_EXTEND: 5062 case ISD::FP_TO_SINT: 5063 case ISD::FP_TO_UINT: 5064 case ISD::TRUNCATE: 5065 case ISD::ANY_EXTEND: 5066 case ISD::ZERO_EXTEND: 5067 case ISD::SIGN_EXTEND: 5068 case ISD::UINT_TO_FP: 5069 case ISD::SINT_TO_FP: 5070 case ISD::ABS: 5071 case ISD::BITREVERSE: 5072 case ISD::BSWAP: 5073 case ISD::CTLZ: 5074 case ISD::CTLZ_ZERO_UNDEF: 5075 case ISD::CTTZ: 5076 case ISD::CTTZ_ZERO_UNDEF: 5077 case ISD::CTPOP: { 5078 SDValue Ops = {Operand}; 5079 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5080 return Fold; 5081 } 5082 } 5083 5084 unsigned OpOpcode = Operand.getNode()->getOpcode(); 5085 switch (Opcode) { 5086 case ISD::STEP_VECTOR: 5087 assert(VT.isScalableVector() && 5088 "STEP_VECTOR can only be used with scalable types"); 5089 assert(OpOpcode == ISD::TargetConstant && 5090 VT.getVectorElementType() == Operand.getValueType() && 5091 "Unexpected step operand"); 5092 break; 5093 case ISD::FREEZE: 5094 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5095 if (isGuaranteedNotToBeUndefOrPoison(Operand)) 5096 return Operand; 5097 break; 5098 case ISD::TokenFactor: 5099 case ISD::MERGE_VALUES: 5100 case ISD::CONCAT_VECTORS: 5101 return Operand; // Factor, merge or concat of one node? No need. 5102 case ISD::BUILD_VECTOR: { 5103 // Attempt to simplify BUILD_VECTOR. 5104 SDValue Ops[] = {Operand}; 5105 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5106 return V; 5107 break; 5108 } 5109 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5110 case ISD::FP_EXTEND: 5111 assert(VT.isFloatingPoint() && 5112 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 5113 if (Operand.getValueType() == VT) return Operand; // noop conversion. 5114 assert((!VT.isVector() || 5115 VT.getVectorElementCount() == 5116 Operand.getValueType().getVectorElementCount()) && 5117 "Vector element count mismatch!"); 5118 assert(Operand.getValueType().bitsLT(VT) && 5119 "Invalid fpext node, dst < src!"); 5120 if (Operand.isUndef()) 5121 return getUNDEF(VT); 5122 break; 5123 case ISD::FP_TO_SINT: 5124 case ISD::FP_TO_UINT: 5125 if (Operand.isUndef()) 5126 return getUNDEF(VT); 5127 break; 5128 case ISD::SINT_TO_FP: 5129 case ISD::UINT_TO_FP: 5130 // [us]itofp(undef) = 0, because the result value is bounded. 5131 if (Operand.isUndef()) 5132 return getConstantFP(0.0, DL, VT); 5133 break; 5134 case ISD::SIGN_EXTEND: 5135 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5136 "Invalid SIGN_EXTEND!"); 5137 assert(VT.isVector() == Operand.getValueType().isVector() && 5138 "SIGN_EXTEND result type type should be vector iff the operand " 5139 "type is vector!"); 5140 if (Operand.getValueType() == VT) return Operand; // noop extension 5141 assert((!VT.isVector() || 5142 VT.getVectorElementCount() == 5143 Operand.getValueType().getVectorElementCount()) && 5144 "Vector element count mismatch!"); 5145 assert(Operand.getValueType().bitsLT(VT) && 5146 "Invalid sext node, dst < src!"); 5147 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5148 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5149 if (OpOpcode == ISD::UNDEF) 5150 // sext(undef) = 0, because the top bits will all be the same. 5151 return getConstant(0, DL, VT); 5152 break; 5153 case ISD::ZERO_EXTEND: 5154 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5155 "Invalid ZERO_EXTEND!"); 5156 assert(VT.isVector() == Operand.getValueType().isVector() && 5157 "ZERO_EXTEND result type type should be vector iff the operand " 5158 "type is vector!"); 5159 if (Operand.getValueType() == VT) return Operand; // noop extension 5160 assert((!VT.isVector() || 5161 VT.getVectorElementCount() == 5162 Operand.getValueType().getVectorElementCount()) && 5163 "Vector element count mismatch!"); 5164 assert(Operand.getValueType().bitsLT(VT) && 5165 "Invalid zext node, dst < src!"); 5166 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5167 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5168 if (OpOpcode == ISD::UNDEF) 5169 // zext(undef) = 0, because the top bits will be zero. 5170 return getConstant(0, DL, VT); 5171 break; 5172 case ISD::ANY_EXTEND: 5173 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5174 "Invalid ANY_EXTEND!"); 5175 assert(VT.isVector() == Operand.getValueType().isVector() && 5176 "ANY_EXTEND result type type should be vector iff the operand " 5177 "type is vector!"); 5178 if (Operand.getValueType() == VT) return Operand; // noop extension 5179 assert((!VT.isVector() || 5180 VT.getVectorElementCount() == 5181 Operand.getValueType().getVectorElementCount()) && 5182 "Vector element count mismatch!"); 5183 assert(Operand.getValueType().bitsLT(VT) && 5184 "Invalid anyext node, dst < src!"); 5185 5186 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5187 OpOpcode == ISD::ANY_EXTEND) 5188 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5189 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5190 if (OpOpcode == ISD::UNDEF) 5191 return getUNDEF(VT); 5192 5193 // (ext (trunc x)) -> x 5194 if (OpOpcode == ISD::TRUNCATE) { 5195 SDValue OpOp = Operand.getOperand(0); 5196 if (OpOp.getValueType() == VT) { 5197 transferDbgValues(Operand, OpOp); 5198 return OpOp; 5199 } 5200 } 5201 break; 5202 case ISD::TRUNCATE: 5203 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5204 "Invalid TRUNCATE!"); 5205 assert(VT.isVector() == Operand.getValueType().isVector() && 5206 "TRUNCATE result type type should be vector iff the operand " 5207 "type is vector!"); 5208 if (Operand.getValueType() == VT) return Operand; // noop truncate 5209 assert((!VT.isVector() || 5210 VT.getVectorElementCount() == 5211 Operand.getValueType().getVectorElementCount()) && 5212 "Vector element count mismatch!"); 5213 assert(Operand.getValueType().bitsGT(VT) && 5214 "Invalid truncate node, src < dst!"); 5215 if (OpOpcode == ISD::TRUNCATE) 5216 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5217 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5218 OpOpcode == ISD::ANY_EXTEND) { 5219 // If the source is smaller than the dest, we still need an extend. 5220 if (Operand.getOperand(0).getValueType().getScalarType() 5221 .bitsLT(VT.getScalarType())) 5222 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5223 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5224 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5225 return Operand.getOperand(0); 5226 } 5227 if (OpOpcode == ISD::UNDEF) 5228 return getUNDEF(VT); 5229 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5230 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5231 break; 5232 case ISD::ANY_EXTEND_VECTOR_INREG: 5233 case ISD::ZERO_EXTEND_VECTOR_INREG: 5234 case ISD::SIGN_EXTEND_VECTOR_INREG: 5235 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5236 assert(Operand.getValueType().bitsLE(VT) && 5237 "The input must be the same size or smaller than the result."); 5238 assert(VT.getVectorMinNumElements() < 5239 Operand.getValueType().getVectorMinNumElements() && 5240 "The destination vector type must have fewer lanes than the input."); 5241 break; 5242 case ISD::ABS: 5243 assert(VT.isInteger() && VT == Operand.getValueType() && 5244 "Invalid ABS!"); 5245 if (OpOpcode == ISD::UNDEF) 5246 return getConstant(0, DL, VT); 5247 break; 5248 case ISD::BSWAP: 5249 assert(VT.isInteger() && VT == Operand.getValueType() && 5250 "Invalid BSWAP!"); 5251 assert((VT.getScalarSizeInBits() % 16 == 0) && 5252 "BSWAP types must be a multiple of 16 bits!"); 5253 if (OpOpcode == ISD::UNDEF) 5254 return getUNDEF(VT); 5255 // bswap(bswap(X)) -> X. 5256 if (OpOpcode == ISD::BSWAP) 5257 return Operand.getOperand(0); 5258 break; 5259 case ISD::BITREVERSE: 5260 assert(VT.isInteger() && VT == Operand.getValueType() && 5261 "Invalid BITREVERSE!"); 5262 if (OpOpcode == ISD::UNDEF) 5263 return getUNDEF(VT); 5264 break; 5265 case ISD::BITCAST: 5266 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5267 "Cannot BITCAST between types of different sizes!"); 5268 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5269 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5270 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5271 if (OpOpcode == ISD::UNDEF) 5272 return getUNDEF(VT); 5273 break; 5274 case ISD::SCALAR_TO_VECTOR: 5275 assert(VT.isVector() && !Operand.getValueType().isVector() && 5276 (VT.getVectorElementType() == Operand.getValueType() || 5277 (VT.getVectorElementType().isInteger() && 5278 Operand.getValueType().isInteger() && 5279 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5280 "Illegal SCALAR_TO_VECTOR node!"); 5281 if (OpOpcode == ISD::UNDEF) 5282 return getUNDEF(VT); 5283 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5284 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5285 isa<ConstantSDNode>(Operand.getOperand(1)) && 5286 Operand.getConstantOperandVal(1) == 0 && 5287 Operand.getOperand(0).getValueType() == VT) 5288 return Operand.getOperand(0); 5289 break; 5290 case ISD::FNEG: 5291 // Negation of an unknown bag of bits is still completely undefined. 5292 if (OpOpcode == ISD::UNDEF) 5293 return getUNDEF(VT); 5294 5295 if (OpOpcode == ISD::FNEG) // --X -> X 5296 return Operand.getOperand(0); 5297 break; 5298 case ISD::FABS: 5299 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5300 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5301 break; 5302 case ISD::VSCALE: 5303 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5304 break; 5305 case ISD::CTPOP: 5306 if (Operand.getValueType().getScalarType() == MVT::i1) 5307 return Operand; 5308 break; 5309 case ISD::CTLZ: 5310 case ISD::CTTZ: 5311 if (Operand.getValueType().getScalarType() == MVT::i1) 5312 return getNOT(DL, Operand, Operand.getValueType()); 5313 break; 5314 case ISD::VECREDUCE_ADD: 5315 if (Operand.getValueType().getScalarType() == MVT::i1) 5316 return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand); 5317 break; 5318 case ISD::VECREDUCE_SMIN: 5319 case ISD::VECREDUCE_UMAX: 5320 if (Operand.getValueType().getScalarType() == MVT::i1) 5321 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5322 break; 5323 case ISD::VECREDUCE_SMAX: 5324 case ISD::VECREDUCE_UMIN: 5325 if (Operand.getValueType().getScalarType() == MVT::i1) 5326 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5327 break; 5328 } 5329 5330 SDNode *N; 5331 SDVTList VTs = getVTList(VT); 5332 SDValue Ops[] = {Operand}; 5333 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5334 FoldingSetNodeID ID; 5335 AddNodeIDNode(ID, Opcode, VTs, Ops); 5336 void *IP = nullptr; 5337 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5338 E->intersectFlagsWith(Flags); 5339 return SDValue(E, 0); 5340 } 5341 5342 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5343 N->setFlags(Flags); 5344 createOperands(N, Ops); 5345 CSEMap.InsertNode(N, IP); 5346 } else { 5347 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5348 createOperands(N, Ops); 5349 } 5350 5351 InsertNode(N); 5352 SDValue V = SDValue(N, 0); 5353 NewSDValueDbgMsg(V, "Creating new node: ", this); 5354 return V; 5355 } 5356 5357 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5358 const APInt &C2) { 5359 switch (Opcode) { 5360 case ISD::ADD: return C1 + C2; 5361 case ISD::SUB: return C1 - C2; 5362 case ISD::MUL: return C1 * C2; 5363 case ISD::AND: return C1 & C2; 5364 case ISD::OR: return C1 | C2; 5365 case ISD::XOR: return C1 ^ C2; 5366 case ISD::SHL: return C1 << C2; 5367 case ISD::SRL: return C1.lshr(C2); 5368 case ISD::SRA: return C1.ashr(C2); 5369 case ISD::ROTL: return C1.rotl(C2); 5370 case ISD::ROTR: return C1.rotr(C2); 5371 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5372 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5373 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5374 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5375 case ISD::SADDSAT: return C1.sadd_sat(C2); 5376 case ISD::UADDSAT: return C1.uadd_sat(C2); 5377 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5378 case ISD::USUBSAT: return C1.usub_sat(C2); 5379 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5380 case ISD::USHLSAT: return C1.ushl_sat(C2); 5381 case ISD::UDIV: 5382 if (!C2.getBoolValue()) 5383 break; 5384 return C1.udiv(C2); 5385 case ISD::UREM: 5386 if (!C2.getBoolValue()) 5387 break; 5388 return C1.urem(C2); 5389 case ISD::SDIV: 5390 if (!C2.getBoolValue()) 5391 break; 5392 return C1.sdiv(C2); 5393 case ISD::SREM: 5394 if (!C2.getBoolValue()) 5395 break; 5396 return C1.srem(C2); 5397 case ISD::MULHS: { 5398 unsigned FullWidth = C1.getBitWidth() * 2; 5399 APInt C1Ext = C1.sext(FullWidth); 5400 APInt C2Ext = C2.sext(FullWidth); 5401 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5402 } 5403 case ISD::MULHU: { 5404 unsigned FullWidth = C1.getBitWidth() * 2; 5405 APInt C1Ext = C1.zext(FullWidth); 5406 APInt C2Ext = C2.zext(FullWidth); 5407 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5408 } 5409 case ISD::AVGFLOORS: { 5410 unsigned FullWidth = C1.getBitWidth() + 1; 5411 APInt C1Ext = C1.sext(FullWidth); 5412 APInt C2Ext = C2.sext(FullWidth); 5413 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5414 } 5415 case ISD::AVGFLOORU: { 5416 unsigned FullWidth = C1.getBitWidth() + 1; 5417 APInt C1Ext = C1.zext(FullWidth); 5418 APInt C2Ext = C2.zext(FullWidth); 5419 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5420 } 5421 case ISD::AVGCEILS: { 5422 unsigned FullWidth = C1.getBitWidth() + 1; 5423 APInt C1Ext = C1.sext(FullWidth); 5424 APInt C2Ext = C2.sext(FullWidth); 5425 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5426 } 5427 case ISD::AVGCEILU: { 5428 unsigned FullWidth = C1.getBitWidth() + 1; 5429 APInt C1Ext = C1.zext(FullWidth); 5430 APInt C2Ext = C2.zext(FullWidth); 5431 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5432 } 5433 } 5434 return llvm::None; 5435 } 5436 5437 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5438 const GlobalAddressSDNode *GA, 5439 const SDNode *N2) { 5440 if (GA->getOpcode() != ISD::GlobalAddress) 5441 return SDValue(); 5442 if (!TLI->isOffsetFoldingLegal(GA)) 5443 return SDValue(); 5444 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5445 if (!C2) 5446 return SDValue(); 5447 int64_t Offset = C2->getSExtValue(); 5448 switch (Opcode) { 5449 case ISD::ADD: break; 5450 case ISD::SUB: Offset = -uint64_t(Offset); break; 5451 default: return SDValue(); 5452 } 5453 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5454 GA->getOffset() + uint64_t(Offset)); 5455 } 5456 5457 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5458 switch (Opcode) { 5459 case ISD::SDIV: 5460 case ISD::UDIV: 5461 case ISD::SREM: 5462 case ISD::UREM: { 5463 // If a divisor is zero/undef or any element of a divisor vector is 5464 // zero/undef, the whole op is undef. 5465 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5466 SDValue Divisor = Ops[1]; 5467 if (Divisor.isUndef() || isNullConstant(Divisor)) 5468 return true; 5469 5470 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5471 llvm::any_of(Divisor->op_values(), 5472 [](SDValue V) { return V.isUndef() || 5473 isNullConstant(V); }); 5474 // TODO: Handle signed overflow. 5475 } 5476 // TODO: Handle oversized shifts. 5477 default: 5478 return false; 5479 } 5480 } 5481 5482 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5483 EVT VT, ArrayRef<SDValue> Ops) { 5484 // If the opcode is a target-specific ISD node, there's nothing we can 5485 // do here and the operand rules may not line up with the below, so 5486 // bail early. 5487 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5488 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5489 // foldCONCAT_VECTORS in getNode before this is called. 5490 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5491 return SDValue(); 5492 5493 unsigned NumOps = Ops.size(); 5494 if (NumOps == 0) 5495 return SDValue(); 5496 5497 if (isUndef(Opcode, Ops)) 5498 return getUNDEF(VT); 5499 5500 // Handle binops special cases. 5501 if (NumOps == 2) { 5502 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5503 return CFP; 5504 5505 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5506 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5507 if (C1->isOpaque() || C2->isOpaque()) 5508 return SDValue(); 5509 5510 Optional<APInt> FoldAttempt = 5511 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5512 if (!FoldAttempt) 5513 return SDValue(); 5514 5515 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5516 assert((!Folded || !VT.isVector()) && 5517 "Can't fold vectors ops with scalar operands"); 5518 return Folded; 5519 } 5520 } 5521 5522 // fold (add Sym, c) -> Sym+c 5523 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5524 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5525 if (TLI->isCommutativeBinOp(Opcode)) 5526 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5527 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5528 } 5529 5530 // This is for vector folding only from here on. 5531 if (!VT.isVector()) 5532 return SDValue(); 5533 5534 ElementCount NumElts = VT.getVectorElementCount(); 5535 5536 // See if we can fold through bitcasted integer ops. 5537 // TODO: Can we handle undef elements? 5538 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5539 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5540 Ops[0].getOpcode() == ISD::BITCAST && 5541 Ops[1].getOpcode() == ISD::BITCAST) { 5542 SDValue N1 = peekThroughBitcasts(Ops[0]); 5543 SDValue N2 = peekThroughBitcasts(Ops[1]); 5544 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5545 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5546 EVT BVVT = N1.getValueType(); 5547 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5548 bool IsLE = getDataLayout().isLittleEndian(); 5549 unsigned EltBits = VT.getScalarSizeInBits(); 5550 SmallVector<APInt> RawBits1, RawBits2; 5551 BitVector UndefElts1, UndefElts2; 5552 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5553 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5554 UndefElts1.none() && UndefElts2.none()) { 5555 SmallVector<APInt> RawBits; 5556 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5557 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5558 if (!Fold) 5559 break; 5560 RawBits.push_back(Fold.getValue()); 5561 } 5562 if (RawBits.size() == NumElts.getFixedValue()) { 5563 // We have constant folded, but we need to cast this again back to 5564 // the original (possibly legalized) type. 5565 SmallVector<APInt> DstBits; 5566 BitVector DstUndefs; 5567 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5568 DstBits, RawBits, DstUndefs, 5569 BitVector(RawBits.size(), false)); 5570 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5571 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5572 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5573 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5574 if (DstUndefs[I]) 5575 continue; 5576 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT); 5577 } 5578 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5579 } 5580 } 5581 } 5582 } 5583 5584 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5585 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5586 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5587 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5588 APInt RHSVal; 5589 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5590 APInt NewStep = Opcode == ISD::MUL 5591 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5592 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5593 return getStepVector(DL, VT, NewStep); 5594 } 5595 } 5596 5597 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5598 return !Op.getValueType().isVector() || 5599 Op.getValueType().getVectorElementCount() == NumElts; 5600 }; 5601 5602 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5603 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5604 Op.getOpcode() == ISD::BUILD_VECTOR || 5605 Op.getOpcode() == ISD::SPLAT_VECTOR; 5606 }; 5607 5608 // All operands must be vector types with the same number of elements as 5609 // the result type and must be either UNDEF or a build/splat vector 5610 // or UNDEF scalars. 5611 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5612 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5613 return SDValue(); 5614 5615 // If we are comparing vectors, then the result needs to be a i1 boolean that 5616 // is then extended back to the legal result type depending on how booleans 5617 // are represented. 5618 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5619 ISD::NodeType ExtendCode = 5620 (Opcode == ISD::SETCC && SVT != VT.getScalarType()) 5621 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT)) 5622 : ISD::SIGN_EXTEND; 5623 5624 // Find legal integer scalar type for constant promotion and 5625 // ensure that its scalar size is at least as large as source. 5626 EVT LegalSVT = VT.getScalarType(); 5627 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5628 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5629 if (LegalSVT.bitsLT(VT.getScalarType())) 5630 return SDValue(); 5631 } 5632 5633 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5634 // only have one operand to check. For fixed-length vector types we may have 5635 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5636 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5637 5638 // Constant fold each scalar lane separately. 5639 SmallVector<SDValue, 4> ScalarResults; 5640 for (unsigned I = 0; I != NumVectorElts; I++) { 5641 SmallVector<SDValue, 4> ScalarOps; 5642 for (SDValue Op : Ops) { 5643 EVT InSVT = Op.getValueType().getScalarType(); 5644 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5645 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5646 if (Op.isUndef()) 5647 ScalarOps.push_back(getUNDEF(InSVT)); 5648 else 5649 ScalarOps.push_back(Op); 5650 continue; 5651 } 5652 5653 SDValue ScalarOp = 5654 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5655 EVT ScalarVT = ScalarOp.getValueType(); 5656 5657 // Build vector (integer) scalar operands may need implicit 5658 // truncation - do this before constant folding. 5659 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 5660 // Don't create illegally-typed nodes unless they're constants or undef 5661 // - if we fail to constant fold we can't guarantee the (dead) nodes 5662 // we're creating will be cleaned up before being visited for 5663 // legalization. 5664 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 5665 !isa<ConstantSDNode>(ScalarOp) && 5666 TLI->getTypeAction(*getContext(), InSVT) != 5667 TargetLowering::TypeLegal) 5668 return SDValue(); 5669 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5670 } 5671 5672 ScalarOps.push_back(ScalarOp); 5673 } 5674 5675 // Constant fold the scalar operands. 5676 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5677 5678 // Legalize the (integer) scalar constant if necessary. 5679 if (LegalSVT != SVT) 5680 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult); 5681 5682 // Scalar folding only succeeded if the result is a constant or UNDEF. 5683 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5684 ScalarResult.getOpcode() != ISD::ConstantFP) 5685 return SDValue(); 5686 ScalarResults.push_back(ScalarResult); 5687 } 5688 5689 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5690 : getBuildVector(VT, DL, ScalarResults); 5691 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5692 return V; 5693 } 5694 5695 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5696 EVT VT, SDValue N1, SDValue N2) { 5697 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5698 // should. That will require dealing with a potentially non-default 5699 // rounding mode, checking the "opStatus" return value from the APFloat 5700 // math calculations, and possibly other variations. 5701 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5702 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5703 if (N1CFP && N2CFP) { 5704 APFloat C1 = N1CFP->getValueAPF(); // make copy 5705 const APFloat &C2 = N2CFP->getValueAPF(); 5706 switch (Opcode) { 5707 case ISD::FADD: 5708 C1.add(C2, APFloat::rmNearestTiesToEven); 5709 return getConstantFP(C1, DL, VT); 5710 case ISD::FSUB: 5711 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5712 return getConstantFP(C1, DL, VT); 5713 case ISD::FMUL: 5714 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5715 return getConstantFP(C1, DL, VT); 5716 case ISD::FDIV: 5717 C1.divide(C2, APFloat::rmNearestTiesToEven); 5718 return getConstantFP(C1, DL, VT); 5719 case ISD::FREM: 5720 C1.mod(C2); 5721 return getConstantFP(C1, DL, VT); 5722 case ISD::FCOPYSIGN: 5723 C1.copySign(C2); 5724 return getConstantFP(C1, DL, VT); 5725 case ISD::FMINNUM: 5726 return getConstantFP(minnum(C1, C2), DL, VT); 5727 case ISD::FMAXNUM: 5728 return getConstantFP(maxnum(C1, C2), DL, VT); 5729 case ISD::FMINIMUM: 5730 return getConstantFP(minimum(C1, C2), DL, VT); 5731 case ISD::FMAXIMUM: 5732 return getConstantFP(maximum(C1, C2), DL, VT); 5733 default: break; 5734 } 5735 } 5736 if (N1CFP && Opcode == ISD::FP_ROUND) { 5737 APFloat C1 = N1CFP->getValueAPF(); // make copy 5738 bool Unused; 5739 // This can return overflow, underflow, or inexact; we don't care. 5740 // FIXME need to be more flexible about rounding mode. 5741 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5742 &Unused); 5743 return getConstantFP(C1, DL, VT); 5744 } 5745 5746 switch (Opcode) { 5747 case ISD::FSUB: 5748 // -0.0 - undef --> undef (consistent with "fneg undef") 5749 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5750 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5751 return getUNDEF(VT); 5752 LLVM_FALLTHROUGH; 5753 5754 case ISD::FADD: 5755 case ISD::FMUL: 5756 case ISD::FDIV: 5757 case ISD::FREM: 5758 // If both operands are undef, the result is undef. If 1 operand is undef, 5759 // the result is NaN. This should match the behavior of the IR optimizer. 5760 if (N1.isUndef() && N2.isUndef()) 5761 return getUNDEF(VT); 5762 if (N1.isUndef() || N2.isUndef()) 5763 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5764 } 5765 return SDValue(); 5766 } 5767 5768 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5769 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5770 5771 // There's no need to assert on a byte-aligned pointer. All pointers are at 5772 // least byte aligned. 5773 if (A == Align(1)) 5774 return Val; 5775 5776 FoldingSetNodeID ID; 5777 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5778 ID.AddInteger(A.value()); 5779 5780 void *IP = nullptr; 5781 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5782 return SDValue(E, 0); 5783 5784 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5785 Val.getValueType(), A); 5786 createOperands(N, {Val}); 5787 5788 CSEMap.InsertNode(N, IP); 5789 InsertNode(N); 5790 5791 SDValue V(N, 0); 5792 NewSDValueDbgMsg(V, "Creating new node: ", this); 5793 return V; 5794 } 5795 5796 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5797 SDValue N1, SDValue N2) { 5798 SDNodeFlags Flags; 5799 if (Inserter) 5800 Flags = Inserter->getFlags(); 5801 return getNode(Opcode, DL, VT, N1, N2, Flags); 5802 } 5803 5804 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5805 SDValue &N2) const { 5806 if (!TLI->isCommutativeBinOp(Opcode)) 5807 return; 5808 5809 // Canonicalize: 5810 // binop(const, nonconst) -> binop(nonconst, const) 5811 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5812 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5813 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5814 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5815 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5816 std::swap(N1, N2); 5817 5818 // Canonicalize: 5819 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5820 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5821 N2.getOpcode() == ISD::STEP_VECTOR) 5822 std::swap(N1, N2); 5823 } 5824 5825 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5826 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5827 assert(N1.getOpcode() != ISD::DELETED_NODE && 5828 N2.getOpcode() != ISD::DELETED_NODE && 5829 "Operand is DELETED_NODE!"); 5830 5831 canonicalizeCommutativeBinop(Opcode, N1, N2); 5832 5833 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5834 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5835 5836 // Don't allow undefs in vector splats - we might be returning N2 when folding 5837 // to zero etc. 5838 ConstantSDNode *N2CV = 5839 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5840 5841 switch (Opcode) { 5842 default: break; 5843 case ISD::TokenFactor: 5844 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5845 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5846 // Fold trivial token factors. 5847 if (N1.getOpcode() == ISD::EntryToken) return N2; 5848 if (N2.getOpcode() == ISD::EntryToken) return N1; 5849 if (N1 == N2) return N1; 5850 break; 5851 case ISD::BUILD_VECTOR: { 5852 // Attempt to simplify BUILD_VECTOR. 5853 SDValue Ops[] = {N1, N2}; 5854 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5855 return V; 5856 break; 5857 } 5858 case ISD::CONCAT_VECTORS: { 5859 SDValue Ops[] = {N1, N2}; 5860 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5861 return V; 5862 break; 5863 } 5864 case ISD::AND: 5865 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5866 assert(N1.getValueType() == N2.getValueType() && 5867 N1.getValueType() == VT && "Binary operator types must match!"); 5868 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5869 // worth handling here. 5870 if (N2CV && N2CV->isZero()) 5871 return N2; 5872 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5873 return N1; 5874 break; 5875 case ISD::OR: 5876 case ISD::XOR: 5877 case ISD::ADD: 5878 case ISD::SUB: 5879 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5880 assert(N1.getValueType() == N2.getValueType() && 5881 N1.getValueType() == VT && "Binary operator types must match!"); 5882 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5883 // it's worth handling here. 5884 if (N2CV && N2CV->isZero()) 5885 return N1; 5886 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5887 VT.getVectorElementType() == MVT::i1) 5888 return getNode(ISD::XOR, DL, VT, N1, N2); 5889 break; 5890 case ISD::MUL: 5891 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5892 assert(N1.getValueType() == N2.getValueType() && 5893 N1.getValueType() == VT && "Binary operator types must match!"); 5894 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5895 return getNode(ISD::AND, DL, VT, N1, N2); 5896 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5897 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5898 const APInt &N2CImm = N2C->getAPIntValue(); 5899 return getVScale(DL, VT, MulImm * N2CImm); 5900 } 5901 break; 5902 case ISD::UDIV: 5903 case ISD::UREM: 5904 case ISD::MULHU: 5905 case ISD::MULHS: 5906 case ISD::SDIV: 5907 case ISD::SREM: 5908 case ISD::SADDSAT: 5909 case ISD::SSUBSAT: 5910 case ISD::UADDSAT: 5911 case ISD::USUBSAT: 5912 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5913 assert(N1.getValueType() == N2.getValueType() && 5914 N1.getValueType() == VT && "Binary operator types must match!"); 5915 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5916 // fold (add_sat x, y) -> (or x, y) for bool types. 5917 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5918 return getNode(ISD::OR, DL, VT, N1, N2); 5919 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5920 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5921 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5922 } 5923 break; 5924 case ISD::SMIN: 5925 case ISD::UMAX: 5926 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5927 assert(N1.getValueType() == N2.getValueType() && 5928 N1.getValueType() == VT && "Binary operator types must match!"); 5929 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5930 return getNode(ISD::OR, DL, VT, N1, N2); 5931 break; 5932 case ISD::SMAX: 5933 case ISD::UMIN: 5934 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5935 assert(N1.getValueType() == N2.getValueType() && 5936 N1.getValueType() == VT && "Binary operator types must match!"); 5937 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5938 return getNode(ISD::AND, DL, VT, N1, N2); 5939 break; 5940 case ISD::FADD: 5941 case ISD::FSUB: 5942 case ISD::FMUL: 5943 case ISD::FDIV: 5944 case ISD::FREM: 5945 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5946 assert(N1.getValueType() == N2.getValueType() && 5947 N1.getValueType() == VT && "Binary operator types must match!"); 5948 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5949 return V; 5950 break; 5951 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5952 assert(N1.getValueType() == VT && 5953 N1.getValueType().isFloatingPoint() && 5954 N2.getValueType().isFloatingPoint() && 5955 "Invalid FCOPYSIGN!"); 5956 break; 5957 case ISD::SHL: 5958 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5959 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5960 const APInt &ShiftImm = N2C->getAPIntValue(); 5961 return getVScale(DL, VT, MulImm << ShiftImm); 5962 } 5963 LLVM_FALLTHROUGH; 5964 case ISD::SRA: 5965 case ISD::SRL: 5966 if (SDValue V = simplifyShift(N1, N2)) 5967 return V; 5968 LLVM_FALLTHROUGH; 5969 case ISD::ROTL: 5970 case ISD::ROTR: 5971 assert(VT == N1.getValueType() && 5972 "Shift operators return type must be the same as their first arg"); 5973 assert(VT.isInteger() && N2.getValueType().isInteger() && 5974 "Shifts only work on integers"); 5975 assert((!VT.isVector() || VT == N2.getValueType()) && 5976 "Vector shift amounts must be in the same as their first arg"); 5977 // Verify that the shift amount VT is big enough to hold valid shift 5978 // amounts. This catches things like trying to shift an i1024 value by an 5979 // i8, which is easy to fall into in generic code that uses 5980 // TLI.getShiftAmount(). 5981 assert(N2.getValueType().getScalarSizeInBits() >= 5982 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5983 "Invalid use of small shift amount with oversized value!"); 5984 5985 // Always fold shifts of i1 values so the code generator doesn't need to 5986 // handle them. Since we know the size of the shift has to be less than the 5987 // size of the value, the shift/rotate count is guaranteed to be zero. 5988 if (VT == MVT::i1) 5989 return N1; 5990 if (N2CV && N2CV->isZero()) 5991 return N1; 5992 break; 5993 case ISD::FP_ROUND: 5994 assert(VT.isFloatingPoint() && 5995 N1.getValueType().isFloatingPoint() && 5996 VT.bitsLE(N1.getValueType()) && 5997 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5998 "Invalid FP_ROUND!"); 5999 if (N1.getValueType() == VT) return N1; // noop conversion. 6000 break; 6001 case ISD::AssertSext: 6002 case ISD::AssertZext: { 6003 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6004 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6005 assert(VT.isInteger() && EVT.isInteger() && 6006 "Cannot *_EXTEND_INREG FP types"); 6007 assert(!EVT.isVector() && 6008 "AssertSExt/AssertZExt type should be the vector element type " 6009 "rather than the vector type!"); 6010 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 6011 if (VT.getScalarType() == EVT) return N1; // noop assertion. 6012 break; 6013 } 6014 case ISD::SIGN_EXTEND_INREG: { 6015 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6016 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6017 assert(VT.isInteger() && EVT.isInteger() && 6018 "Cannot *_EXTEND_INREG FP types"); 6019 assert(EVT.isVector() == VT.isVector() && 6020 "SIGN_EXTEND_INREG type should be vector iff the operand " 6021 "type is vector!"); 6022 assert((!EVT.isVector() || 6023 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 6024 "Vector element counts must match in SIGN_EXTEND_INREG"); 6025 assert(EVT.bitsLE(VT) && "Not extending!"); 6026 if (EVT == VT) return N1; // Not actually extending 6027 6028 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 6029 unsigned FromBits = EVT.getScalarSizeInBits(); 6030 Val <<= Val.getBitWidth() - FromBits; 6031 Val.ashrInPlace(Val.getBitWidth() - FromBits); 6032 return getConstant(Val, DL, ConstantVT); 6033 }; 6034 6035 if (N1C) { 6036 const APInt &Val = N1C->getAPIntValue(); 6037 return SignExtendInReg(Val, VT); 6038 } 6039 6040 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 6041 SmallVector<SDValue, 8> Ops; 6042 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 6043 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6044 SDValue Op = N1.getOperand(i); 6045 if (Op.isUndef()) { 6046 Ops.push_back(getUNDEF(OpVT)); 6047 continue; 6048 } 6049 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6050 APInt Val = C->getAPIntValue(); 6051 Ops.push_back(SignExtendInReg(Val, OpVT)); 6052 } 6053 return getBuildVector(VT, DL, Ops); 6054 } 6055 break; 6056 } 6057 case ISD::FP_TO_SINT_SAT: 6058 case ISD::FP_TO_UINT_SAT: { 6059 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6060 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6061 assert(N1.getValueType().isVector() == VT.isVector() && 6062 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6063 "vector!"); 6064 assert((!VT.isVector() || VT.getVectorNumElements() == 6065 N1.getValueType().getVectorNumElements()) && 6066 "Vector element counts must match in FP_TO_*INT_SAT"); 6067 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6068 "Type to saturate to must be a scalar."); 6069 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6070 "Not extending!"); 6071 break; 6072 } 6073 case ISD::EXTRACT_VECTOR_ELT: 6074 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6075 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6076 element type of the vector."); 6077 6078 // Extract from an undefined value or using an undefined index is undefined. 6079 if (N1.isUndef() || N2.isUndef()) 6080 return getUNDEF(VT); 6081 6082 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6083 // vectors. For scalable vectors we will provide appropriate support for 6084 // dealing with arbitrary indices. 6085 if (N2C && N1.getValueType().isFixedLengthVector() && 6086 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6087 return getUNDEF(VT); 6088 6089 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6090 // expanding copies of large vectors from registers. This only works for 6091 // fixed length vectors, since we need to know the exact number of 6092 // elements. 6093 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6094 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6095 unsigned Factor = 6096 N1.getOperand(0).getValueType().getVectorNumElements(); 6097 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6098 N1.getOperand(N2C->getZExtValue() / Factor), 6099 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6100 } 6101 6102 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6103 // lowering is expanding large vector constants. 6104 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6105 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6106 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6107 N1.getValueType().isFixedLengthVector()) && 6108 "BUILD_VECTOR used for scalable vectors"); 6109 unsigned Index = 6110 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6111 SDValue Elt = N1.getOperand(Index); 6112 6113 if (VT != Elt.getValueType()) 6114 // If the vector element type is not legal, the BUILD_VECTOR operands 6115 // are promoted and implicitly truncated, and the result implicitly 6116 // extended. Make that explicit here. 6117 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6118 6119 return Elt; 6120 } 6121 6122 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6123 // operations are lowered to scalars. 6124 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6125 // If the indices are the same, return the inserted element else 6126 // if the indices are known different, extract the element from 6127 // the original vector. 6128 SDValue N1Op2 = N1.getOperand(2); 6129 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6130 6131 if (N1Op2C && N2C) { 6132 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6133 if (VT == N1.getOperand(1).getValueType()) 6134 return N1.getOperand(1); 6135 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6136 } 6137 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6138 } 6139 } 6140 6141 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6142 // when vector types are scalarized and v1iX is legal. 6143 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6144 // Here we are completely ignoring the extract element index (N2), 6145 // which is fine for fixed width vectors, since any index other than 0 6146 // is undefined anyway. However, this cannot be ignored for scalable 6147 // vectors - in theory we could support this, but we don't want to do this 6148 // without a profitability check. 6149 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6150 N1.getValueType().isFixedLengthVector() && 6151 N1.getValueType().getVectorNumElements() == 1) { 6152 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6153 N1.getOperand(1)); 6154 } 6155 break; 6156 case ISD::EXTRACT_ELEMENT: 6157 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6158 assert(!N1.getValueType().isVector() && !VT.isVector() && 6159 (N1.getValueType().isInteger() == VT.isInteger()) && 6160 N1.getValueType() != VT && 6161 "Wrong types for EXTRACT_ELEMENT!"); 6162 6163 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6164 // 64-bit integers into 32-bit parts. Instead of building the extract of 6165 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6166 if (N1.getOpcode() == ISD::BUILD_PAIR) 6167 return N1.getOperand(N2C->getZExtValue()); 6168 6169 // EXTRACT_ELEMENT of a constant int is also very common. 6170 if (N1C) { 6171 unsigned ElementSize = VT.getSizeInBits(); 6172 unsigned Shift = ElementSize * N2C->getZExtValue(); 6173 const APInt &Val = N1C->getAPIntValue(); 6174 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6175 } 6176 break; 6177 case ISD::EXTRACT_SUBVECTOR: { 6178 EVT N1VT = N1.getValueType(); 6179 assert(VT.isVector() && N1VT.isVector() && 6180 "Extract subvector VTs must be vectors!"); 6181 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6182 "Extract subvector VTs must have the same element type!"); 6183 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6184 "Cannot extract a scalable vector from a fixed length vector!"); 6185 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6186 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6187 "Extract subvector must be from larger vector to smaller vector!"); 6188 assert(N2C && "Extract subvector index must be a constant"); 6189 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6190 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6191 N1VT.getVectorMinNumElements()) && 6192 "Extract subvector overflow!"); 6193 assert(N2C->getAPIntValue().getBitWidth() == 6194 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6195 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6196 6197 // Trivial extraction. 6198 if (VT == N1VT) 6199 return N1; 6200 6201 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6202 if (N1.isUndef()) 6203 return getUNDEF(VT); 6204 6205 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6206 // the concat have the same type as the extract. 6207 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6208 VT == N1.getOperand(0).getValueType()) { 6209 unsigned Factor = VT.getVectorMinNumElements(); 6210 return N1.getOperand(N2C->getZExtValue() / Factor); 6211 } 6212 6213 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6214 // during shuffle legalization. 6215 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6216 VT == N1.getOperand(1).getValueType()) 6217 return N1.getOperand(1); 6218 break; 6219 } 6220 } 6221 6222 // Perform trivial constant folding. 6223 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6224 return SV; 6225 6226 // Canonicalize an UNDEF to the RHS, even over a constant. 6227 if (N1.isUndef()) { 6228 if (TLI->isCommutativeBinOp(Opcode)) { 6229 std::swap(N1, N2); 6230 } else { 6231 switch (Opcode) { 6232 case ISD::SUB: 6233 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6234 case ISD::SIGN_EXTEND_INREG: 6235 case ISD::UDIV: 6236 case ISD::SDIV: 6237 case ISD::UREM: 6238 case ISD::SREM: 6239 case ISD::SSUBSAT: 6240 case ISD::USUBSAT: 6241 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6242 } 6243 } 6244 } 6245 6246 // Fold a bunch of operators when the RHS is undef. 6247 if (N2.isUndef()) { 6248 switch (Opcode) { 6249 case ISD::XOR: 6250 if (N1.isUndef()) 6251 // Handle undef ^ undef -> 0 special case. This is a common 6252 // idiom (misuse). 6253 return getConstant(0, DL, VT); 6254 LLVM_FALLTHROUGH; 6255 case ISD::ADD: 6256 case ISD::SUB: 6257 case ISD::UDIV: 6258 case ISD::SDIV: 6259 case ISD::UREM: 6260 case ISD::SREM: 6261 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6262 case ISD::MUL: 6263 case ISD::AND: 6264 case ISD::SSUBSAT: 6265 case ISD::USUBSAT: 6266 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6267 case ISD::OR: 6268 case ISD::SADDSAT: 6269 case ISD::UADDSAT: 6270 return getAllOnesConstant(DL, VT); 6271 } 6272 } 6273 6274 // Memoize this node if possible. 6275 SDNode *N; 6276 SDVTList VTs = getVTList(VT); 6277 SDValue Ops[] = {N1, N2}; 6278 if (VT != MVT::Glue) { 6279 FoldingSetNodeID ID; 6280 AddNodeIDNode(ID, Opcode, VTs, Ops); 6281 void *IP = nullptr; 6282 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6283 E->intersectFlagsWith(Flags); 6284 return SDValue(E, 0); 6285 } 6286 6287 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6288 N->setFlags(Flags); 6289 createOperands(N, Ops); 6290 CSEMap.InsertNode(N, IP); 6291 } else { 6292 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6293 createOperands(N, Ops); 6294 } 6295 6296 InsertNode(N); 6297 SDValue V = SDValue(N, 0); 6298 NewSDValueDbgMsg(V, "Creating new node: ", this); 6299 return V; 6300 } 6301 6302 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6303 SDValue N1, SDValue N2, SDValue N3) { 6304 SDNodeFlags Flags; 6305 if (Inserter) 6306 Flags = Inserter->getFlags(); 6307 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6308 } 6309 6310 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6311 SDValue N1, SDValue N2, SDValue N3, 6312 const SDNodeFlags Flags) { 6313 assert(N1.getOpcode() != ISD::DELETED_NODE && 6314 N2.getOpcode() != ISD::DELETED_NODE && 6315 N3.getOpcode() != ISD::DELETED_NODE && 6316 "Operand is DELETED_NODE!"); 6317 // Perform various simplifications. 6318 switch (Opcode) { 6319 case ISD::FMA: { 6320 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6321 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6322 N3.getValueType() == VT && "FMA types must match!"); 6323 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6324 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6325 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6326 if (N1CFP && N2CFP && N3CFP) { 6327 APFloat V1 = N1CFP->getValueAPF(); 6328 const APFloat &V2 = N2CFP->getValueAPF(); 6329 const APFloat &V3 = N3CFP->getValueAPF(); 6330 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6331 return getConstantFP(V1, DL, VT); 6332 } 6333 break; 6334 } 6335 case ISD::BUILD_VECTOR: { 6336 // Attempt to simplify BUILD_VECTOR. 6337 SDValue Ops[] = {N1, N2, N3}; 6338 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6339 return V; 6340 break; 6341 } 6342 case ISD::CONCAT_VECTORS: { 6343 SDValue Ops[] = {N1, N2, N3}; 6344 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6345 return V; 6346 break; 6347 } 6348 case ISD::SETCC: { 6349 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6350 assert(N1.getValueType() == N2.getValueType() && 6351 "SETCC operands must have the same type!"); 6352 assert(VT.isVector() == N1.getValueType().isVector() && 6353 "SETCC type should be vector iff the operand type is vector!"); 6354 assert((!VT.isVector() || VT.getVectorElementCount() == 6355 N1.getValueType().getVectorElementCount()) && 6356 "SETCC vector element counts must match!"); 6357 // Use FoldSetCC to simplify SETCC's. 6358 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6359 return V; 6360 // Vector constant folding. 6361 SDValue Ops[] = {N1, N2, N3}; 6362 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6363 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6364 return V; 6365 } 6366 break; 6367 } 6368 case ISD::SELECT: 6369 case ISD::VSELECT: 6370 if (SDValue V = simplifySelect(N1, N2, N3)) 6371 return V; 6372 break; 6373 case ISD::VECTOR_SHUFFLE: 6374 llvm_unreachable("should use getVectorShuffle constructor!"); 6375 case ISD::VECTOR_SPLICE: { 6376 if (cast<ConstantSDNode>(N3)->isNullValue()) 6377 return N1; 6378 break; 6379 } 6380 case ISD::INSERT_VECTOR_ELT: { 6381 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6382 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6383 // for scalable vectors where we will generate appropriate code to 6384 // deal with out-of-bounds cases correctly. 6385 if (N3C && N1.getValueType().isFixedLengthVector() && 6386 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6387 return getUNDEF(VT); 6388 6389 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6390 if (N3.isUndef()) 6391 return getUNDEF(VT); 6392 6393 // If the inserted element is an UNDEF, just use the input vector. 6394 if (N2.isUndef()) 6395 return N1; 6396 6397 break; 6398 } 6399 case ISD::INSERT_SUBVECTOR: { 6400 // Inserting undef into undef is still undef. 6401 if (N1.isUndef() && N2.isUndef()) 6402 return getUNDEF(VT); 6403 6404 EVT N2VT = N2.getValueType(); 6405 assert(VT == N1.getValueType() && 6406 "Dest and insert subvector source types must match!"); 6407 assert(VT.isVector() && N2VT.isVector() && 6408 "Insert subvector VTs must be vectors!"); 6409 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6410 "Cannot insert a scalable vector into a fixed length vector!"); 6411 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6412 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6413 "Insert subvector must be from smaller vector to larger vector!"); 6414 assert(isa<ConstantSDNode>(N3) && 6415 "Insert subvector index must be constant"); 6416 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6417 (N2VT.getVectorMinNumElements() + 6418 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6419 VT.getVectorMinNumElements()) && 6420 "Insert subvector overflow!"); 6421 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6422 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6423 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6424 6425 // Trivial insertion. 6426 if (VT == N2VT) 6427 return N2; 6428 6429 // If this is an insert of an extracted vector into an undef vector, we 6430 // can just use the input to the extract. 6431 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6432 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6433 return N2.getOperand(0); 6434 break; 6435 } 6436 case ISD::BITCAST: 6437 // Fold bit_convert nodes from a type to themselves. 6438 if (N1.getValueType() == VT) 6439 return N1; 6440 break; 6441 } 6442 6443 // Memoize node if it doesn't produce a flag. 6444 SDNode *N; 6445 SDVTList VTs = getVTList(VT); 6446 SDValue Ops[] = {N1, N2, N3}; 6447 if (VT != MVT::Glue) { 6448 FoldingSetNodeID ID; 6449 AddNodeIDNode(ID, Opcode, VTs, Ops); 6450 void *IP = nullptr; 6451 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6452 E->intersectFlagsWith(Flags); 6453 return SDValue(E, 0); 6454 } 6455 6456 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6457 N->setFlags(Flags); 6458 createOperands(N, Ops); 6459 CSEMap.InsertNode(N, IP); 6460 } else { 6461 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6462 createOperands(N, Ops); 6463 } 6464 6465 InsertNode(N); 6466 SDValue V = SDValue(N, 0); 6467 NewSDValueDbgMsg(V, "Creating new node: ", this); 6468 return V; 6469 } 6470 6471 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6472 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6473 SDValue Ops[] = { N1, N2, N3, N4 }; 6474 return getNode(Opcode, DL, VT, Ops); 6475 } 6476 6477 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6478 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6479 SDValue N5) { 6480 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6481 return getNode(Opcode, DL, VT, Ops); 6482 } 6483 6484 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6485 /// the incoming stack arguments to be loaded from the stack. 6486 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6487 SmallVector<SDValue, 8> ArgChains; 6488 6489 // Include the original chain at the beginning of the list. When this is 6490 // used by target LowerCall hooks, this helps legalize find the 6491 // CALLSEQ_BEGIN node. 6492 ArgChains.push_back(Chain); 6493 6494 // Add a chain value for each stack argument. 6495 for (SDNode *U : getEntryNode().getNode()->uses()) 6496 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6497 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6498 if (FI->getIndex() < 0) 6499 ArgChains.push_back(SDValue(L, 1)); 6500 6501 // Build a tokenfactor for all the chains. 6502 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6503 } 6504 6505 /// getMemsetValue - Vectorized representation of the memset value 6506 /// operand. 6507 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6508 const SDLoc &dl) { 6509 assert(!Value.isUndef()); 6510 6511 unsigned NumBits = VT.getScalarSizeInBits(); 6512 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6513 assert(C->getAPIntValue().getBitWidth() == 8); 6514 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6515 if (VT.isInteger()) { 6516 bool IsOpaque = VT.getSizeInBits() > 64 || 6517 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6518 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6519 } 6520 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6521 VT); 6522 } 6523 6524 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6525 EVT IntVT = VT.getScalarType(); 6526 if (!IntVT.isInteger()) 6527 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6528 6529 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6530 if (NumBits > 8) { 6531 // Use a multiplication with 0x010101... to extend the input to the 6532 // required length. 6533 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6534 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6535 DAG.getConstant(Magic, dl, IntVT)); 6536 } 6537 6538 if (VT != Value.getValueType() && !VT.isInteger()) 6539 Value = DAG.getBitcast(VT.getScalarType(), Value); 6540 if (VT != Value.getValueType()) 6541 Value = DAG.getSplatBuildVector(VT, dl, Value); 6542 6543 return Value; 6544 } 6545 6546 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6547 /// used when a memcpy is turned into a memset when the source is a constant 6548 /// string ptr. 6549 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6550 const TargetLowering &TLI, 6551 const ConstantDataArraySlice &Slice) { 6552 // Handle vector with all elements zero. 6553 if (Slice.Array == nullptr) { 6554 if (VT.isInteger()) 6555 return DAG.getConstant(0, dl, VT); 6556 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6557 return DAG.getConstantFP(0.0, dl, VT); 6558 if (VT.isVector()) { 6559 unsigned NumElts = VT.getVectorNumElements(); 6560 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6561 return DAG.getNode(ISD::BITCAST, dl, VT, 6562 DAG.getConstant(0, dl, 6563 EVT::getVectorVT(*DAG.getContext(), 6564 EltVT, NumElts))); 6565 } 6566 llvm_unreachable("Expected type!"); 6567 } 6568 6569 assert(!VT.isVector() && "Can't handle vector type here!"); 6570 unsigned NumVTBits = VT.getSizeInBits(); 6571 unsigned NumVTBytes = NumVTBits / 8; 6572 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6573 6574 APInt Val(NumVTBits, 0); 6575 if (DAG.getDataLayout().isLittleEndian()) { 6576 for (unsigned i = 0; i != NumBytes; ++i) 6577 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6578 } else { 6579 for (unsigned i = 0; i != NumBytes; ++i) 6580 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6581 } 6582 6583 // If the "cost" of materializing the integer immediate is less than the cost 6584 // of a load, then it is cost effective to turn the load into the immediate. 6585 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6586 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6587 return DAG.getConstant(Val, dl, VT); 6588 return SDValue(); 6589 } 6590 6591 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6592 const SDLoc &DL, 6593 const SDNodeFlags Flags) { 6594 EVT VT = Base.getValueType(); 6595 SDValue Index; 6596 6597 if (Offset.isScalable()) 6598 Index = getVScale(DL, Base.getValueType(), 6599 APInt(Base.getValueSizeInBits().getFixedSize(), 6600 Offset.getKnownMinSize())); 6601 else 6602 Index = getConstant(Offset.getFixedSize(), DL, VT); 6603 6604 return getMemBasePlusOffset(Base, Index, DL, Flags); 6605 } 6606 6607 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6608 const SDLoc &DL, 6609 const SDNodeFlags Flags) { 6610 assert(Offset.getValueType().isInteger()); 6611 EVT BasePtrVT = Ptr.getValueType(); 6612 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6613 } 6614 6615 /// Returns true if memcpy source is constant data. 6616 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6617 uint64_t SrcDelta = 0; 6618 GlobalAddressSDNode *G = nullptr; 6619 if (Src.getOpcode() == ISD::GlobalAddress) 6620 G = cast<GlobalAddressSDNode>(Src); 6621 else if (Src.getOpcode() == ISD::ADD && 6622 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6623 Src.getOperand(1).getOpcode() == ISD::Constant) { 6624 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6625 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6626 } 6627 if (!G) 6628 return false; 6629 6630 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6631 SrcDelta + G->getOffset()); 6632 } 6633 6634 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6635 SelectionDAG &DAG) { 6636 // On Darwin, -Os means optimize for size without hurting performance, so 6637 // only really optimize for size when -Oz (MinSize) is used. 6638 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6639 return MF.getFunction().hasMinSize(); 6640 return DAG.shouldOptForSize(); 6641 } 6642 6643 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6644 SmallVector<SDValue, 32> &OutChains, unsigned From, 6645 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6646 SmallVector<SDValue, 16> &OutStoreChains) { 6647 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6648 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6649 SmallVector<SDValue, 16> GluedLoadChains; 6650 for (unsigned i = From; i < To; ++i) { 6651 OutChains.push_back(OutLoadChains[i]); 6652 GluedLoadChains.push_back(OutLoadChains[i]); 6653 } 6654 6655 // Chain for all loads. 6656 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6657 GluedLoadChains); 6658 6659 for (unsigned i = From; i < To; ++i) { 6660 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6661 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6662 ST->getBasePtr(), ST->getMemoryVT(), 6663 ST->getMemOperand()); 6664 OutChains.push_back(NewStore); 6665 } 6666 } 6667 6668 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6669 SDValue Chain, SDValue Dst, SDValue Src, 6670 uint64_t Size, Align Alignment, 6671 bool isVol, bool AlwaysInline, 6672 MachinePointerInfo DstPtrInfo, 6673 MachinePointerInfo SrcPtrInfo, 6674 const AAMDNodes &AAInfo) { 6675 // Turn a memcpy of undef to nop. 6676 // FIXME: We need to honor volatile even is Src is undef. 6677 if (Src.isUndef()) 6678 return Chain; 6679 6680 // Expand memcpy to a series of load and store ops if the size operand falls 6681 // below a certain threshold. 6682 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6683 // rather than maybe a humongous number of loads and stores. 6684 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6685 const DataLayout &DL = DAG.getDataLayout(); 6686 LLVMContext &C = *DAG.getContext(); 6687 std::vector<EVT> MemOps; 6688 bool DstAlignCanChange = false; 6689 MachineFunction &MF = DAG.getMachineFunction(); 6690 MachineFrameInfo &MFI = MF.getFrameInfo(); 6691 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6692 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6693 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6694 DstAlignCanChange = true; 6695 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6696 if (!SrcAlign || Alignment > *SrcAlign) 6697 SrcAlign = Alignment; 6698 assert(SrcAlign && "SrcAlign must be set"); 6699 ConstantDataArraySlice Slice; 6700 // If marked as volatile, perform a copy even when marked as constant. 6701 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6702 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6703 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6704 const MemOp Op = isZeroConstant 6705 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6706 /*IsZeroMemset*/ true, isVol) 6707 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6708 *SrcAlign, isVol, CopyFromConstant); 6709 if (!TLI.findOptimalMemOpLowering( 6710 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6711 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6712 return SDValue(); 6713 6714 if (DstAlignCanChange) { 6715 Type *Ty = MemOps[0].getTypeForEVT(C); 6716 Align NewAlign = DL.getABITypeAlign(Ty); 6717 6718 // Don't promote to an alignment that would require dynamic stack 6719 // realignment. 6720 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6721 if (!TRI->hasStackRealignment(MF)) 6722 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6723 NewAlign = NewAlign / 2; 6724 6725 if (NewAlign > Alignment) { 6726 // Give the stack frame object a larger alignment if needed. 6727 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6728 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6729 Alignment = NewAlign; 6730 } 6731 } 6732 6733 // Prepare AAInfo for loads/stores after lowering this memcpy. 6734 AAMDNodes NewAAInfo = AAInfo; 6735 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6736 6737 MachineMemOperand::Flags MMOFlags = 6738 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6739 SmallVector<SDValue, 16> OutLoadChains; 6740 SmallVector<SDValue, 16> OutStoreChains; 6741 SmallVector<SDValue, 32> OutChains; 6742 unsigned NumMemOps = MemOps.size(); 6743 uint64_t SrcOff = 0, DstOff = 0; 6744 for (unsigned i = 0; i != NumMemOps; ++i) { 6745 EVT VT = MemOps[i]; 6746 unsigned VTSize = VT.getSizeInBits() / 8; 6747 SDValue Value, Store; 6748 6749 if (VTSize > Size) { 6750 // Issuing an unaligned load / store pair that overlaps with the previous 6751 // pair. Adjust the offset accordingly. 6752 assert(i == NumMemOps-1 && i != 0); 6753 SrcOff -= VTSize - Size; 6754 DstOff -= VTSize - Size; 6755 } 6756 6757 if (CopyFromConstant && 6758 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6759 // It's unlikely a store of a vector immediate can be done in a single 6760 // instruction. It would require a load from a constantpool first. 6761 // We only handle zero vectors here. 6762 // FIXME: Handle other cases where store of vector immediate is done in 6763 // a single instruction. 6764 ConstantDataArraySlice SubSlice; 6765 if (SrcOff < Slice.Length) { 6766 SubSlice = Slice; 6767 SubSlice.move(SrcOff); 6768 } else { 6769 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6770 SubSlice.Array = nullptr; 6771 SubSlice.Offset = 0; 6772 SubSlice.Length = VTSize; 6773 } 6774 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6775 if (Value.getNode()) { 6776 Store = DAG.getStore( 6777 Chain, dl, Value, 6778 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6779 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6780 OutChains.push_back(Store); 6781 } 6782 } 6783 6784 if (!Store.getNode()) { 6785 // The type might not be legal for the target. This should only happen 6786 // if the type is smaller than a legal type, as on PPC, so the right 6787 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6788 // to Load/Store if NVT==VT. 6789 // FIXME does the case above also need this? 6790 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6791 assert(NVT.bitsGE(VT)); 6792 6793 bool isDereferenceable = 6794 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6795 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6796 if (isDereferenceable) 6797 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6798 6799 Value = DAG.getExtLoad( 6800 ISD::EXTLOAD, dl, NVT, Chain, 6801 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6802 SrcPtrInfo.getWithOffset(SrcOff), VT, 6803 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6804 OutLoadChains.push_back(Value.getValue(1)); 6805 6806 Store = DAG.getTruncStore( 6807 Chain, dl, Value, 6808 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6809 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6810 OutStoreChains.push_back(Store); 6811 } 6812 SrcOff += VTSize; 6813 DstOff += VTSize; 6814 Size -= VTSize; 6815 } 6816 6817 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6818 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6819 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6820 6821 if (NumLdStInMemcpy) { 6822 // It may be that memcpy might be converted to memset if it's memcpy 6823 // of constants. In such a case, we won't have loads and stores, but 6824 // just stores. In the absence of loads, there is nothing to gang up. 6825 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6826 // If target does not care, just leave as it. 6827 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6828 OutChains.push_back(OutLoadChains[i]); 6829 OutChains.push_back(OutStoreChains[i]); 6830 } 6831 } else { 6832 // Ld/St less than/equal limit set by target. 6833 if (NumLdStInMemcpy <= GluedLdStLimit) { 6834 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6835 NumLdStInMemcpy, OutLoadChains, 6836 OutStoreChains); 6837 } else { 6838 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6839 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6840 unsigned GlueIter = 0; 6841 6842 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6843 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6844 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6845 6846 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6847 OutLoadChains, OutStoreChains); 6848 GlueIter += GluedLdStLimit; 6849 } 6850 6851 // Residual ld/st. 6852 if (RemainingLdStInMemcpy) { 6853 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6854 RemainingLdStInMemcpy, OutLoadChains, 6855 OutStoreChains); 6856 } 6857 } 6858 } 6859 } 6860 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6861 } 6862 6863 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6864 SDValue Chain, SDValue Dst, SDValue Src, 6865 uint64_t Size, Align Alignment, 6866 bool isVol, bool AlwaysInline, 6867 MachinePointerInfo DstPtrInfo, 6868 MachinePointerInfo SrcPtrInfo, 6869 const AAMDNodes &AAInfo) { 6870 // Turn a memmove of undef to nop. 6871 // FIXME: We need to honor volatile even is Src is undef. 6872 if (Src.isUndef()) 6873 return Chain; 6874 6875 // Expand memmove to a series of load and store ops if the size operand falls 6876 // below a certain threshold. 6877 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6878 const DataLayout &DL = DAG.getDataLayout(); 6879 LLVMContext &C = *DAG.getContext(); 6880 std::vector<EVT> MemOps; 6881 bool DstAlignCanChange = false; 6882 MachineFunction &MF = DAG.getMachineFunction(); 6883 MachineFrameInfo &MFI = MF.getFrameInfo(); 6884 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6885 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6886 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6887 DstAlignCanChange = true; 6888 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6889 if (!SrcAlign || Alignment > *SrcAlign) 6890 SrcAlign = Alignment; 6891 assert(SrcAlign && "SrcAlign must be set"); 6892 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6893 if (!TLI.findOptimalMemOpLowering( 6894 MemOps, Limit, 6895 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6896 /*IsVolatile*/ true), 6897 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6898 MF.getFunction().getAttributes())) 6899 return SDValue(); 6900 6901 if (DstAlignCanChange) { 6902 Type *Ty = MemOps[0].getTypeForEVT(C); 6903 Align NewAlign = DL.getABITypeAlign(Ty); 6904 if (NewAlign > Alignment) { 6905 // Give the stack frame object a larger alignment if needed. 6906 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6907 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6908 Alignment = NewAlign; 6909 } 6910 } 6911 6912 // Prepare AAInfo for loads/stores after lowering this memmove. 6913 AAMDNodes NewAAInfo = AAInfo; 6914 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6915 6916 MachineMemOperand::Flags MMOFlags = 6917 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6918 uint64_t SrcOff = 0, DstOff = 0; 6919 SmallVector<SDValue, 8> LoadValues; 6920 SmallVector<SDValue, 8> LoadChains; 6921 SmallVector<SDValue, 8> OutChains; 6922 unsigned NumMemOps = MemOps.size(); 6923 for (unsigned i = 0; i < NumMemOps; i++) { 6924 EVT VT = MemOps[i]; 6925 unsigned VTSize = VT.getSizeInBits() / 8; 6926 SDValue Value; 6927 6928 bool isDereferenceable = 6929 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6930 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6931 if (isDereferenceable) 6932 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6933 6934 Value = DAG.getLoad( 6935 VT, dl, Chain, 6936 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6937 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6938 LoadValues.push_back(Value); 6939 LoadChains.push_back(Value.getValue(1)); 6940 SrcOff += VTSize; 6941 } 6942 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6943 OutChains.clear(); 6944 for (unsigned i = 0; i < NumMemOps; i++) { 6945 EVT VT = MemOps[i]; 6946 unsigned VTSize = VT.getSizeInBits() / 8; 6947 SDValue Store; 6948 6949 Store = DAG.getStore( 6950 Chain, dl, LoadValues[i], 6951 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6952 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6953 OutChains.push_back(Store); 6954 DstOff += VTSize; 6955 } 6956 6957 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6958 } 6959 6960 /// Lower the call to 'memset' intrinsic function into a series of store 6961 /// operations. 6962 /// 6963 /// \param DAG Selection DAG where lowered code is placed. 6964 /// \param dl Link to corresponding IR location. 6965 /// \param Chain Control flow dependency. 6966 /// \param Dst Pointer to destination memory location. 6967 /// \param Src Value of byte to write into the memory. 6968 /// \param Size Number of bytes to write. 6969 /// \param Alignment Alignment of the destination in bytes. 6970 /// \param isVol True if destination is volatile. 6971 /// \param DstPtrInfo IR information on the memory pointer. 6972 /// \returns New head in the control flow, if lowering was successful, empty 6973 /// SDValue otherwise. 6974 /// 6975 /// The function tries to replace 'llvm.memset' intrinsic with several store 6976 /// operations and value calculation code. This is usually profitable for small 6977 /// memory size. 6978 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6979 SDValue Chain, SDValue Dst, SDValue Src, 6980 uint64_t Size, Align Alignment, bool isVol, 6981 MachinePointerInfo DstPtrInfo, 6982 const AAMDNodes &AAInfo) { 6983 // Turn a memset of undef to nop. 6984 // FIXME: We need to honor volatile even is Src is undef. 6985 if (Src.isUndef()) 6986 return Chain; 6987 6988 // Expand memset to a series of load/store ops if the size operand 6989 // falls below a certain threshold. 6990 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6991 std::vector<EVT> MemOps; 6992 bool DstAlignCanChange = false; 6993 MachineFunction &MF = DAG.getMachineFunction(); 6994 MachineFrameInfo &MFI = MF.getFrameInfo(); 6995 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6996 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6997 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6998 DstAlignCanChange = true; 6999 bool IsZeroVal = 7000 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 7001 if (!TLI.findOptimalMemOpLowering( 7002 MemOps, TLI.getMaxStoresPerMemset(OptSize), 7003 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 7004 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 7005 return SDValue(); 7006 7007 if (DstAlignCanChange) { 7008 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 7009 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 7010 if (NewAlign > Alignment) { 7011 // Give the stack frame object a larger alignment if needed. 7012 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7013 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7014 Alignment = NewAlign; 7015 } 7016 } 7017 7018 SmallVector<SDValue, 8> OutChains; 7019 uint64_t DstOff = 0; 7020 unsigned NumMemOps = MemOps.size(); 7021 7022 // Find the largest store and generate the bit pattern for it. 7023 EVT LargestVT = MemOps[0]; 7024 for (unsigned i = 1; i < NumMemOps; i++) 7025 if (MemOps[i].bitsGT(LargestVT)) 7026 LargestVT = MemOps[i]; 7027 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 7028 7029 // Prepare AAInfo for loads/stores after lowering this memset. 7030 AAMDNodes NewAAInfo = AAInfo; 7031 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7032 7033 for (unsigned i = 0; i < NumMemOps; i++) { 7034 EVT VT = MemOps[i]; 7035 unsigned VTSize = VT.getSizeInBits() / 8; 7036 if (VTSize > Size) { 7037 // Issuing an unaligned load / store pair that overlaps with the previous 7038 // pair. Adjust the offset accordingly. 7039 assert(i == NumMemOps-1 && i != 0); 7040 DstOff -= VTSize - Size; 7041 } 7042 7043 // If this store is smaller than the largest store see whether we can get 7044 // the smaller value for free with a truncate. 7045 SDValue Value = MemSetValue; 7046 if (VT.bitsLT(LargestVT)) { 7047 if (!LargestVT.isVector() && !VT.isVector() && 7048 TLI.isTruncateFree(LargestVT, VT)) 7049 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7050 else 7051 Value = getMemsetValue(Src, VT, DAG, dl); 7052 } 7053 assert(Value.getValueType() == VT && "Value with wrong type."); 7054 SDValue Store = DAG.getStore( 7055 Chain, dl, Value, 7056 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7057 DstPtrInfo.getWithOffset(DstOff), Alignment, 7058 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7059 NewAAInfo); 7060 OutChains.push_back(Store); 7061 DstOff += VT.getSizeInBits() / 8; 7062 Size -= VTSize; 7063 } 7064 7065 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7066 } 7067 7068 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7069 unsigned AS) { 7070 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7071 // pointer operands can be losslessly bitcasted to pointers of address space 0 7072 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7073 report_fatal_error("cannot lower memory intrinsic in address space " + 7074 Twine(AS)); 7075 } 7076 } 7077 7078 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7079 SDValue Src, SDValue Size, Align Alignment, 7080 bool isVol, bool AlwaysInline, bool isTailCall, 7081 MachinePointerInfo DstPtrInfo, 7082 MachinePointerInfo SrcPtrInfo, 7083 const AAMDNodes &AAInfo) { 7084 // Check to see if we should lower the memcpy to loads and stores first. 7085 // For cases within the target-specified limits, this is the best choice. 7086 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7087 if (ConstantSize) { 7088 // Memcpy with size zero? Just return the original chain. 7089 if (ConstantSize->isZero()) 7090 return Chain; 7091 7092 SDValue Result = getMemcpyLoadsAndStores( 7093 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7094 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7095 if (Result.getNode()) 7096 return Result; 7097 } 7098 7099 // Then check to see if we should lower the memcpy with target-specific 7100 // code. If the target chooses to do this, this is the next best. 7101 if (TSI) { 7102 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7103 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7104 DstPtrInfo, SrcPtrInfo); 7105 if (Result.getNode()) 7106 return Result; 7107 } 7108 7109 // If we really need inline code and the target declined to provide it, 7110 // use a (potentially long) sequence of loads and stores. 7111 if (AlwaysInline) { 7112 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7113 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 7114 ConstantSize->getZExtValue(), Alignment, 7115 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 7116 } 7117 7118 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7119 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7120 7121 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7122 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7123 // respect volatile, so they may do things like read or write memory 7124 // beyond the given memory regions. But fixing this isn't easy, and most 7125 // people don't care. 7126 7127 // Emit a library call. 7128 TargetLowering::ArgListTy Args; 7129 TargetLowering::ArgListEntry Entry; 7130 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7131 Entry.Node = Dst; Args.push_back(Entry); 7132 Entry.Node = Src; Args.push_back(Entry); 7133 7134 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7135 Entry.Node = Size; Args.push_back(Entry); 7136 // FIXME: pass in SDLoc 7137 TargetLowering::CallLoweringInfo CLI(*this); 7138 CLI.setDebugLoc(dl) 7139 .setChain(Chain) 7140 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7141 Dst.getValueType().getTypeForEVT(*getContext()), 7142 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7143 TLI->getPointerTy(getDataLayout())), 7144 std::move(Args)) 7145 .setDiscardResult() 7146 .setTailCall(isTailCall); 7147 7148 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7149 return CallResult.second; 7150 } 7151 7152 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7153 SDValue Dst, unsigned DstAlign, 7154 SDValue Src, unsigned SrcAlign, 7155 SDValue Size, Type *SizeTy, 7156 unsigned ElemSz, bool isTailCall, 7157 MachinePointerInfo DstPtrInfo, 7158 MachinePointerInfo SrcPtrInfo) { 7159 // Emit a library call. 7160 TargetLowering::ArgListTy Args; 7161 TargetLowering::ArgListEntry Entry; 7162 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7163 Entry.Node = Dst; 7164 Args.push_back(Entry); 7165 7166 Entry.Node = Src; 7167 Args.push_back(Entry); 7168 7169 Entry.Ty = SizeTy; 7170 Entry.Node = Size; 7171 Args.push_back(Entry); 7172 7173 RTLIB::Libcall LibraryCall = 7174 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7175 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7176 report_fatal_error("Unsupported element size"); 7177 7178 TargetLowering::CallLoweringInfo CLI(*this); 7179 CLI.setDebugLoc(dl) 7180 .setChain(Chain) 7181 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7182 Type::getVoidTy(*getContext()), 7183 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7184 TLI->getPointerTy(getDataLayout())), 7185 std::move(Args)) 7186 .setDiscardResult() 7187 .setTailCall(isTailCall); 7188 7189 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7190 return CallResult.second; 7191 } 7192 7193 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7194 SDValue Src, SDValue Size, Align Alignment, 7195 bool isVol, bool isTailCall, 7196 MachinePointerInfo DstPtrInfo, 7197 MachinePointerInfo SrcPtrInfo, 7198 const AAMDNodes &AAInfo) { 7199 // Check to see if we should lower the memmove to loads and stores first. 7200 // For cases within the target-specified limits, this is the best choice. 7201 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7202 if (ConstantSize) { 7203 // Memmove with size zero? Just return the original chain. 7204 if (ConstantSize->isZero()) 7205 return Chain; 7206 7207 SDValue Result = getMemmoveLoadsAndStores( 7208 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7209 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7210 if (Result.getNode()) 7211 return Result; 7212 } 7213 7214 // Then check to see if we should lower the memmove with target-specific 7215 // code. If the target chooses to do this, this is the next best. 7216 if (TSI) { 7217 SDValue Result = 7218 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7219 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7220 if (Result.getNode()) 7221 return Result; 7222 } 7223 7224 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7225 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7226 7227 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7228 // not be safe. See memcpy above for more details. 7229 7230 // Emit a library call. 7231 TargetLowering::ArgListTy Args; 7232 TargetLowering::ArgListEntry Entry; 7233 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7234 Entry.Node = Dst; Args.push_back(Entry); 7235 Entry.Node = Src; Args.push_back(Entry); 7236 7237 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7238 Entry.Node = Size; Args.push_back(Entry); 7239 // FIXME: pass in SDLoc 7240 TargetLowering::CallLoweringInfo CLI(*this); 7241 CLI.setDebugLoc(dl) 7242 .setChain(Chain) 7243 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7244 Dst.getValueType().getTypeForEVT(*getContext()), 7245 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7246 TLI->getPointerTy(getDataLayout())), 7247 std::move(Args)) 7248 .setDiscardResult() 7249 .setTailCall(isTailCall); 7250 7251 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7252 return CallResult.second; 7253 } 7254 7255 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7256 SDValue Dst, unsigned DstAlign, 7257 SDValue Src, unsigned SrcAlign, 7258 SDValue Size, Type *SizeTy, 7259 unsigned ElemSz, bool isTailCall, 7260 MachinePointerInfo DstPtrInfo, 7261 MachinePointerInfo SrcPtrInfo) { 7262 // Emit a library call. 7263 TargetLowering::ArgListTy Args; 7264 TargetLowering::ArgListEntry Entry; 7265 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7266 Entry.Node = Dst; 7267 Args.push_back(Entry); 7268 7269 Entry.Node = Src; 7270 Args.push_back(Entry); 7271 7272 Entry.Ty = SizeTy; 7273 Entry.Node = Size; 7274 Args.push_back(Entry); 7275 7276 RTLIB::Libcall LibraryCall = 7277 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7278 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7279 report_fatal_error("Unsupported element size"); 7280 7281 TargetLowering::CallLoweringInfo CLI(*this); 7282 CLI.setDebugLoc(dl) 7283 .setChain(Chain) 7284 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7285 Type::getVoidTy(*getContext()), 7286 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7287 TLI->getPointerTy(getDataLayout())), 7288 std::move(Args)) 7289 .setDiscardResult() 7290 .setTailCall(isTailCall); 7291 7292 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7293 return CallResult.second; 7294 } 7295 7296 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7297 SDValue Src, SDValue Size, Align Alignment, 7298 bool isVol, bool isTailCall, 7299 MachinePointerInfo DstPtrInfo, 7300 const AAMDNodes &AAInfo) { 7301 // Check to see if we should lower the memset to stores first. 7302 // For cases within the target-specified limits, this is the best choice. 7303 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7304 if (ConstantSize) { 7305 // Memset with size zero? Just return the original chain. 7306 if (ConstantSize->isZero()) 7307 return Chain; 7308 7309 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7310 ConstantSize->getZExtValue(), Alignment, 7311 isVol, DstPtrInfo, AAInfo); 7312 7313 if (Result.getNode()) 7314 return Result; 7315 } 7316 7317 // Then check to see if we should lower the memset with target-specific 7318 // code. If the target chooses to do this, this is the next best. 7319 if (TSI) { 7320 SDValue Result = TSI->EmitTargetCodeForMemset( 7321 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7322 if (Result.getNode()) 7323 return Result; 7324 } 7325 7326 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7327 7328 // Emit a library call. 7329 TargetLowering::ArgListTy Args; 7330 TargetLowering::ArgListEntry Entry; 7331 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7332 Args.push_back(Entry); 7333 Entry.Node = Src; 7334 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7335 Args.push_back(Entry); 7336 Entry.Node = Size; 7337 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7338 Args.push_back(Entry); 7339 7340 // FIXME: pass in SDLoc 7341 TargetLowering::CallLoweringInfo CLI(*this); 7342 CLI.setDebugLoc(dl) 7343 .setChain(Chain) 7344 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7345 Dst.getValueType().getTypeForEVT(*getContext()), 7346 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7347 TLI->getPointerTy(getDataLayout())), 7348 std::move(Args)) 7349 .setDiscardResult() 7350 .setTailCall(isTailCall); 7351 7352 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7353 return CallResult.second; 7354 } 7355 7356 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7357 SDValue Dst, unsigned DstAlign, 7358 SDValue Value, SDValue Size, Type *SizeTy, 7359 unsigned ElemSz, bool isTailCall, 7360 MachinePointerInfo DstPtrInfo) { 7361 // Emit a library call. 7362 TargetLowering::ArgListTy Args; 7363 TargetLowering::ArgListEntry Entry; 7364 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7365 Entry.Node = Dst; 7366 Args.push_back(Entry); 7367 7368 Entry.Ty = Type::getInt8Ty(*getContext()); 7369 Entry.Node = Value; 7370 Args.push_back(Entry); 7371 7372 Entry.Ty = SizeTy; 7373 Entry.Node = Size; 7374 Args.push_back(Entry); 7375 7376 RTLIB::Libcall LibraryCall = 7377 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7378 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7379 report_fatal_error("Unsupported element size"); 7380 7381 TargetLowering::CallLoweringInfo CLI(*this); 7382 CLI.setDebugLoc(dl) 7383 .setChain(Chain) 7384 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7385 Type::getVoidTy(*getContext()), 7386 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7387 TLI->getPointerTy(getDataLayout())), 7388 std::move(Args)) 7389 .setDiscardResult() 7390 .setTailCall(isTailCall); 7391 7392 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7393 return CallResult.second; 7394 } 7395 7396 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7397 SDVTList VTList, ArrayRef<SDValue> Ops, 7398 MachineMemOperand *MMO) { 7399 FoldingSetNodeID ID; 7400 ID.AddInteger(MemVT.getRawBits()); 7401 AddNodeIDNode(ID, Opcode, VTList, Ops); 7402 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7403 ID.AddInteger(MMO->getFlags()); 7404 void* IP = nullptr; 7405 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7406 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7407 return SDValue(E, 0); 7408 } 7409 7410 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7411 VTList, MemVT, MMO); 7412 createOperands(N, Ops); 7413 7414 CSEMap.InsertNode(N, IP); 7415 InsertNode(N); 7416 return SDValue(N, 0); 7417 } 7418 7419 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7420 EVT MemVT, SDVTList VTs, SDValue Chain, 7421 SDValue Ptr, SDValue Cmp, SDValue Swp, 7422 MachineMemOperand *MMO) { 7423 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7424 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7425 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7426 7427 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7428 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7429 } 7430 7431 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7432 SDValue Chain, SDValue Ptr, SDValue Val, 7433 MachineMemOperand *MMO) { 7434 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7435 Opcode == ISD::ATOMIC_LOAD_SUB || 7436 Opcode == ISD::ATOMIC_LOAD_AND || 7437 Opcode == ISD::ATOMIC_LOAD_CLR || 7438 Opcode == ISD::ATOMIC_LOAD_OR || 7439 Opcode == ISD::ATOMIC_LOAD_XOR || 7440 Opcode == ISD::ATOMIC_LOAD_NAND || 7441 Opcode == ISD::ATOMIC_LOAD_MIN || 7442 Opcode == ISD::ATOMIC_LOAD_MAX || 7443 Opcode == ISD::ATOMIC_LOAD_UMIN || 7444 Opcode == ISD::ATOMIC_LOAD_UMAX || 7445 Opcode == ISD::ATOMIC_LOAD_FADD || 7446 Opcode == ISD::ATOMIC_LOAD_FSUB || 7447 Opcode == ISD::ATOMIC_SWAP || 7448 Opcode == ISD::ATOMIC_STORE) && 7449 "Invalid Atomic Op"); 7450 7451 EVT VT = Val.getValueType(); 7452 7453 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7454 getVTList(VT, MVT::Other); 7455 SDValue Ops[] = {Chain, Ptr, Val}; 7456 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7457 } 7458 7459 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7460 EVT VT, SDValue Chain, SDValue Ptr, 7461 MachineMemOperand *MMO) { 7462 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7463 7464 SDVTList VTs = getVTList(VT, MVT::Other); 7465 SDValue Ops[] = {Chain, Ptr}; 7466 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7467 } 7468 7469 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7470 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7471 if (Ops.size() == 1) 7472 return Ops[0]; 7473 7474 SmallVector<EVT, 4> VTs; 7475 VTs.reserve(Ops.size()); 7476 for (const SDValue &Op : Ops) 7477 VTs.push_back(Op.getValueType()); 7478 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7479 } 7480 7481 SDValue SelectionDAG::getMemIntrinsicNode( 7482 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7483 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7484 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7485 if (!Size && MemVT.isScalableVector()) 7486 Size = MemoryLocation::UnknownSize; 7487 else if (!Size) 7488 Size = MemVT.getStoreSize(); 7489 7490 MachineFunction &MF = getMachineFunction(); 7491 MachineMemOperand *MMO = 7492 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7493 7494 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7495 } 7496 7497 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7498 SDVTList VTList, 7499 ArrayRef<SDValue> Ops, EVT MemVT, 7500 MachineMemOperand *MMO) { 7501 assert((Opcode == ISD::INTRINSIC_VOID || 7502 Opcode == ISD::INTRINSIC_W_CHAIN || 7503 Opcode == ISD::PREFETCH || 7504 ((int)Opcode <= std::numeric_limits<int>::max() && 7505 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7506 "Opcode is not a memory-accessing opcode!"); 7507 7508 // Memoize the node unless it returns a flag. 7509 MemIntrinsicSDNode *N; 7510 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7511 FoldingSetNodeID ID; 7512 AddNodeIDNode(ID, Opcode, VTList, Ops); 7513 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7514 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7515 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7516 ID.AddInteger(MMO->getFlags()); 7517 void *IP = nullptr; 7518 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7519 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7520 return SDValue(E, 0); 7521 } 7522 7523 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7524 VTList, MemVT, MMO); 7525 createOperands(N, Ops); 7526 7527 CSEMap.InsertNode(N, IP); 7528 } else { 7529 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7530 VTList, MemVT, MMO); 7531 createOperands(N, Ops); 7532 } 7533 InsertNode(N); 7534 SDValue V(N, 0); 7535 NewSDValueDbgMsg(V, "Creating new node: ", this); 7536 return V; 7537 } 7538 7539 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7540 SDValue Chain, int FrameIndex, 7541 int64_t Size, int64_t Offset) { 7542 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7543 const auto VTs = getVTList(MVT::Other); 7544 SDValue Ops[2] = { 7545 Chain, 7546 getFrameIndex(FrameIndex, 7547 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7548 true)}; 7549 7550 FoldingSetNodeID ID; 7551 AddNodeIDNode(ID, Opcode, VTs, Ops); 7552 ID.AddInteger(FrameIndex); 7553 ID.AddInteger(Size); 7554 ID.AddInteger(Offset); 7555 void *IP = nullptr; 7556 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7557 return SDValue(E, 0); 7558 7559 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7560 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7561 createOperands(N, Ops); 7562 CSEMap.InsertNode(N, IP); 7563 InsertNode(N); 7564 SDValue V(N, 0); 7565 NewSDValueDbgMsg(V, "Creating new node: ", this); 7566 return V; 7567 } 7568 7569 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7570 uint64_t Guid, uint64_t Index, 7571 uint32_t Attr) { 7572 const unsigned Opcode = ISD::PSEUDO_PROBE; 7573 const auto VTs = getVTList(MVT::Other); 7574 SDValue Ops[] = {Chain}; 7575 FoldingSetNodeID ID; 7576 AddNodeIDNode(ID, Opcode, VTs, Ops); 7577 ID.AddInteger(Guid); 7578 ID.AddInteger(Index); 7579 void *IP = nullptr; 7580 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7581 return SDValue(E, 0); 7582 7583 auto *N = newSDNode<PseudoProbeSDNode>( 7584 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7585 createOperands(N, Ops); 7586 CSEMap.InsertNode(N, IP); 7587 InsertNode(N); 7588 SDValue V(N, 0); 7589 NewSDValueDbgMsg(V, "Creating new node: ", this); 7590 return V; 7591 } 7592 7593 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7594 /// MachinePointerInfo record from it. This is particularly useful because the 7595 /// code generator has many cases where it doesn't bother passing in a 7596 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7597 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7598 SelectionDAG &DAG, SDValue Ptr, 7599 int64_t Offset = 0) { 7600 // If this is FI+Offset, we can model it. 7601 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7602 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7603 FI->getIndex(), Offset); 7604 7605 // If this is (FI+Offset1)+Offset2, we can model it. 7606 if (Ptr.getOpcode() != ISD::ADD || 7607 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7608 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7609 return Info; 7610 7611 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7612 return MachinePointerInfo::getFixedStack( 7613 DAG.getMachineFunction(), FI, 7614 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7615 } 7616 7617 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7618 /// MachinePointerInfo record from it. This is particularly useful because the 7619 /// code generator has many cases where it doesn't bother passing in a 7620 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7621 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7622 SelectionDAG &DAG, SDValue Ptr, 7623 SDValue OffsetOp) { 7624 // If the 'Offset' value isn't a constant, we can't handle this. 7625 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7626 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7627 if (OffsetOp.isUndef()) 7628 return InferPointerInfo(Info, DAG, Ptr); 7629 return Info; 7630 } 7631 7632 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7633 EVT VT, const SDLoc &dl, SDValue Chain, 7634 SDValue Ptr, SDValue Offset, 7635 MachinePointerInfo PtrInfo, EVT MemVT, 7636 Align Alignment, 7637 MachineMemOperand::Flags MMOFlags, 7638 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7639 assert(Chain.getValueType() == MVT::Other && 7640 "Invalid chain type"); 7641 7642 MMOFlags |= MachineMemOperand::MOLoad; 7643 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7644 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7645 // clients. 7646 if (PtrInfo.V.isNull()) 7647 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7648 7649 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7650 MachineFunction &MF = getMachineFunction(); 7651 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7652 Alignment, AAInfo, Ranges); 7653 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7654 } 7655 7656 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7657 EVT VT, const SDLoc &dl, SDValue Chain, 7658 SDValue Ptr, SDValue Offset, EVT MemVT, 7659 MachineMemOperand *MMO) { 7660 if (VT == MemVT) { 7661 ExtType = ISD::NON_EXTLOAD; 7662 } else if (ExtType == ISD::NON_EXTLOAD) { 7663 assert(VT == MemVT && "Non-extending load from different memory type!"); 7664 } else { 7665 // Extending load. 7666 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7667 "Should only be an extending load, not truncating!"); 7668 assert(VT.isInteger() == MemVT.isInteger() && 7669 "Cannot convert from FP to Int or Int -> FP!"); 7670 assert(VT.isVector() == MemVT.isVector() && 7671 "Cannot use an ext load to convert to or from a vector!"); 7672 assert((!VT.isVector() || 7673 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7674 "Cannot use an ext load to change the number of vector elements!"); 7675 } 7676 7677 bool Indexed = AM != ISD::UNINDEXED; 7678 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7679 7680 SDVTList VTs = Indexed ? 7681 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7682 SDValue Ops[] = { Chain, Ptr, Offset }; 7683 FoldingSetNodeID ID; 7684 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7685 ID.AddInteger(MemVT.getRawBits()); 7686 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7687 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7688 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7689 ID.AddInteger(MMO->getFlags()); 7690 void *IP = nullptr; 7691 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7692 cast<LoadSDNode>(E)->refineAlignment(MMO); 7693 return SDValue(E, 0); 7694 } 7695 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7696 ExtType, MemVT, MMO); 7697 createOperands(N, Ops); 7698 7699 CSEMap.InsertNode(N, IP); 7700 InsertNode(N); 7701 SDValue V(N, 0); 7702 NewSDValueDbgMsg(V, "Creating new node: ", this); 7703 return V; 7704 } 7705 7706 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7707 SDValue Ptr, MachinePointerInfo PtrInfo, 7708 MaybeAlign Alignment, 7709 MachineMemOperand::Flags MMOFlags, 7710 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7711 SDValue Undef = getUNDEF(Ptr.getValueType()); 7712 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7713 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7714 } 7715 7716 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7717 SDValue Ptr, MachineMemOperand *MMO) { 7718 SDValue Undef = getUNDEF(Ptr.getValueType()); 7719 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7720 VT, MMO); 7721 } 7722 7723 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7724 EVT VT, SDValue Chain, SDValue Ptr, 7725 MachinePointerInfo PtrInfo, EVT MemVT, 7726 MaybeAlign Alignment, 7727 MachineMemOperand::Flags MMOFlags, 7728 const AAMDNodes &AAInfo) { 7729 SDValue Undef = getUNDEF(Ptr.getValueType()); 7730 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7731 MemVT, Alignment, MMOFlags, AAInfo); 7732 } 7733 7734 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7735 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7736 MachineMemOperand *MMO) { 7737 SDValue Undef = getUNDEF(Ptr.getValueType()); 7738 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7739 MemVT, MMO); 7740 } 7741 7742 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7743 SDValue Base, SDValue Offset, 7744 ISD::MemIndexedMode AM) { 7745 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7746 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7747 // Don't propagate the invariant or dereferenceable flags. 7748 auto MMOFlags = 7749 LD->getMemOperand()->getFlags() & 7750 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7751 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7752 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7753 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7754 } 7755 7756 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7757 SDValue Ptr, MachinePointerInfo PtrInfo, 7758 Align Alignment, 7759 MachineMemOperand::Flags MMOFlags, 7760 const AAMDNodes &AAInfo) { 7761 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7762 7763 MMOFlags |= MachineMemOperand::MOStore; 7764 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7765 7766 if (PtrInfo.V.isNull()) 7767 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7768 7769 MachineFunction &MF = getMachineFunction(); 7770 uint64_t Size = 7771 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7772 MachineMemOperand *MMO = 7773 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7774 return getStore(Chain, dl, Val, Ptr, MMO); 7775 } 7776 7777 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7778 SDValue Ptr, MachineMemOperand *MMO) { 7779 assert(Chain.getValueType() == MVT::Other && 7780 "Invalid chain type"); 7781 EVT VT = Val.getValueType(); 7782 SDVTList VTs = getVTList(MVT::Other); 7783 SDValue Undef = getUNDEF(Ptr.getValueType()); 7784 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7785 FoldingSetNodeID ID; 7786 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7787 ID.AddInteger(VT.getRawBits()); 7788 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7789 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7790 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7791 ID.AddInteger(MMO->getFlags()); 7792 void *IP = nullptr; 7793 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7794 cast<StoreSDNode>(E)->refineAlignment(MMO); 7795 return SDValue(E, 0); 7796 } 7797 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7798 ISD::UNINDEXED, false, VT, MMO); 7799 createOperands(N, Ops); 7800 7801 CSEMap.InsertNode(N, IP); 7802 InsertNode(N); 7803 SDValue V(N, 0); 7804 NewSDValueDbgMsg(V, "Creating new node: ", this); 7805 return V; 7806 } 7807 7808 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7809 SDValue Ptr, MachinePointerInfo PtrInfo, 7810 EVT SVT, Align Alignment, 7811 MachineMemOperand::Flags MMOFlags, 7812 const AAMDNodes &AAInfo) { 7813 assert(Chain.getValueType() == MVT::Other && 7814 "Invalid chain type"); 7815 7816 MMOFlags |= MachineMemOperand::MOStore; 7817 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7818 7819 if (PtrInfo.V.isNull()) 7820 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7821 7822 MachineFunction &MF = getMachineFunction(); 7823 MachineMemOperand *MMO = MF.getMachineMemOperand( 7824 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7825 Alignment, AAInfo); 7826 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7827 } 7828 7829 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7830 SDValue Ptr, EVT SVT, 7831 MachineMemOperand *MMO) { 7832 EVT VT = Val.getValueType(); 7833 7834 assert(Chain.getValueType() == MVT::Other && 7835 "Invalid chain type"); 7836 if (VT == SVT) 7837 return getStore(Chain, dl, Val, Ptr, MMO); 7838 7839 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7840 "Should only be a truncating store, not extending!"); 7841 assert(VT.isInteger() == SVT.isInteger() && 7842 "Can't do FP-INT conversion!"); 7843 assert(VT.isVector() == SVT.isVector() && 7844 "Cannot use trunc store to convert to or from a vector!"); 7845 assert((!VT.isVector() || 7846 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7847 "Cannot use trunc store to change the number of vector elements!"); 7848 7849 SDVTList VTs = getVTList(MVT::Other); 7850 SDValue Undef = getUNDEF(Ptr.getValueType()); 7851 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7852 FoldingSetNodeID ID; 7853 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7854 ID.AddInteger(SVT.getRawBits()); 7855 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7856 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7857 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7858 ID.AddInteger(MMO->getFlags()); 7859 void *IP = nullptr; 7860 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7861 cast<StoreSDNode>(E)->refineAlignment(MMO); 7862 return SDValue(E, 0); 7863 } 7864 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7865 ISD::UNINDEXED, true, SVT, MMO); 7866 createOperands(N, Ops); 7867 7868 CSEMap.InsertNode(N, IP); 7869 InsertNode(N); 7870 SDValue V(N, 0); 7871 NewSDValueDbgMsg(V, "Creating new node: ", this); 7872 return V; 7873 } 7874 7875 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7876 SDValue Base, SDValue Offset, 7877 ISD::MemIndexedMode AM) { 7878 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7879 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7880 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7881 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7882 FoldingSetNodeID ID; 7883 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7884 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7885 ID.AddInteger(ST->getRawSubclassData()); 7886 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7887 ID.AddInteger(ST->getMemOperand()->getFlags()); 7888 void *IP = nullptr; 7889 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7890 return SDValue(E, 0); 7891 7892 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7893 ST->isTruncatingStore(), ST->getMemoryVT(), 7894 ST->getMemOperand()); 7895 createOperands(N, Ops); 7896 7897 CSEMap.InsertNode(N, IP); 7898 InsertNode(N); 7899 SDValue V(N, 0); 7900 NewSDValueDbgMsg(V, "Creating new node: ", this); 7901 return V; 7902 } 7903 7904 SDValue SelectionDAG::getLoadVP( 7905 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7906 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7907 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7908 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7909 const MDNode *Ranges, bool IsExpanding) { 7910 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7911 7912 MMOFlags |= MachineMemOperand::MOLoad; 7913 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7914 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7915 // clients. 7916 if (PtrInfo.V.isNull()) 7917 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7918 7919 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7920 MachineFunction &MF = getMachineFunction(); 7921 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7922 Alignment, AAInfo, Ranges); 7923 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7924 MMO, IsExpanding); 7925 } 7926 7927 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7928 ISD::LoadExtType ExtType, EVT VT, 7929 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7930 SDValue Offset, SDValue Mask, SDValue EVL, 7931 EVT MemVT, MachineMemOperand *MMO, 7932 bool IsExpanding) { 7933 bool Indexed = AM != ISD::UNINDEXED; 7934 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7935 7936 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7937 : getVTList(VT, MVT::Other); 7938 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7939 FoldingSetNodeID ID; 7940 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7941 ID.AddInteger(VT.getRawBits()); 7942 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7943 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7944 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7945 ID.AddInteger(MMO->getFlags()); 7946 void *IP = nullptr; 7947 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7948 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7949 return SDValue(E, 0); 7950 } 7951 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7952 ExtType, IsExpanding, MemVT, MMO); 7953 createOperands(N, Ops); 7954 7955 CSEMap.InsertNode(N, IP); 7956 InsertNode(N); 7957 SDValue V(N, 0); 7958 NewSDValueDbgMsg(V, "Creating new node: ", this); 7959 return V; 7960 } 7961 7962 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7963 SDValue Ptr, SDValue Mask, SDValue EVL, 7964 MachinePointerInfo PtrInfo, 7965 MaybeAlign Alignment, 7966 MachineMemOperand::Flags MMOFlags, 7967 const AAMDNodes &AAInfo, const MDNode *Ranges, 7968 bool IsExpanding) { 7969 SDValue Undef = getUNDEF(Ptr.getValueType()); 7970 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7971 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7972 IsExpanding); 7973 } 7974 7975 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7976 SDValue Ptr, SDValue Mask, SDValue EVL, 7977 MachineMemOperand *MMO, bool IsExpanding) { 7978 SDValue Undef = getUNDEF(Ptr.getValueType()); 7979 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7980 Mask, EVL, VT, MMO, IsExpanding); 7981 } 7982 7983 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7984 EVT VT, SDValue Chain, SDValue Ptr, 7985 SDValue Mask, SDValue EVL, 7986 MachinePointerInfo PtrInfo, EVT MemVT, 7987 MaybeAlign Alignment, 7988 MachineMemOperand::Flags MMOFlags, 7989 const AAMDNodes &AAInfo, bool IsExpanding) { 7990 SDValue Undef = getUNDEF(Ptr.getValueType()); 7991 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7992 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7993 IsExpanding); 7994 } 7995 7996 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7997 EVT VT, SDValue Chain, SDValue Ptr, 7998 SDValue Mask, SDValue EVL, EVT MemVT, 7999 MachineMemOperand *MMO, bool IsExpanding) { 8000 SDValue Undef = getUNDEF(Ptr.getValueType()); 8001 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8002 EVL, MemVT, MMO, IsExpanding); 8003 } 8004 8005 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 8006 SDValue Base, SDValue Offset, 8007 ISD::MemIndexedMode AM) { 8008 auto *LD = cast<VPLoadSDNode>(OrigLoad); 8009 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8010 // Don't propagate the invariant or dereferenceable flags. 8011 auto MMOFlags = 8012 LD->getMemOperand()->getFlags() & 8013 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8014 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8015 LD->getChain(), Base, Offset, LD->getMask(), 8016 LD->getVectorLength(), LD->getPointerInfo(), 8017 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 8018 nullptr, LD->isExpandingLoad()); 8019 } 8020 8021 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 8022 SDValue Ptr, SDValue Offset, SDValue Mask, 8023 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 8024 ISD::MemIndexedMode AM, bool IsTruncating, 8025 bool IsCompressing) { 8026 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8027 bool Indexed = AM != ISD::UNINDEXED; 8028 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8029 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8030 : getVTList(MVT::Other); 8031 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 8032 FoldingSetNodeID ID; 8033 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8034 ID.AddInteger(MemVT.getRawBits()); 8035 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8036 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8037 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8038 ID.AddInteger(MMO->getFlags()); 8039 void *IP = nullptr; 8040 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8041 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8042 return SDValue(E, 0); 8043 } 8044 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8045 IsTruncating, IsCompressing, MemVT, MMO); 8046 createOperands(N, Ops); 8047 8048 CSEMap.InsertNode(N, IP); 8049 InsertNode(N); 8050 SDValue V(N, 0); 8051 NewSDValueDbgMsg(V, "Creating new node: ", this); 8052 return V; 8053 } 8054 8055 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8056 SDValue Val, SDValue Ptr, SDValue Mask, 8057 SDValue EVL, MachinePointerInfo PtrInfo, 8058 EVT SVT, Align Alignment, 8059 MachineMemOperand::Flags MMOFlags, 8060 const AAMDNodes &AAInfo, 8061 bool IsCompressing) { 8062 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8063 8064 MMOFlags |= MachineMemOperand::MOStore; 8065 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8066 8067 if (PtrInfo.V.isNull()) 8068 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8069 8070 MachineFunction &MF = getMachineFunction(); 8071 MachineMemOperand *MMO = MF.getMachineMemOperand( 8072 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8073 Alignment, AAInfo); 8074 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8075 IsCompressing); 8076 } 8077 8078 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8079 SDValue Val, SDValue Ptr, SDValue Mask, 8080 SDValue EVL, EVT SVT, 8081 MachineMemOperand *MMO, 8082 bool IsCompressing) { 8083 EVT VT = Val.getValueType(); 8084 8085 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8086 if (VT == SVT) 8087 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8088 EVL, VT, MMO, ISD::UNINDEXED, 8089 /*IsTruncating*/ false, IsCompressing); 8090 8091 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8092 "Should only be a truncating store, not extending!"); 8093 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8094 assert(VT.isVector() == SVT.isVector() && 8095 "Cannot use trunc store to convert to or from a vector!"); 8096 assert((!VT.isVector() || 8097 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8098 "Cannot use trunc store to change the number of vector elements!"); 8099 8100 SDVTList VTs = getVTList(MVT::Other); 8101 SDValue Undef = getUNDEF(Ptr.getValueType()); 8102 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8103 FoldingSetNodeID ID; 8104 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8105 ID.AddInteger(SVT.getRawBits()); 8106 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8107 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8108 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8109 ID.AddInteger(MMO->getFlags()); 8110 void *IP = nullptr; 8111 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8112 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8113 return SDValue(E, 0); 8114 } 8115 auto *N = 8116 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8117 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8118 createOperands(N, Ops); 8119 8120 CSEMap.InsertNode(N, IP); 8121 InsertNode(N); 8122 SDValue V(N, 0); 8123 NewSDValueDbgMsg(V, "Creating new node: ", this); 8124 return V; 8125 } 8126 8127 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8128 SDValue Base, SDValue Offset, 8129 ISD::MemIndexedMode AM) { 8130 auto *ST = cast<VPStoreSDNode>(OrigStore); 8131 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8132 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8133 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8134 Offset, ST->getMask(), ST->getVectorLength()}; 8135 FoldingSetNodeID ID; 8136 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8137 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8138 ID.AddInteger(ST->getRawSubclassData()); 8139 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8140 ID.AddInteger(ST->getMemOperand()->getFlags()); 8141 void *IP = nullptr; 8142 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8143 return SDValue(E, 0); 8144 8145 auto *N = newSDNode<VPStoreSDNode>( 8146 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8147 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8148 createOperands(N, Ops); 8149 8150 CSEMap.InsertNode(N, IP); 8151 InsertNode(N); 8152 SDValue V(N, 0); 8153 NewSDValueDbgMsg(V, "Creating new node: ", this); 8154 return V; 8155 } 8156 8157 SDValue SelectionDAG::getStridedLoadVP( 8158 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8159 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8160 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8161 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8162 const MDNode *Ranges, bool IsExpanding) { 8163 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8164 8165 MMOFlags |= MachineMemOperand::MOLoad; 8166 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8167 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8168 // clients. 8169 if (PtrInfo.V.isNull()) 8170 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8171 8172 uint64_t Size = MemoryLocation::UnknownSize; 8173 MachineFunction &MF = getMachineFunction(); 8174 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8175 Alignment, AAInfo, Ranges); 8176 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8177 EVL, MemVT, MMO, IsExpanding); 8178 } 8179 8180 SDValue SelectionDAG::getStridedLoadVP( 8181 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8182 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8183 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8184 bool Indexed = AM != ISD::UNINDEXED; 8185 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8186 8187 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8188 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8189 : getVTList(VT, MVT::Other); 8190 FoldingSetNodeID ID; 8191 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8192 ID.AddInteger(VT.getRawBits()); 8193 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8194 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8195 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8196 8197 void *IP = nullptr; 8198 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8199 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8200 return SDValue(E, 0); 8201 } 8202 8203 auto *N = 8204 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8205 ExtType, IsExpanding, MemVT, MMO); 8206 createOperands(N, Ops); 8207 CSEMap.InsertNode(N, IP); 8208 InsertNode(N); 8209 SDValue V(N, 0); 8210 NewSDValueDbgMsg(V, "Creating new node: ", this); 8211 return V; 8212 } 8213 8214 SDValue SelectionDAG::getStridedLoadVP( 8215 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8216 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8217 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8218 const MDNode *Ranges, bool IsExpanding) { 8219 SDValue Undef = getUNDEF(Ptr.getValueType()); 8220 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8221 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8222 MMOFlags, AAInfo, Ranges, IsExpanding); 8223 } 8224 8225 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8226 SDValue Ptr, SDValue Stride, 8227 SDValue Mask, SDValue EVL, 8228 MachineMemOperand *MMO, 8229 bool IsExpanding) { 8230 SDValue Undef = getUNDEF(Ptr.getValueType()); 8231 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8232 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8233 } 8234 8235 SDValue SelectionDAG::getExtStridedLoadVP( 8236 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8237 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8238 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8239 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8240 bool IsExpanding) { 8241 SDValue Undef = getUNDEF(Ptr.getValueType()); 8242 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8243 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8244 MMOFlags, AAInfo, nullptr, IsExpanding); 8245 } 8246 8247 SDValue SelectionDAG::getExtStridedLoadVP( 8248 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8249 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8250 MachineMemOperand *MMO, bool IsExpanding) { 8251 SDValue Undef = getUNDEF(Ptr.getValueType()); 8252 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8253 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8254 } 8255 8256 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8257 SDValue Base, SDValue Offset, 8258 ISD::MemIndexedMode AM) { 8259 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8260 assert(SLD->getOffset().isUndef() && 8261 "Strided load is already a indexed load!"); 8262 // Don't propagate the invariant or dereferenceable flags. 8263 auto MMOFlags = 8264 SLD->getMemOperand()->getFlags() & 8265 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8266 return getStridedLoadVP( 8267 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8268 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8269 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8270 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8271 } 8272 8273 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8274 SDValue Val, SDValue Ptr, 8275 SDValue Offset, SDValue Stride, 8276 SDValue Mask, SDValue EVL, EVT MemVT, 8277 MachineMemOperand *MMO, 8278 ISD::MemIndexedMode AM, 8279 bool IsTruncating, bool IsCompressing) { 8280 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8281 bool Indexed = AM != ISD::UNINDEXED; 8282 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8283 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8284 : getVTList(MVT::Other); 8285 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8286 FoldingSetNodeID ID; 8287 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8288 ID.AddInteger(MemVT.getRawBits()); 8289 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8290 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8291 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8292 void *IP = nullptr; 8293 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8294 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8295 return SDValue(E, 0); 8296 } 8297 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8298 VTs, AM, IsTruncating, 8299 IsCompressing, MemVT, MMO); 8300 createOperands(N, Ops); 8301 8302 CSEMap.InsertNode(N, IP); 8303 InsertNode(N); 8304 SDValue V(N, 0); 8305 NewSDValueDbgMsg(V, "Creating new node: ", this); 8306 return V; 8307 } 8308 8309 SDValue SelectionDAG::getTruncStridedStoreVP( 8310 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8311 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8312 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8313 bool IsCompressing) { 8314 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8315 8316 MMOFlags |= MachineMemOperand::MOStore; 8317 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8318 8319 if (PtrInfo.V.isNull()) 8320 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8321 8322 MachineFunction &MF = getMachineFunction(); 8323 MachineMemOperand *MMO = MF.getMachineMemOperand( 8324 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8325 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8326 MMO, IsCompressing); 8327 } 8328 8329 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8330 SDValue Val, SDValue Ptr, 8331 SDValue Stride, SDValue Mask, 8332 SDValue EVL, EVT SVT, 8333 MachineMemOperand *MMO, 8334 bool IsCompressing) { 8335 EVT VT = Val.getValueType(); 8336 8337 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8338 if (VT == SVT) 8339 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8340 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8341 /*IsTruncating*/ false, IsCompressing); 8342 8343 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8344 "Should only be a truncating store, not extending!"); 8345 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8346 assert(VT.isVector() == SVT.isVector() && 8347 "Cannot use trunc store to convert to or from a vector!"); 8348 assert((!VT.isVector() || 8349 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8350 "Cannot use trunc store to change the number of vector elements!"); 8351 8352 SDVTList VTs = getVTList(MVT::Other); 8353 SDValue Undef = getUNDEF(Ptr.getValueType()); 8354 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8355 FoldingSetNodeID ID; 8356 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8357 ID.AddInteger(SVT.getRawBits()); 8358 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8359 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8360 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8361 void *IP = nullptr; 8362 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8363 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8364 return SDValue(E, 0); 8365 } 8366 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8367 VTs, ISD::UNINDEXED, true, 8368 IsCompressing, SVT, MMO); 8369 createOperands(N, Ops); 8370 8371 CSEMap.InsertNode(N, IP); 8372 InsertNode(N); 8373 SDValue V(N, 0); 8374 NewSDValueDbgMsg(V, "Creating new node: ", this); 8375 return V; 8376 } 8377 8378 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 8379 const SDLoc &DL, SDValue Base, 8380 SDValue Offset, 8381 ISD::MemIndexedMode AM) { 8382 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 8383 assert(SST->getOffset().isUndef() && 8384 "Strided store is already an indexed store!"); 8385 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8386 SDValue Ops[] = { 8387 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 8388 SST->getMask(), SST->getVectorLength()}; 8389 FoldingSetNodeID ID; 8390 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8391 ID.AddInteger(SST->getMemoryVT().getRawBits()); 8392 ID.AddInteger(SST->getRawSubclassData()); 8393 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 8394 void *IP = nullptr; 8395 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8396 return SDValue(E, 0); 8397 8398 auto *N = newSDNode<VPStridedStoreSDNode>( 8399 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 8400 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 8401 createOperands(N, Ops); 8402 8403 CSEMap.InsertNode(N, IP); 8404 InsertNode(N); 8405 SDValue V(N, 0); 8406 NewSDValueDbgMsg(V, "Creating new node: ", this); 8407 return V; 8408 } 8409 8410 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8411 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8412 ISD::MemIndexType IndexType) { 8413 assert(Ops.size() == 6 && "Incompatible number of operands"); 8414 8415 FoldingSetNodeID ID; 8416 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8417 ID.AddInteger(VT.getRawBits()); 8418 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8419 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8420 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8421 ID.AddInteger(MMO->getFlags()); 8422 void *IP = nullptr; 8423 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8424 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8425 return SDValue(E, 0); 8426 } 8427 8428 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8429 VT, MMO, IndexType); 8430 createOperands(N, Ops); 8431 8432 assert(N->getMask().getValueType().getVectorElementCount() == 8433 N->getValueType(0).getVectorElementCount() && 8434 "Vector width mismatch between mask and data"); 8435 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8436 N->getValueType(0).getVectorElementCount().isScalable() && 8437 "Scalable flags of index and data do not match"); 8438 assert(ElementCount::isKnownGE( 8439 N->getIndex().getValueType().getVectorElementCount(), 8440 N->getValueType(0).getVectorElementCount()) && 8441 "Vector width mismatch between index and data"); 8442 assert(isa<ConstantSDNode>(N->getScale()) && 8443 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8444 "Scale should be a constant power of 2"); 8445 8446 CSEMap.InsertNode(N, IP); 8447 InsertNode(N); 8448 SDValue V(N, 0); 8449 NewSDValueDbgMsg(V, "Creating new node: ", this); 8450 return V; 8451 } 8452 8453 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8454 ArrayRef<SDValue> Ops, 8455 MachineMemOperand *MMO, 8456 ISD::MemIndexType IndexType) { 8457 assert(Ops.size() == 7 && "Incompatible number of operands"); 8458 8459 FoldingSetNodeID ID; 8460 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8461 ID.AddInteger(VT.getRawBits()); 8462 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8463 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8464 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8465 ID.AddInteger(MMO->getFlags()); 8466 void *IP = nullptr; 8467 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8468 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8469 return SDValue(E, 0); 8470 } 8471 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8472 VT, MMO, IndexType); 8473 createOperands(N, Ops); 8474 8475 assert(N->getMask().getValueType().getVectorElementCount() == 8476 N->getValue().getValueType().getVectorElementCount() && 8477 "Vector width mismatch between mask and data"); 8478 assert( 8479 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8480 N->getValue().getValueType().getVectorElementCount().isScalable() && 8481 "Scalable flags of index and data do not match"); 8482 assert(ElementCount::isKnownGE( 8483 N->getIndex().getValueType().getVectorElementCount(), 8484 N->getValue().getValueType().getVectorElementCount()) && 8485 "Vector width mismatch between index and data"); 8486 assert(isa<ConstantSDNode>(N->getScale()) && 8487 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8488 "Scale should be a constant power of 2"); 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::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8498 SDValue Base, SDValue Offset, SDValue Mask, 8499 SDValue PassThru, EVT MemVT, 8500 MachineMemOperand *MMO, 8501 ISD::MemIndexedMode AM, 8502 ISD::LoadExtType ExtTy, bool isExpanding) { 8503 bool Indexed = AM != ISD::UNINDEXED; 8504 assert((Indexed || Offset.isUndef()) && 8505 "Unindexed masked load with an offset!"); 8506 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8507 : getVTList(VT, MVT::Other); 8508 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8509 FoldingSetNodeID ID; 8510 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8511 ID.AddInteger(MemVT.getRawBits()); 8512 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8513 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8514 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8515 ID.AddInteger(MMO->getFlags()); 8516 void *IP = nullptr; 8517 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8518 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8519 return SDValue(E, 0); 8520 } 8521 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8522 AM, ExtTy, isExpanding, MemVT, MMO); 8523 createOperands(N, Ops); 8524 8525 CSEMap.InsertNode(N, IP); 8526 InsertNode(N); 8527 SDValue V(N, 0); 8528 NewSDValueDbgMsg(V, "Creating new node: ", this); 8529 return V; 8530 } 8531 8532 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8533 SDValue Base, SDValue Offset, 8534 ISD::MemIndexedMode AM) { 8535 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8536 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8537 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8538 Offset, LD->getMask(), LD->getPassThru(), 8539 LD->getMemoryVT(), LD->getMemOperand(), AM, 8540 LD->getExtensionType(), LD->isExpandingLoad()); 8541 } 8542 8543 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8544 SDValue Val, SDValue Base, SDValue Offset, 8545 SDValue Mask, EVT MemVT, 8546 MachineMemOperand *MMO, 8547 ISD::MemIndexedMode AM, bool IsTruncating, 8548 bool IsCompressing) { 8549 assert(Chain.getValueType() == MVT::Other && 8550 "Invalid chain type"); 8551 bool Indexed = AM != ISD::UNINDEXED; 8552 assert((Indexed || Offset.isUndef()) && 8553 "Unindexed masked store with an offset!"); 8554 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8555 : getVTList(MVT::Other); 8556 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8557 FoldingSetNodeID ID; 8558 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8559 ID.AddInteger(MemVT.getRawBits()); 8560 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8561 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8562 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8563 ID.AddInteger(MMO->getFlags()); 8564 void *IP = nullptr; 8565 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8566 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8567 return SDValue(E, 0); 8568 } 8569 auto *N = 8570 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8571 IsTruncating, IsCompressing, MemVT, MMO); 8572 createOperands(N, Ops); 8573 8574 CSEMap.InsertNode(N, IP); 8575 InsertNode(N); 8576 SDValue V(N, 0); 8577 NewSDValueDbgMsg(V, "Creating new node: ", this); 8578 return V; 8579 } 8580 8581 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8582 SDValue Base, SDValue Offset, 8583 ISD::MemIndexedMode AM) { 8584 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8585 assert(ST->getOffset().isUndef() && 8586 "Masked store is already a indexed store!"); 8587 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8588 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8589 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8590 } 8591 8592 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8593 ArrayRef<SDValue> Ops, 8594 MachineMemOperand *MMO, 8595 ISD::MemIndexType IndexType, 8596 ISD::LoadExtType ExtTy) { 8597 assert(Ops.size() == 6 && "Incompatible number of operands"); 8598 8599 FoldingSetNodeID ID; 8600 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8601 ID.AddInteger(MemVT.getRawBits()); 8602 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8603 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8604 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8605 ID.AddInteger(MMO->getFlags()); 8606 void *IP = nullptr; 8607 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8608 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8609 return SDValue(E, 0); 8610 } 8611 8612 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8613 VTs, MemVT, MMO, IndexType, ExtTy); 8614 createOperands(N, Ops); 8615 8616 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8617 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8618 assert(N->getMask().getValueType().getVectorElementCount() == 8619 N->getValueType(0).getVectorElementCount() && 8620 "Vector width mismatch between mask and data"); 8621 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8622 N->getValueType(0).getVectorElementCount().isScalable() && 8623 "Scalable flags of index and data do not match"); 8624 assert(ElementCount::isKnownGE( 8625 N->getIndex().getValueType().getVectorElementCount(), 8626 N->getValueType(0).getVectorElementCount()) && 8627 "Vector width mismatch between index and data"); 8628 assert(isa<ConstantSDNode>(N->getScale()) && 8629 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8630 "Scale should be a constant power of 2"); 8631 8632 CSEMap.InsertNode(N, IP); 8633 InsertNode(N); 8634 SDValue V(N, 0); 8635 NewSDValueDbgMsg(V, "Creating new node: ", this); 8636 return V; 8637 } 8638 8639 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8640 ArrayRef<SDValue> Ops, 8641 MachineMemOperand *MMO, 8642 ISD::MemIndexType IndexType, 8643 bool IsTrunc) { 8644 assert(Ops.size() == 6 && "Incompatible number of operands"); 8645 8646 FoldingSetNodeID ID; 8647 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8648 ID.AddInteger(MemVT.getRawBits()); 8649 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8650 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8651 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8652 ID.AddInteger(MMO->getFlags()); 8653 void *IP = nullptr; 8654 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8655 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8656 return SDValue(E, 0); 8657 } 8658 8659 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8660 VTs, MemVT, MMO, IndexType, IsTrunc); 8661 createOperands(N, Ops); 8662 8663 assert(N->getMask().getValueType().getVectorElementCount() == 8664 N->getValue().getValueType().getVectorElementCount() && 8665 "Vector width mismatch between mask and data"); 8666 assert( 8667 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8668 N->getValue().getValueType().getVectorElementCount().isScalable() && 8669 "Scalable flags of index and data do not match"); 8670 assert(ElementCount::isKnownGE( 8671 N->getIndex().getValueType().getVectorElementCount(), 8672 N->getValue().getValueType().getVectorElementCount()) && 8673 "Vector width mismatch between index and data"); 8674 assert(isa<ConstantSDNode>(N->getScale()) && 8675 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8676 "Scale should be a constant power of 2"); 8677 8678 CSEMap.InsertNode(N, IP); 8679 InsertNode(N); 8680 SDValue V(N, 0); 8681 NewSDValueDbgMsg(V, "Creating new node: ", this); 8682 return V; 8683 } 8684 8685 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8686 // select undef, T, F --> T (if T is a constant), otherwise F 8687 // select, ?, undef, F --> F 8688 // select, ?, T, undef --> T 8689 if (Cond.isUndef()) 8690 return isConstantValueOfAnyType(T) ? T : F; 8691 if (T.isUndef()) 8692 return F; 8693 if (F.isUndef()) 8694 return T; 8695 8696 // select true, T, F --> T 8697 // select false, T, F --> F 8698 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8699 return CondC->isZero() ? F : T; 8700 8701 // TODO: This should simplify VSELECT with constant condition using something 8702 // like this (but check boolean contents to be complete?): 8703 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8704 // return T; 8705 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8706 // return F; 8707 8708 // select ?, T, T --> T 8709 if (T == F) 8710 return T; 8711 8712 return SDValue(); 8713 } 8714 8715 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8716 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8717 if (X.isUndef()) 8718 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8719 // shift X, undef --> undef (because it may shift by the bitwidth) 8720 if (Y.isUndef()) 8721 return getUNDEF(X.getValueType()); 8722 8723 // shift 0, Y --> 0 8724 // shift X, 0 --> X 8725 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8726 return X; 8727 8728 // shift X, C >= bitwidth(X) --> undef 8729 // All vector elements must be too big (or undef) to avoid partial undefs. 8730 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8731 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8732 }; 8733 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8734 return getUNDEF(X.getValueType()); 8735 8736 return SDValue(); 8737 } 8738 8739 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8740 SDNodeFlags Flags) { 8741 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8742 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8743 // operation is poison. That result can be relaxed to undef. 8744 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8745 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8746 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8747 (YC && YC->getValueAPF().isNaN()); 8748 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8749 (YC && YC->getValueAPF().isInfinity()); 8750 8751 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8752 return getUNDEF(X.getValueType()); 8753 8754 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8755 return getUNDEF(X.getValueType()); 8756 8757 if (!YC) 8758 return SDValue(); 8759 8760 // X + -0.0 --> X 8761 if (Opcode == ISD::FADD) 8762 if (YC->getValueAPF().isNegZero()) 8763 return X; 8764 8765 // X - +0.0 --> X 8766 if (Opcode == ISD::FSUB) 8767 if (YC->getValueAPF().isPosZero()) 8768 return X; 8769 8770 // X * 1.0 --> X 8771 // X / 1.0 --> X 8772 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8773 if (YC->getValueAPF().isExactlyValue(1.0)) 8774 return X; 8775 8776 // X * 0.0 --> 0.0 8777 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8778 if (YC->getValueAPF().isZero()) 8779 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8780 8781 return SDValue(); 8782 } 8783 8784 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8785 SDValue Ptr, SDValue SV, unsigned Align) { 8786 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8787 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8788 } 8789 8790 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8791 ArrayRef<SDUse> Ops) { 8792 switch (Ops.size()) { 8793 case 0: return getNode(Opcode, DL, VT); 8794 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8795 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8796 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8797 default: break; 8798 } 8799 8800 // Copy from an SDUse array into an SDValue array for use with 8801 // the regular getNode logic. 8802 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8803 return getNode(Opcode, DL, VT, NewOps); 8804 } 8805 8806 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8807 ArrayRef<SDValue> Ops) { 8808 SDNodeFlags Flags; 8809 if (Inserter) 8810 Flags = Inserter->getFlags(); 8811 return getNode(Opcode, DL, VT, Ops, Flags); 8812 } 8813 8814 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8815 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8816 unsigned NumOps = Ops.size(); 8817 switch (NumOps) { 8818 case 0: return getNode(Opcode, DL, VT); 8819 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8820 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8821 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8822 default: break; 8823 } 8824 8825 #ifndef NDEBUG 8826 for (auto &Op : Ops) 8827 assert(Op.getOpcode() != ISD::DELETED_NODE && 8828 "Operand is DELETED_NODE!"); 8829 #endif 8830 8831 switch (Opcode) { 8832 default: break; 8833 case ISD::BUILD_VECTOR: 8834 // Attempt to simplify BUILD_VECTOR. 8835 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8836 return V; 8837 break; 8838 case ISD::CONCAT_VECTORS: 8839 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8840 return V; 8841 break; 8842 case ISD::SELECT_CC: 8843 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8844 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8845 "LHS and RHS of condition must have same type!"); 8846 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8847 "True and False arms of SelectCC must have same type!"); 8848 assert(Ops[2].getValueType() == VT && 8849 "select_cc node must be of same type as true and false value!"); 8850 break; 8851 case ISD::BR_CC: 8852 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8853 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8854 "LHS/RHS of comparison should match types!"); 8855 break; 8856 case ISD::VP_ADD: 8857 case ISD::VP_SUB: 8858 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR 8859 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8860 Opcode = ISD::VP_XOR; 8861 break; 8862 case ISD::VP_MUL: 8863 // If it is VP_MUL mask operation then turn it to VP_AND 8864 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8865 Opcode = ISD::VP_AND; 8866 break; 8867 case ISD::VP_REDUCE_MUL: 8868 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND 8869 if (VT == MVT::i1) 8870 Opcode = ISD::VP_REDUCE_AND; 8871 break; 8872 case ISD::VP_REDUCE_ADD: 8873 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR 8874 if (VT == MVT::i1) 8875 Opcode = ISD::VP_REDUCE_XOR; 8876 break; 8877 case ISD::VP_REDUCE_SMAX: 8878 case ISD::VP_REDUCE_UMIN: 8879 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to 8880 // VP_REDUCE_AND. 8881 if (VT == MVT::i1) 8882 Opcode = ISD::VP_REDUCE_AND; 8883 break; 8884 case ISD::VP_REDUCE_SMIN: 8885 case ISD::VP_REDUCE_UMAX: 8886 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to 8887 // VP_REDUCE_OR. 8888 if (VT == MVT::i1) 8889 Opcode = ISD::VP_REDUCE_OR; 8890 break; 8891 } 8892 8893 // Memoize nodes. 8894 SDNode *N; 8895 SDVTList VTs = getVTList(VT); 8896 8897 if (VT != MVT::Glue) { 8898 FoldingSetNodeID ID; 8899 AddNodeIDNode(ID, Opcode, VTs, Ops); 8900 void *IP = nullptr; 8901 8902 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8903 return SDValue(E, 0); 8904 8905 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8906 createOperands(N, Ops); 8907 8908 CSEMap.InsertNode(N, IP); 8909 } else { 8910 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8911 createOperands(N, Ops); 8912 } 8913 8914 N->setFlags(Flags); 8915 InsertNode(N); 8916 SDValue V(N, 0); 8917 NewSDValueDbgMsg(V, "Creating new node: ", this); 8918 return V; 8919 } 8920 8921 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8922 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8923 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8924 } 8925 8926 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8927 ArrayRef<SDValue> Ops) { 8928 SDNodeFlags Flags; 8929 if (Inserter) 8930 Flags = Inserter->getFlags(); 8931 return getNode(Opcode, DL, VTList, Ops, Flags); 8932 } 8933 8934 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8935 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8936 if (VTList.NumVTs == 1) 8937 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags); 8938 8939 #ifndef NDEBUG 8940 for (auto &Op : Ops) 8941 assert(Op.getOpcode() != ISD::DELETED_NODE && 8942 "Operand is DELETED_NODE!"); 8943 #endif 8944 8945 switch (Opcode) { 8946 case ISD::STRICT_FP_EXTEND: 8947 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8948 "Invalid STRICT_FP_EXTEND!"); 8949 assert(VTList.VTs[0].isFloatingPoint() && 8950 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8951 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8952 "STRICT_FP_EXTEND result type should be vector iff the operand " 8953 "type is vector!"); 8954 assert((!VTList.VTs[0].isVector() || 8955 VTList.VTs[0].getVectorNumElements() == 8956 Ops[1].getValueType().getVectorNumElements()) && 8957 "Vector element count mismatch!"); 8958 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8959 "Invalid fpext node, dst <= src!"); 8960 break; 8961 case ISD::STRICT_FP_ROUND: 8962 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8963 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8964 "STRICT_FP_ROUND result type should be vector iff the operand " 8965 "type is vector!"); 8966 assert((!VTList.VTs[0].isVector() || 8967 VTList.VTs[0].getVectorNumElements() == 8968 Ops[1].getValueType().getVectorNumElements()) && 8969 "Vector element count mismatch!"); 8970 assert(VTList.VTs[0].isFloatingPoint() && 8971 Ops[1].getValueType().isFloatingPoint() && 8972 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8973 isa<ConstantSDNode>(Ops[2]) && 8974 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8975 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8976 "Invalid STRICT_FP_ROUND!"); 8977 break; 8978 #if 0 8979 // FIXME: figure out how to safely handle things like 8980 // int foo(int x) { return 1 << (x & 255); } 8981 // int bar() { return foo(256); } 8982 case ISD::SRA_PARTS: 8983 case ISD::SRL_PARTS: 8984 case ISD::SHL_PARTS: 8985 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8986 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8987 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8988 else if (N3.getOpcode() == ISD::AND) 8989 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8990 // If the and is only masking out bits that cannot effect the shift, 8991 // eliminate the and. 8992 unsigned NumBits = VT.getScalarSizeInBits()*2; 8993 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8994 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8995 } 8996 break; 8997 #endif 8998 } 8999 9000 // Memoize the node unless it returns a flag. 9001 SDNode *N; 9002 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 9003 FoldingSetNodeID ID; 9004 AddNodeIDNode(ID, Opcode, VTList, Ops); 9005 void *IP = nullptr; 9006 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9007 return SDValue(E, 0); 9008 9009 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9010 createOperands(N, Ops); 9011 CSEMap.InsertNode(N, IP); 9012 } else { 9013 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9014 createOperands(N, Ops); 9015 } 9016 9017 N->setFlags(Flags); 9018 InsertNode(N); 9019 SDValue V(N, 0); 9020 NewSDValueDbgMsg(V, "Creating new node: ", this); 9021 return V; 9022 } 9023 9024 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 9025 SDVTList VTList) { 9026 return getNode(Opcode, DL, VTList, None); 9027 } 9028 9029 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9030 SDValue N1) { 9031 SDValue Ops[] = { N1 }; 9032 return getNode(Opcode, DL, VTList, Ops); 9033 } 9034 9035 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9036 SDValue N1, SDValue N2) { 9037 SDValue Ops[] = { N1, N2 }; 9038 return getNode(Opcode, DL, VTList, Ops); 9039 } 9040 9041 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9042 SDValue N1, SDValue N2, SDValue N3) { 9043 SDValue Ops[] = { N1, N2, N3 }; 9044 return getNode(Opcode, DL, VTList, Ops); 9045 } 9046 9047 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9048 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 9049 SDValue Ops[] = { N1, N2, N3, N4 }; 9050 return getNode(Opcode, DL, VTList, Ops); 9051 } 9052 9053 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9054 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 9055 SDValue N5) { 9056 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 9057 return getNode(Opcode, DL, VTList, Ops); 9058 } 9059 9060 SDVTList SelectionDAG::getVTList(EVT VT) { 9061 return makeVTList(SDNode::getValueTypeList(VT), 1); 9062 } 9063 9064 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 9065 FoldingSetNodeID ID; 9066 ID.AddInteger(2U); 9067 ID.AddInteger(VT1.getRawBits()); 9068 ID.AddInteger(VT2.getRawBits()); 9069 9070 void *IP = nullptr; 9071 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9072 if (!Result) { 9073 EVT *Array = Allocator.Allocate<EVT>(2); 9074 Array[0] = VT1; 9075 Array[1] = VT2; 9076 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 9077 VTListMap.InsertNode(Result, IP); 9078 } 9079 return Result->getSDVTList(); 9080 } 9081 9082 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 9083 FoldingSetNodeID ID; 9084 ID.AddInteger(3U); 9085 ID.AddInteger(VT1.getRawBits()); 9086 ID.AddInteger(VT2.getRawBits()); 9087 ID.AddInteger(VT3.getRawBits()); 9088 9089 void *IP = nullptr; 9090 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9091 if (!Result) { 9092 EVT *Array = Allocator.Allocate<EVT>(3); 9093 Array[0] = VT1; 9094 Array[1] = VT2; 9095 Array[2] = VT3; 9096 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9097 VTListMap.InsertNode(Result, IP); 9098 } 9099 return Result->getSDVTList(); 9100 } 9101 9102 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9103 FoldingSetNodeID ID; 9104 ID.AddInteger(4U); 9105 ID.AddInteger(VT1.getRawBits()); 9106 ID.AddInteger(VT2.getRawBits()); 9107 ID.AddInteger(VT3.getRawBits()); 9108 ID.AddInteger(VT4.getRawBits()); 9109 9110 void *IP = nullptr; 9111 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9112 if (!Result) { 9113 EVT *Array = Allocator.Allocate<EVT>(4); 9114 Array[0] = VT1; 9115 Array[1] = VT2; 9116 Array[2] = VT3; 9117 Array[3] = VT4; 9118 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9119 VTListMap.InsertNode(Result, IP); 9120 } 9121 return Result->getSDVTList(); 9122 } 9123 9124 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9125 unsigned NumVTs = VTs.size(); 9126 FoldingSetNodeID ID; 9127 ID.AddInteger(NumVTs); 9128 for (unsigned index = 0; index < NumVTs; index++) { 9129 ID.AddInteger(VTs[index].getRawBits()); 9130 } 9131 9132 void *IP = nullptr; 9133 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9134 if (!Result) { 9135 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9136 llvm::copy(VTs, Array); 9137 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9138 VTListMap.InsertNode(Result, IP); 9139 } 9140 return Result->getSDVTList(); 9141 } 9142 9143 9144 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9145 /// specified operands. If the resultant node already exists in the DAG, 9146 /// this does not modify the specified node, instead it returns the node that 9147 /// already exists. If the resultant node does not exist in the DAG, the 9148 /// input node is returned. As a degenerate case, if you specify the same 9149 /// input operands as the node already has, the input node is returned. 9150 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9151 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9152 9153 // Check to see if there is no change. 9154 if (Op == N->getOperand(0)) return N; 9155 9156 // See if the modified node already exists. 9157 void *InsertPos = nullptr; 9158 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9159 return Existing; 9160 9161 // Nope it doesn't. Remove the node from its current place in the maps. 9162 if (InsertPos) 9163 if (!RemoveNodeFromCSEMaps(N)) 9164 InsertPos = nullptr; 9165 9166 // Now we update the operands. 9167 N->OperandList[0].set(Op); 9168 9169 updateDivergence(N); 9170 // If this gets put into a CSE map, add it. 9171 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9172 return N; 9173 } 9174 9175 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9176 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9177 9178 // Check to see if there is no change. 9179 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9180 return N; // No operands changed, just return the input node. 9181 9182 // See if the modified node already exists. 9183 void *InsertPos = nullptr; 9184 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9185 return Existing; 9186 9187 // Nope it doesn't. Remove the node from its current place in the maps. 9188 if (InsertPos) 9189 if (!RemoveNodeFromCSEMaps(N)) 9190 InsertPos = nullptr; 9191 9192 // Now we update the operands. 9193 if (N->OperandList[0] != Op1) 9194 N->OperandList[0].set(Op1); 9195 if (N->OperandList[1] != Op2) 9196 N->OperandList[1].set(Op2); 9197 9198 updateDivergence(N); 9199 // If this gets put into a CSE map, add it. 9200 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9201 return N; 9202 } 9203 9204 SDNode *SelectionDAG:: 9205 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9206 SDValue Ops[] = { Op1, Op2, Op3 }; 9207 return UpdateNodeOperands(N, Ops); 9208 } 9209 9210 SDNode *SelectionDAG:: 9211 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9212 SDValue Op3, SDValue Op4) { 9213 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9214 return UpdateNodeOperands(N, Ops); 9215 } 9216 9217 SDNode *SelectionDAG:: 9218 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9219 SDValue Op3, SDValue Op4, SDValue Op5) { 9220 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9221 return UpdateNodeOperands(N, Ops); 9222 } 9223 9224 SDNode *SelectionDAG:: 9225 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9226 unsigned NumOps = Ops.size(); 9227 assert(N->getNumOperands() == NumOps && 9228 "Update with wrong number of operands"); 9229 9230 // If no operands changed just return the input node. 9231 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9232 return N; 9233 9234 // See if the modified node already exists. 9235 void *InsertPos = nullptr; 9236 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9237 return Existing; 9238 9239 // Nope it doesn't. Remove the node from its current place in the maps. 9240 if (InsertPos) 9241 if (!RemoveNodeFromCSEMaps(N)) 9242 InsertPos = nullptr; 9243 9244 // Now we update the operands. 9245 for (unsigned i = 0; i != NumOps; ++i) 9246 if (N->OperandList[i] != Ops[i]) 9247 N->OperandList[i].set(Ops[i]); 9248 9249 updateDivergence(N); 9250 // If this gets put into a CSE map, add it. 9251 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9252 return N; 9253 } 9254 9255 /// DropOperands - Release the operands and set this node to have 9256 /// zero operands. 9257 void SDNode::DropOperands() { 9258 // Unlike the code in MorphNodeTo that does this, we don't need to 9259 // watch for dead nodes here. 9260 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9261 SDUse &Use = *I++; 9262 Use.set(SDValue()); 9263 } 9264 } 9265 9266 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9267 ArrayRef<MachineMemOperand *> NewMemRefs) { 9268 if (NewMemRefs.empty()) { 9269 N->clearMemRefs(); 9270 return; 9271 } 9272 9273 // Check if we can avoid allocating by storing a single reference directly. 9274 if (NewMemRefs.size() == 1) { 9275 N->MemRefs = NewMemRefs[0]; 9276 N->NumMemRefs = 1; 9277 return; 9278 } 9279 9280 MachineMemOperand **MemRefsBuffer = 9281 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 9282 llvm::copy(NewMemRefs, MemRefsBuffer); 9283 N->MemRefs = MemRefsBuffer; 9284 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 9285 } 9286 9287 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 9288 /// machine opcode. 9289 /// 9290 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9291 EVT VT) { 9292 SDVTList VTs = getVTList(VT); 9293 return SelectNodeTo(N, MachineOpc, VTs, None); 9294 } 9295 9296 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9297 EVT VT, SDValue Op1) { 9298 SDVTList VTs = getVTList(VT); 9299 SDValue Ops[] = { Op1 }; 9300 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9301 } 9302 9303 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9304 EVT VT, SDValue Op1, 9305 SDValue Op2) { 9306 SDVTList VTs = getVTList(VT); 9307 SDValue Ops[] = { Op1, Op2 }; 9308 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9309 } 9310 9311 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9312 EVT VT, SDValue Op1, 9313 SDValue Op2, SDValue Op3) { 9314 SDVTList VTs = getVTList(VT); 9315 SDValue Ops[] = { Op1, Op2, Op3 }; 9316 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9317 } 9318 9319 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9320 EVT VT, ArrayRef<SDValue> Ops) { 9321 SDVTList VTs = getVTList(VT); 9322 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9323 } 9324 9325 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9326 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 9327 SDVTList VTs = getVTList(VT1, VT2); 9328 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9329 } 9330 9331 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9332 EVT VT1, EVT VT2) { 9333 SDVTList VTs = getVTList(VT1, VT2); 9334 return SelectNodeTo(N, MachineOpc, VTs, None); 9335 } 9336 9337 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9338 EVT VT1, EVT VT2, EVT VT3, 9339 ArrayRef<SDValue> Ops) { 9340 SDVTList VTs = getVTList(VT1, VT2, VT3); 9341 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9342 } 9343 9344 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9345 EVT VT1, EVT VT2, 9346 SDValue Op1, SDValue Op2) { 9347 SDVTList VTs = getVTList(VT1, VT2); 9348 SDValue Ops[] = { Op1, Op2 }; 9349 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9350 } 9351 9352 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9353 SDVTList VTs,ArrayRef<SDValue> Ops) { 9354 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 9355 // Reset the NodeID to -1. 9356 New->setNodeId(-1); 9357 if (New != N) { 9358 ReplaceAllUsesWith(N, New); 9359 RemoveDeadNode(N); 9360 } 9361 return New; 9362 } 9363 9364 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 9365 /// the line number information on the merged node since it is not possible to 9366 /// preserve the information that operation is associated with multiple lines. 9367 /// This will make the debugger working better at -O0, were there is a higher 9368 /// probability having other instructions associated with that line. 9369 /// 9370 /// For IROrder, we keep the smaller of the two 9371 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 9372 DebugLoc NLoc = N->getDebugLoc(); 9373 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 9374 N->setDebugLoc(DebugLoc()); 9375 } 9376 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 9377 N->setIROrder(Order); 9378 return N; 9379 } 9380 9381 /// MorphNodeTo - This *mutates* the specified node to have the specified 9382 /// return type, opcode, and operands. 9383 /// 9384 /// Note that MorphNodeTo returns the resultant node. If there is already a 9385 /// node of the specified opcode and operands, it returns that node instead of 9386 /// the current one. Note that the SDLoc need not be the same. 9387 /// 9388 /// Using MorphNodeTo is faster than creating a new node and swapping it in 9389 /// with ReplaceAllUsesWith both because it often avoids allocating a new 9390 /// node, and because it doesn't require CSE recalculation for any of 9391 /// the node's users. 9392 /// 9393 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 9394 /// As a consequence it isn't appropriate to use from within the DAG combiner or 9395 /// the legalizer which maintain worklists that would need to be updated when 9396 /// deleting things. 9397 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 9398 SDVTList VTs, ArrayRef<SDValue> Ops) { 9399 // If an identical node already exists, use it. 9400 void *IP = nullptr; 9401 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 9402 FoldingSetNodeID ID; 9403 AddNodeIDNode(ID, Opc, VTs, Ops); 9404 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 9405 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 9406 } 9407 9408 if (!RemoveNodeFromCSEMaps(N)) 9409 IP = nullptr; 9410 9411 // Start the morphing. 9412 N->NodeType = Opc; 9413 N->ValueList = VTs.VTs; 9414 N->NumValues = VTs.NumVTs; 9415 9416 // Clear the operands list, updating used nodes to remove this from their 9417 // use list. Keep track of any operands that become dead as a result. 9418 SmallPtrSet<SDNode*, 16> DeadNodeSet; 9419 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 9420 SDUse &Use = *I++; 9421 SDNode *Used = Use.getNode(); 9422 Use.set(SDValue()); 9423 if (Used->use_empty()) 9424 DeadNodeSet.insert(Used); 9425 } 9426 9427 // For MachineNode, initialize the memory references information. 9428 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 9429 MN->clearMemRefs(); 9430 9431 // Swap for an appropriately sized array from the recycler. 9432 removeOperands(N); 9433 createOperands(N, Ops); 9434 9435 // Delete any nodes that are still dead after adding the uses for the 9436 // new operands. 9437 if (!DeadNodeSet.empty()) { 9438 SmallVector<SDNode *, 16> DeadNodes; 9439 for (SDNode *N : DeadNodeSet) 9440 if (N->use_empty()) 9441 DeadNodes.push_back(N); 9442 RemoveDeadNodes(DeadNodes); 9443 } 9444 9445 if (IP) 9446 CSEMap.InsertNode(N, IP); // Memoize the new node. 9447 return N; 9448 } 9449 9450 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9451 unsigned OrigOpc = Node->getOpcode(); 9452 unsigned NewOpc; 9453 switch (OrigOpc) { 9454 default: 9455 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9456 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9457 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9458 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9459 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9460 #include "llvm/IR/ConstrainedOps.def" 9461 } 9462 9463 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9464 9465 // We're taking this node out of the chain, so we need to re-link things. 9466 SDValue InputChain = Node->getOperand(0); 9467 SDValue OutputChain = SDValue(Node, 1); 9468 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9469 9470 SmallVector<SDValue, 3> Ops; 9471 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9472 Ops.push_back(Node->getOperand(i)); 9473 9474 SDVTList VTs = getVTList(Node->getValueType(0)); 9475 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9476 9477 // MorphNodeTo can operate in two ways: if an existing node with the 9478 // specified operands exists, it can just return it. Otherwise, it 9479 // updates the node in place to have the requested operands. 9480 if (Res == Node) { 9481 // If we updated the node in place, reset the node ID. To the isel, 9482 // this should be just like a newly allocated machine node. 9483 Res->setNodeId(-1); 9484 } else { 9485 ReplaceAllUsesWith(Node, Res); 9486 RemoveDeadNode(Node); 9487 } 9488 9489 return Res; 9490 } 9491 9492 /// getMachineNode - These are used for target selectors to create a new node 9493 /// with specified return type(s), MachineInstr opcode, and operands. 9494 /// 9495 /// Note that getMachineNode returns the resultant node. If there is already a 9496 /// node of the specified opcode and operands, it returns that node instead of 9497 /// the current one. 9498 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9499 EVT VT) { 9500 SDVTList VTs = getVTList(VT); 9501 return getMachineNode(Opcode, dl, VTs, None); 9502 } 9503 9504 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9505 EVT VT, SDValue Op1) { 9506 SDVTList VTs = getVTList(VT); 9507 SDValue Ops[] = { Op1 }; 9508 return getMachineNode(Opcode, dl, VTs, Ops); 9509 } 9510 9511 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9512 EVT VT, SDValue Op1, SDValue Op2) { 9513 SDVTList VTs = getVTList(VT); 9514 SDValue Ops[] = { Op1, Op2 }; 9515 return getMachineNode(Opcode, dl, VTs, Ops); 9516 } 9517 9518 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9519 EVT VT, SDValue Op1, SDValue Op2, 9520 SDValue Op3) { 9521 SDVTList VTs = getVTList(VT); 9522 SDValue Ops[] = { Op1, Op2, Op3 }; 9523 return getMachineNode(Opcode, dl, VTs, Ops); 9524 } 9525 9526 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9527 EVT VT, ArrayRef<SDValue> Ops) { 9528 SDVTList VTs = getVTList(VT); 9529 return getMachineNode(Opcode, dl, VTs, Ops); 9530 } 9531 9532 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9533 EVT VT1, EVT VT2, SDValue Op1, 9534 SDValue Op2) { 9535 SDVTList VTs = getVTList(VT1, VT2); 9536 SDValue Ops[] = { Op1, Op2 }; 9537 return getMachineNode(Opcode, dl, VTs, Ops); 9538 } 9539 9540 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9541 EVT VT1, EVT VT2, SDValue Op1, 9542 SDValue Op2, SDValue Op3) { 9543 SDVTList VTs = getVTList(VT1, VT2); 9544 SDValue Ops[] = { Op1, Op2, Op3 }; 9545 return getMachineNode(Opcode, dl, VTs, Ops); 9546 } 9547 9548 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9549 EVT VT1, EVT VT2, 9550 ArrayRef<SDValue> Ops) { 9551 SDVTList VTs = getVTList(VT1, VT2); 9552 return getMachineNode(Opcode, dl, VTs, Ops); 9553 } 9554 9555 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9556 EVT VT1, EVT VT2, EVT VT3, 9557 SDValue Op1, SDValue Op2) { 9558 SDVTList VTs = getVTList(VT1, VT2, VT3); 9559 SDValue Ops[] = { Op1, Op2 }; 9560 return getMachineNode(Opcode, dl, VTs, Ops); 9561 } 9562 9563 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9564 EVT VT1, EVT VT2, EVT VT3, 9565 SDValue Op1, SDValue Op2, 9566 SDValue Op3) { 9567 SDVTList VTs = getVTList(VT1, VT2, VT3); 9568 SDValue Ops[] = { Op1, Op2, Op3 }; 9569 return getMachineNode(Opcode, dl, VTs, Ops); 9570 } 9571 9572 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9573 EVT VT1, EVT VT2, EVT VT3, 9574 ArrayRef<SDValue> Ops) { 9575 SDVTList VTs = getVTList(VT1, VT2, VT3); 9576 return getMachineNode(Opcode, dl, VTs, Ops); 9577 } 9578 9579 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9580 ArrayRef<EVT> ResultTys, 9581 ArrayRef<SDValue> Ops) { 9582 SDVTList VTs = getVTList(ResultTys); 9583 return getMachineNode(Opcode, dl, VTs, Ops); 9584 } 9585 9586 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9587 SDVTList VTs, 9588 ArrayRef<SDValue> Ops) { 9589 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9590 MachineSDNode *N; 9591 void *IP = nullptr; 9592 9593 if (DoCSE) { 9594 FoldingSetNodeID ID; 9595 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9596 IP = nullptr; 9597 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9598 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9599 } 9600 } 9601 9602 // Allocate a new MachineSDNode. 9603 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9604 createOperands(N, Ops); 9605 9606 if (DoCSE) 9607 CSEMap.InsertNode(N, IP); 9608 9609 InsertNode(N); 9610 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9611 return N; 9612 } 9613 9614 /// getTargetExtractSubreg - A convenience function for creating 9615 /// TargetOpcode::EXTRACT_SUBREG nodes. 9616 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9617 SDValue Operand) { 9618 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9619 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9620 VT, Operand, SRIdxVal); 9621 return SDValue(Subreg, 0); 9622 } 9623 9624 /// getTargetInsertSubreg - A convenience function for creating 9625 /// TargetOpcode::INSERT_SUBREG nodes. 9626 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9627 SDValue Operand, SDValue Subreg) { 9628 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9629 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9630 VT, Operand, Subreg, SRIdxVal); 9631 return SDValue(Result, 0); 9632 } 9633 9634 /// getNodeIfExists - Get the specified node if it's already available, or 9635 /// else return NULL. 9636 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9637 ArrayRef<SDValue> Ops) { 9638 SDNodeFlags Flags; 9639 if (Inserter) 9640 Flags = Inserter->getFlags(); 9641 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9642 } 9643 9644 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9645 ArrayRef<SDValue> Ops, 9646 const SDNodeFlags Flags) { 9647 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9648 FoldingSetNodeID ID; 9649 AddNodeIDNode(ID, Opcode, VTList, Ops); 9650 void *IP = nullptr; 9651 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9652 E->intersectFlagsWith(Flags); 9653 return E; 9654 } 9655 } 9656 return nullptr; 9657 } 9658 9659 /// doesNodeExist - Check if a node exists without modifying its flags. 9660 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9661 ArrayRef<SDValue> Ops) { 9662 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9663 FoldingSetNodeID ID; 9664 AddNodeIDNode(ID, Opcode, VTList, Ops); 9665 void *IP = nullptr; 9666 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9667 return true; 9668 } 9669 return false; 9670 } 9671 9672 /// getDbgValue - Creates a SDDbgValue node. 9673 /// 9674 /// SDNode 9675 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9676 SDNode *N, unsigned R, bool IsIndirect, 9677 const DebugLoc &DL, unsigned O) { 9678 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9679 "Expected inlined-at fields to agree"); 9680 return new (DbgInfo->getAlloc()) 9681 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9682 {}, IsIndirect, DL, O, 9683 /*IsVariadic=*/false); 9684 } 9685 9686 /// Constant 9687 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9688 DIExpression *Expr, 9689 const Value *C, 9690 const DebugLoc &DL, unsigned O) { 9691 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9692 "Expected inlined-at fields to agree"); 9693 return new (DbgInfo->getAlloc()) 9694 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9695 /*IsIndirect=*/false, DL, O, 9696 /*IsVariadic=*/false); 9697 } 9698 9699 /// FrameIndex 9700 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9701 DIExpression *Expr, unsigned FI, 9702 bool IsIndirect, 9703 const DebugLoc &DL, 9704 unsigned O) { 9705 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9706 "Expected inlined-at fields to agree"); 9707 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9708 } 9709 9710 /// FrameIndex with dependencies 9711 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9712 DIExpression *Expr, unsigned FI, 9713 ArrayRef<SDNode *> Dependencies, 9714 bool IsIndirect, 9715 const DebugLoc &DL, 9716 unsigned O) { 9717 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9718 "Expected inlined-at fields to agree"); 9719 return new (DbgInfo->getAlloc()) 9720 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9721 Dependencies, IsIndirect, DL, O, 9722 /*IsVariadic=*/false); 9723 } 9724 9725 /// VReg 9726 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9727 unsigned VReg, bool IsIndirect, 9728 const DebugLoc &DL, unsigned O) { 9729 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9730 "Expected inlined-at fields to agree"); 9731 return new (DbgInfo->getAlloc()) 9732 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9733 {}, IsIndirect, DL, O, 9734 /*IsVariadic=*/false); 9735 } 9736 9737 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9738 ArrayRef<SDDbgOperand> Locs, 9739 ArrayRef<SDNode *> Dependencies, 9740 bool IsIndirect, const DebugLoc &DL, 9741 unsigned O, bool IsVariadic) { 9742 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9743 "Expected inlined-at fields to agree"); 9744 return new (DbgInfo->getAlloc()) 9745 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9746 DL, O, IsVariadic); 9747 } 9748 9749 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9750 unsigned OffsetInBits, unsigned SizeInBits, 9751 bool InvalidateDbg) { 9752 SDNode *FromNode = From.getNode(); 9753 SDNode *ToNode = To.getNode(); 9754 assert(FromNode && ToNode && "Can't modify dbg values"); 9755 9756 // PR35338 9757 // TODO: assert(From != To && "Redundant dbg value transfer"); 9758 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9759 if (From == To || FromNode == ToNode) 9760 return; 9761 9762 if (!FromNode->getHasDebugValue()) 9763 return; 9764 9765 SDDbgOperand FromLocOp = 9766 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9767 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9768 9769 SmallVector<SDDbgValue *, 2> ClonedDVs; 9770 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9771 if (Dbg->isInvalidated()) 9772 continue; 9773 9774 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9775 9776 // Create a new location ops vector that is equal to the old vector, but 9777 // with each instance of FromLocOp replaced with ToLocOp. 9778 bool Changed = false; 9779 auto NewLocOps = Dbg->copyLocationOps(); 9780 std::replace_if( 9781 NewLocOps.begin(), NewLocOps.end(), 9782 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9783 bool Match = Op == FromLocOp; 9784 Changed |= Match; 9785 return Match; 9786 }, 9787 ToLocOp); 9788 // Ignore this SDDbgValue if we didn't find a matching location. 9789 if (!Changed) 9790 continue; 9791 9792 DIVariable *Var = Dbg->getVariable(); 9793 auto *Expr = Dbg->getExpression(); 9794 // If a fragment is requested, update the expression. 9795 if (SizeInBits) { 9796 // When splitting a larger (e.g., sign-extended) value whose 9797 // lower bits are described with an SDDbgValue, do not attempt 9798 // to transfer the SDDbgValue to the upper bits. 9799 if (auto FI = Expr->getFragmentInfo()) 9800 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9801 continue; 9802 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9803 SizeInBits); 9804 if (!Fragment) 9805 continue; 9806 Expr = *Fragment; 9807 } 9808 9809 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9810 // Clone the SDDbgValue and move it to To. 9811 SDDbgValue *Clone = getDbgValueList( 9812 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9813 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9814 Dbg->isVariadic()); 9815 ClonedDVs.push_back(Clone); 9816 9817 if (InvalidateDbg) { 9818 // Invalidate value and indicate the SDDbgValue should not be emitted. 9819 Dbg->setIsInvalidated(); 9820 Dbg->setIsEmitted(); 9821 } 9822 } 9823 9824 for (SDDbgValue *Dbg : ClonedDVs) { 9825 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9826 "Transferred DbgValues should depend on the new SDNode"); 9827 AddDbgValue(Dbg, false); 9828 } 9829 } 9830 9831 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9832 if (!N.getHasDebugValue()) 9833 return; 9834 9835 SmallVector<SDDbgValue *, 2> ClonedDVs; 9836 for (auto DV : GetDbgValues(&N)) { 9837 if (DV->isInvalidated()) 9838 continue; 9839 switch (N.getOpcode()) { 9840 default: 9841 break; 9842 case ISD::ADD: 9843 SDValue N0 = N.getOperand(0); 9844 SDValue N1 = N.getOperand(1); 9845 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9846 isConstantIntBuildVectorOrConstantInt(N1)) { 9847 uint64_t Offset = N.getConstantOperandVal(1); 9848 9849 // Rewrite an ADD constant node into a DIExpression. Since we are 9850 // performing arithmetic to compute the variable's *value* in the 9851 // DIExpression, we need to mark the expression with a 9852 // DW_OP_stack_value. 9853 auto *DIExpr = DV->getExpression(); 9854 auto NewLocOps = DV->copyLocationOps(); 9855 bool Changed = false; 9856 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9857 // We're not given a ResNo to compare against because the whole 9858 // node is going away. We know that any ISD::ADD only has one 9859 // result, so we can assume any node match is using the result. 9860 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9861 NewLocOps[i].getSDNode() != &N) 9862 continue; 9863 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9864 SmallVector<uint64_t, 3> ExprOps; 9865 DIExpression::appendOffset(ExprOps, Offset); 9866 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9867 Changed = true; 9868 } 9869 (void)Changed; 9870 assert(Changed && "Salvage target doesn't use N"); 9871 9872 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9873 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9874 NewLocOps, AdditionalDependencies, 9875 DV->isIndirect(), DV->getDebugLoc(), 9876 DV->getOrder(), DV->isVariadic()); 9877 ClonedDVs.push_back(Clone); 9878 DV->setIsInvalidated(); 9879 DV->setIsEmitted(); 9880 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9881 N0.getNode()->dumprFull(this); 9882 dbgs() << " into " << *DIExpr << '\n'); 9883 } 9884 } 9885 } 9886 9887 for (SDDbgValue *Dbg : ClonedDVs) { 9888 assert(!Dbg->getSDNodes().empty() && 9889 "Salvaged DbgValue should depend on a new SDNode"); 9890 AddDbgValue(Dbg, false); 9891 } 9892 } 9893 9894 /// Creates a SDDbgLabel node. 9895 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9896 const DebugLoc &DL, unsigned O) { 9897 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9898 "Expected inlined-at fields to agree"); 9899 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9900 } 9901 9902 namespace { 9903 9904 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9905 /// pointed to by a use iterator is deleted, increment the use iterator 9906 /// so that it doesn't dangle. 9907 /// 9908 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9909 SDNode::use_iterator &UI; 9910 SDNode::use_iterator &UE; 9911 9912 void NodeDeleted(SDNode *N, SDNode *E) override { 9913 // Increment the iterator as needed. 9914 while (UI != UE && N == *UI) 9915 ++UI; 9916 } 9917 9918 public: 9919 RAUWUpdateListener(SelectionDAG &d, 9920 SDNode::use_iterator &ui, 9921 SDNode::use_iterator &ue) 9922 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9923 }; 9924 9925 } // end anonymous namespace 9926 9927 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9928 /// This can cause recursive merging of nodes in the DAG. 9929 /// 9930 /// This version assumes From has a single result value. 9931 /// 9932 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9933 SDNode *From = FromN.getNode(); 9934 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9935 "Cannot replace with this method!"); 9936 assert(From != To.getNode() && "Cannot replace uses of with self"); 9937 9938 // Preserve Debug Values 9939 transferDbgValues(FromN, To); 9940 9941 // Iterate over all the existing uses of From. New uses will be added 9942 // to the beginning of the use list, which we avoid visiting. 9943 // This specifically avoids visiting uses of From that arise while the 9944 // replacement is happening, because any such uses would be the result 9945 // of CSE: If an existing node looks like From after one of its operands 9946 // is replaced by To, we don't want to replace of all its users with To 9947 // too. See PR3018 for more info. 9948 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9949 RAUWUpdateListener Listener(*this, UI, UE); 9950 while (UI != UE) { 9951 SDNode *User = *UI; 9952 9953 // This node is about to morph, remove its old self from the CSE maps. 9954 RemoveNodeFromCSEMaps(User); 9955 9956 // A user can appear in a use list multiple times, and when this 9957 // happens the uses are usually next to each other in the list. 9958 // To help reduce the number of CSE recomputations, process all 9959 // the uses of this user that we can find this way. 9960 do { 9961 SDUse &Use = UI.getUse(); 9962 ++UI; 9963 Use.set(To); 9964 if (To->isDivergent() != From->isDivergent()) 9965 updateDivergence(User); 9966 } while (UI != UE && *UI == User); 9967 // Now that we have modified User, add it back to the CSE maps. If it 9968 // already exists there, recursively merge the results together. 9969 AddModifiedNodeToCSEMaps(User); 9970 } 9971 9972 // If we just RAUW'd the root, take note. 9973 if (FromN == getRoot()) 9974 setRoot(To); 9975 } 9976 9977 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9978 /// This can cause recursive merging of nodes in the DAG. 9979 /// 9980 /// This version assumes that for each value of From, there is a 9981 /// corresponding value in To in the same position with the same type. 9982 /// 9983 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9984 #ifndef NDEBUG 9985 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9986 assert((!From->hasAnyUseOfValue(i) || 9987 From->getValueType(i) == To->getValueType(i)) && 9988 "Cannot use this version of ReplaceAllUsesWith!"); 9989 #endif 9990 9991 // Handle the trivial case. 9992 if (From == To) 9993 return; 9994 9995 // Preserve Debug Info. Only do this if there's a use. 9996 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9997 if (From->hasAnyUseOfValue(i)) { 9998 assert((i < To->getNumValues()) && "Invalid To location"); 9999 transferDbgValues(SDValue(From, i), SDValue(To, i)); 10000 } 10001 10002 // Iterate over just the existing users of From. See the comments in 10003 // the ReplaceAllUsesWith above. 10004 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10005 RAUWUpdateListener Listener(*this, UI, UE); 10006 while (UI != UE) { 10007 SDNode *User = *UI; 10008 10009 // This node is about to morph, remove its old self from the CSE maps. 10010 RemoveNodeFromCSEMaps(User); 10011 10012 // A user can appear in a use list multiple times, and when this 10013 // happens the uses are usually next to each other in the list. 10014 // To help reduce the number of CSE recomputations, process all 10015 // the uses of this user that we can find this way. 10016 do { 10017 SDUse &Use = UI.getUse(); 10018 ++UI; 10019 Use.setNode(To); 10020 if (To->isDivergent() != From->isDivergent()) 10021 updateDivergence(User); 10022 } while (UI != UE && *UI == User); 10023 10024 // Now that we have modified User, add it back to the CSE maps. If it 10025 // already exists there, recursively merge the results together. 10026 AddModifiedNodeToCSEMaps(User); 10027 } 10028 10029 // If we just RAUW'd the root, take note. 10030 if (From == getRoot().getNode()) 10031 setRoot(SDValue(To, getRoot().getResNo())); 10032 } 10033 10034 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10035 /// This can cause recursive merging of nodes in the DAG. 10036 /// 10037 /// This version can replace From with any result values. To must match the 10038 /// number and types of values returned by From. 10039 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 10040 if (From->getNumValues() == 1) // Handle the simple case efficiently. 10041 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 10042 10043 // Preserve Debug Info. 10044 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10045 transferDbgValues(SDValue(From, i), To[i]); 10046 10047 // Iterate over just the existing users of From. See the comments in 10048 // the ReplaceAllUsesWith above. 10049 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10050 RAUWUpdateListener Listener(*this, UI, UE); 10051 while (UI != UE) { 10052 SDNode *User = *UI; 10053 10054 // This node is about to morph, remove its old self from the CSE maps. 10055 RemoveNodeFromCSEMaps(User); 10056 10057 // A user can appear in a use list multiple times, and when this happens the 10058 // uses are usually next to each other in the list. To help reduce the 10059 // number of CSE and divergence recomputations, process all the uses of this 10060 // user that we can find this way. 10061 bool To_IsDivergent = false; 10062 do { 10063 SDUse &Use = UI.getUse(); 10064 const SDValue &ToOp = To[Use.getResNo()]; 10065 ++UI; 10066 Use.set(ToOp); 10067 To_IsDivergent |= ToOp->isDivergent(); 10068 } while (UI != UE && *UI == User); 10069 10070 if (To_IsDivergent != From->isDivergent()) 10071 updateDivergence(User); 10072 10073 // Now that we have modified User, add it back to the CSE maps. If it 10074 // already exists there, recursively merge the results together. 10075 AddModifiedNodeToCSEMaps(User); 10076 } 10077 10078 // If we just RAUW'd the root, take note. 10079 if (From == getRoot().getNode()) 10080 setRoot(SDValue(To[getRoot().getResNo()])); 10081 } 10082 10083 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 10084 /// uses of other values produced by From.getNode() alone. The Deleted 10085 /// vector is handled the same way as for ReplaceAllUsesWith. 10086 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 10087 // Handle the really simple, really trivial case efficiently. 10088 if (From == To) return; 10089 10090 // Handle the simple, trivial, case efficiently. 10091 if (From.getNode()->getNumValues() == 1) { 10092 ReplaceAllUsesWith(From, To); 10093 return; 10094 } 10095 10096 // Preserve Debug Info. 10097 transferDbgValues(From, To); 10098 10099 // Iterate over just the existing users of From. See the comments in 10100 // the ReplaceAllUsesWith above. 10101 SDNode::use_iterator UI = From.getNode()->use_begin(), 10102 UE = From.getNode()->use_end(); 10103 RAUWUpdateListener Listener(*this, UI, UE); 10104 while (UI != UE) { 10105 SDNode *User = *UI; 10106 bool UserRemovedFromCSEMaps = false; 10107 10108 // A user can appear in a use list multiple times, and when this 10109 // happens the uses are usually next to each other in the list. 10110 // To help reduce the number of CSE recomputations, process all 10111 // the uses of this user that we can find this way. 10112 do { 10113 SDUse &Use = UI.getUse(); 10114 10115 // Skip uses of different values from the same node. 10116 if (Use.getResNo() != From.getResNo()) { 10117 ++UI; 10118 continue; 10119 } 10120 10121 // If this node hasn't been modified yet, it's still in the CSE maps, 10122 // so remove its old self from the CSE maps. 10123 if (!UserRemovedFromCSEMaps) { 10124 RemoveNodeFromCSEMaps(User); 10125 UserRemovedFromCSEMaps = true; 10126 } 10127 10128 ++UI; 10129 Use.set(To); 10130 if (To->isDivergent() != From->isDivergent()) 10131 updateDivergence(User); 10132 } while (UI != UE && *UI == User); 10133 // We are iterating over all uses of the From node, so if a use 10134 // doesn't use the specific value, no changes are made. 10135 if (!UserRemovedFromCSEMaps) 10136 continue; 10137 10138 // Now that we have modified User, add it back to the CSE maps. If it 10139 // already exists there, recursively merge the results together. 10140 AddModifiedNodeToCSEMaps(User); 10141 } 10142 10143 // If we just RAUW'd the root, take note. 10144 if (From == getRoot()) 10145 setRoot(To); 10146 } 10147 10148 namespace { 10149 10150 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10151 /// to record information about a use. 10152 struct UseMemo { 10153 SDNode *User; 10154 unsigned Index; 10155 SDUse *Use; 10156 }; 10157 10158 /// operator< - Sort Memos by User. 10159 bool operator<(const UseMemo &L, const UseMemo &R) { 10160 return (intptr_t)L.User < (intptr_t)R.User; 10161 } 10162 10163 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10164 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10165 /// the node already has been taken care of recursively. 10166 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10167 SmallVector<UseMemo, 4> &Uses; 10168 10169 void NodeDeleted(SDNode *N, SDNode *E) override { 10170 for (UseMemo &Memo : Uses) 10171 if (Memo.User == N) 10172 Memo.User = nullptr; 10173 } 10174 10175 public: 10176 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10177 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10178 }; 10179 10180 } // end anonymous namespace 10181 10182 bool SelectionDAG::calculateDivergence(SDNode *N) { 10183 if (TLI->isSDNodeAlwaysUniform(N)) { 10184 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 10185 "Conflicting divergence information!"); 10186 return false; 10187 } 10188 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 10189 return true; 10190 for (auto &Op : N->ops()) { 10191 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10192 return true; 10193 } 10194 return false; 10195 } 10196 10197 void SelectionDAG::updateDivergence(SDNode *N) { 10198 SmallVector<SDNode *, 16> Worklist(1, N); 10199 do { 10200 N = Worklist.pop_back_val(); 10201 bool IsDivergent = calculateDivergence(N); 10202 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10203 N->SDNodeBits.IsDivergent = IsDivergent; 10204 llvm::append_range(Worklist, N->uses()); 10205 } 10206 } while (!Worklist.empty()); 10207 } 10208 10209 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10210 DenseMap<SDNode *, unsigned> Degree; 10211 Order.reserve(AllNodes.size()); 10212 for (auto &N : allnodes()) { 10213 unsigned NOps = N.getNumOperands(); 10214 Degree[&N] = NOps; 10215 if (0 == NOps) 10216 Order.push_back(&N); 10217 } 10218 for (size_t I = 0; I != Order.size(); ++I) { 10219 SDNode *N = Order[I]; 10220 for (auto U : N->uses()) { 10221 unsigned &UnsortedOps = Degree[U]; 10222 if (0 == --UnsortedOps) 10223 Order.push_back(U); 10224 } 10225 } 10226 } 10227 10228 #ifndef NDEBUG 10229 void SelectionDAG::VerifyDAGDivergence() { 10230 std::vector<SDNode *> TopoOrder; 10231 CreateTopologicalOrder(TopoOrder); 10232 for (auto *N : TopoOrder) { 10233 assert(calculateDivergence(N) == N->isDivergent() && 10234 "Divergence bit inconsistency detected"); 10235 } 10236 } 10237 #endif 10238 10239 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10240 /// uses of other values produced by From.getNode() alone. The same value 10241 /// may appear in both the From and To list. The Deleted vector is 10242 /// handled the same way as for ReplaceAllUsesWith. 10243 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10244 const SDValue *To, 10245 unsigned Num){ 10246 // Handle the simple, trivial case efficiently. 10247 if (Num == 1) 10248 return ReplaceAllUsesOfValueWith(*From, *To); 10249 10250 transferDbgValues(*From, *To); 10251 10252 // Read up all the uses and make records of them. This helps 10253 // processing new uses that are introduced during the 10254 // replacement process. 10255 SmallVector<UseMemo, 4> Uses; 10256 for (unsigned i = 0; i != Num; ++i) { 10257 unsigned FromResNo = From[i].getResNo(); 10258 SDNode *FromNode = From[i].getNode(); 10259 for (SDNode::use_iterator UI = FromNode->use_begin(), 10260 E = FromNode->use_end(); UI != E; ++UI) { 10261 SDUse &Use = UI.getUse(); 10262 if (Use.getResNo() == FromResNo) { 10263 UseMemo Memo = { *UI, i, &Use }; 10264 Uses.push_back(Memo); 10265 } 10266 } 10267 } 10268 10269 // Sort the uses, so that all the uses from a given User are together. 10270 llvm::sort(Uses); 10271 RAUOVWUpdateListener Listener(*this, Uses); 10272 10273 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 10274 UseIndex != UseIndexEnd; ) { 10275 // We know that this user uses some value of From. If it is the right 10276 // value, update it. 10277 SDNode *User = Uses[UseIndex].User; 10278 // If the node has been deleted by recursive CSE updates when updating 10279 // another node, then just skip this entry. 10280 if (User == nullptr) { 10281 ++UseIndex; 10282 continue; 10283 } 10284 10285 // This node is about to morph, remove its old self from the CSE maps. 10286 RemoveNodeFromCSEMaps(User); 10287 10288 // The Uses array is sorted, so all the uses for a given User 10289 // are next to each other in the list. 10290 // To help reduce the number of CSE recomputations, process all 10291 // the uses of this user that we can find this way. 10292 do { 10293 unsigned i = Uses[UseIndex].Index; 10294 SDUse &Use = *Uses[UseIndex].Use; 10295 ++UseIndex; 10296 10297 Use.set(To[i]); 10298 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 10299 10300 // Now that we have modified User, add it back to the CSE maps. If it 10301 // already exists there, recursively merge the results together. 10302 AddModifiedNodeToCSEMaps(User); 10303 } 10304 } 10305 10306 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 10307 /// based on their topological order. It returns the maximum id and a vector 10308 /// of the SDNodes* in assigned order by reference. 10309 unsigned SelectionDAG::AssignTopologicalOrder() { 10310 unsigned DAGSize = 0; 10311 10312 // SortedPos tracks the progress of the algorithm. Nodes before it are 10313 // sorted, nodes after it are unsorted. When the algorithm completes 10314 // it is at the end of the list. 10315 allnodes_iterator SortedPos = allnodes_begin(); 10316 10317 // Visit all the nodes. Move nodes with no operands to the front of 10318 // the list immediately. Annotate nodes that do have operands with their 10319 // operand count. Before we do this, the Node Id fields of the nodes 10320 // may contain arbitrary values. After, the Node Id fields for nodes 10321 // before SortedPos will contain the topological sort index, and the 10322 // Node Id fields for nodes At SortedPos and after will contain the 10323 // count of outstanding operands. 10324 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 10325 checkForCycles(&N, this); 10326 unsigned Degree = N.getNumOperands(); 10327 if (Degree == 0) { 10328 // A node with no uses, add it to the result array immediately. 10329 N.setNodeId(DAGSize++); 10330 allnodes_iterator Q(&N); 10331 if (Q != SortedPos) 10332 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 10333 assert(SortedPos != AllNodes.end() && "Overran node list"); 10334 ++SortedPos; 10335 } else { 10336 // Temporarily use the Node Id as scratch space for the degree count. 10337 N.setNodeId(Degree); 10338 } 10339 } 10340 10341 // Visit all the nodes. As we iterate, move nodes into sorted order, 10342 // such that by the time the end is reached all nodes will be sorted. 10343 for (SDNode &Node : allnodes()) { 10344 SDNode *N = &Node; 10345 checkForCycles(N, this); 10346 // N is in sorted position, so all its uses have one less operand 10347 // that needs to be sorted. 10348 for (SDNode *P : N->uses()) { 10349 unsigned Degree = P->getNodeId(); 10350 assert(Degree != 0 && "Invalid node degree"); 10351 --Degree; 10352 if (Degree == 0) { 10353 // All of P's operands are sorted, so P may sorted now. 10354 P->setNodeId(DAGSize++); 10355 if (P->getIterator() != SortedPos) 10356 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 10357 assert(SortedPos != AllNodes.end() && "Overran node list"); 10358 ++SortedPos; 10359 } else { 10360 // Update P's outstanding operand count. 10361 P->setNodeId(Degree); 10362 } 10363 } 10364 if (Node.getIterator() == SortedPos) { 10365 #ifndef NDEBUG 10366 allnodes_iterator I(N); 10367 SDNode *S = &*++I; 10368 dbgs() << "Overran sorted position:\n"; 10369 S->dumprFull(this); dbgs() << "\n"; 10370 dbgs() << "Checking if this is due to cycles\n"; 10371 checkForCycles(this, true); 10372 #endif 10373 llvm_unreachable(nullptr); 10374 } 10375 } 10376 10377 assert(SortedPos == AllNodes.end() && 10378 "Topological sort incomplete!"); 10379 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 10380 "First node in topological sort is not the entry token!"); 10381 assert(AllNodes.front().getNodeId() == 0 && 10382 "First node in topological sort has non-zero id!"); 10383 assert(AllNodes.front().getNumOperands() == 0 && 10384 "First node in topological sort has operands!"); 10385 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 10386 "Last node in topologic sort has unexpected id!"); 10387 assert(AllNodes.back().use_empty() && 10388 "Last node in topologic sort has users!"); 10389 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 10390 return DAGSize; 10391 } 10392 10393 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 10394 /// value is produced by SD. 10395 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 10396 for (SDNode *SD : DB->getSDNodes()) { 10397 if (!SD) 10398 continue; 10399 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 10400 SD->setHasDebugValue(true); 10401 } 10402 DbgInfo->add(DB, isParameter); 10403 } 10404 10405 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 10406 10407 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 10408 SDValue NewMemOpChain) { 10409 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 10410 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 10411 // The new memory operation must have the same position as the old load in 10412 // terms of memory dependency. Create a TokenFactor for the old load and new 10413 // memory operation and update uses of the old load's output chain to use that 10414 // TokenFactor. 10415 if (OldChain == NewMemOpChain || OldChain.use_empty()) 10416 return NewMemOpChain; 10417 10418 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 10419 OldChain, NewMemOpChain); 10420 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 10421 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 10422 return TokenFactor; 10423 } 10424 10425 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 10426 SDValue NewMemOp) { 10427 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 10428 SDValue OldChain = SDValue(OldLoad, 1); 10429 SDValue NewMemOpChain = NewMemOp.getValue(1); 10430 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 10431 } 10432 10433 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 10434 Function **OutFunction) { 10435 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 10436 10437 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 10438 auto *Module = MF->getFunction().getParent(); 10439 auto *Function = Module->getFunction(Symbol); 10440 10441 if (OutFunction != nullptr) 10442 *OutFunction = Function; 10443 10444 if (Function != nullptr) { 10445 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 10446 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 10447 } 10448 10449 std::string ErrorStr; 10450 raw_string_ostream ErrorFormatter(ErrorStr); 10451 ErrorFormatter << "Undefined external symbol "; 10452 ErrorFormatter << '"' << Symbol << '"'; 10453 report_fatal_error(Twine(ErrorFormatter.str())); 10454 } 10455 10456 //===----------------------------------------------------------------------===// 10457 // SDNode Class 10458 //===----------------------------------------------------------------------===// 10459 10460 bool llvm::isNullConstant(SDValue V) { 10461 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10462 return Const != nullptr && Const->isZero(); 10463 } 10464 10465 bool llvm::isNullFPConstant(SDValue V) { 10466 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10467 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10468 } 10469 10470 bool llvm::isAllOnesConstant(SDValue V) { 10471 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10472 return Const != nullptr && Const->isAllOnes(); 10473 } 10474 10475 bool llvm::isOneConstant(SDValue V) { 10476 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10477 return Const != nullptr && Const->isOne(); 10478 } 10479 10480 bool llvm::isMinSignedConstant(SDValue V) { 10481 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10482 return Const != nullptr && Const->isMinSignedValue(); 10483 } 10484 10485 SDValue llvm::peekThroughBitcasts(SDValue V) { 10486 while (V.getOpcode() == ISD::BITCAST) 10487 V = V.getOperand(0); 10488 return V; 10489 } 10490 10491 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10492 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10493 V = V.getOperand(0); 10494 return V; 10495 } 10496 10497 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10498 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10499 V = V.getOperand(0); 10500 return V; 10501 } 10502 10503 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10504 if (V.getOpcode() != ISD::XOR) 10505 return false; 10506 V = peekThroughBitcasts(V.getOperand(1)); 10507 unsigned NumBits = V.getScalarValueSizeInBits(); 10508 ConstantSDNode *C = 10509 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10510 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10511 } 10512 10513 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10514 bool AllowTruncation) { 10515 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10516 return CN; 10517 10518 // SplatVectors can truncate their operands. Ignore that case here unless 10519 // AllowTruncation is set. 10520 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10521 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10522 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10523 EVT CVT = CN->getValueType(0); 10524 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10525 if (AllowTruncation || CVT == VecEltVT) 10526 return CN; 10527 } 10528 } 10529 10530 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10531 BitVector UndefElements; 10532 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10533 10534 // BuildVectors can truncate their operands. Ignore that case here unless 10535 // AllowTruncation is set. 10536 if (CN && (UndefElements.none() || AllowUndefs)) { 10537 EVT CVT = CN->getValueType(0); 10538 EVT NSVT = N.getValueType().getScalarType(); 10539 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10540 if (AllowTruncation || (CVT == NSVT)) 10541 return CN; 10542 } 10543 } 10544 10545 return nullptr; 10546 } 10547 10548 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10549 bool AllowUndefs, 10550 bool AllowTruncation) { 10551 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10552 return CN; 10553 10554 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10555 BitVector UndefElements; 10556 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10557 10558 // BuildVectors can truncate their operands. Ignore that case here unless 10559 // AllowTruncation is set. 10560 if (CN && (UndefElements.none() || AllowUndefs)) { 10561 EVT CVT = CN->getValueType(0); 10562 EVT NSVT = N.getValueType().getScalarType(); 10563 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10564 if (AllowTruncation || (CVT == NSVT)) 10565 return CN; 10566 } 10567 } 10568 10569 return nullptr; 10570 } 10571 10572 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10573 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10574 return CN; 10575 10576 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10577 BitVector UndefElements; 10578 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10579 if (CN && (UndefElements.none() || AllowUndefs)) 10580 return CN; 10581 } 10582 10583 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10584 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10585 return CN; 10586 10587 return nullptr; 10588 } 10589 10590 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10591 const APInt &DemandedElts, 10592 bool AllowUndefs) { 10593 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10594 return CN; 10595 10596 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10597 BitVector UndefElements; 10598 ConstantFPSDNode *CN = 10599 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10600 if (CN && (UndefElements.none() || AllowUndefs)) 10601 return CN; 10602 } 10603 10604 return nullptr; 10605 } 10606 10607 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10608 // TODO: may want to use peekThroughBitcast() here. 10609 ConstantSDNode *C = 10610 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10611 return C && C->isZero(); 10612 } 10613 10614 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10615 // TODO: may want to use peekThroughBitcast() here. 10616 unsigned BitWidth = N.getScalarValueSizeInBits(); 10617 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10618 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10619 } 10620 10621 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10622 N = peekThroughBitcasts(N); 10623 unsigned BitWidth = N.getScalarValueSizeInBits(); 10624 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10625 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10626 } 10627 10628 HandleSDNode::~HandleSDNode() { 10629 DropOperands(); 10630 } 10631 10632 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10633 const DebugLoc &DL, 10634 const GlobalValue *GA, EVT VT, 10635 int64_t o, unsigned TF) 10636 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10637 TheGlobal = GA; 10638 } 10639 10640 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10641 EVT VT, unsigned SrcAS, 10642 unsigned DestAS) 10643 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10644 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10645 10646 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10647 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10648 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10649 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10650 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10651 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10652 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10653 10654 // We check here that the size of the memory operand fits within the size of 10655 // the MMO. This is because the MMO might indicate only a possible address 10656 // range instead of specifying the affected memory addresses precisely. 10657 // TODO: Make MachineMemOperands aware of scalable vectors. 10658 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10659 "Size mismatch!"); 10660 } 10661 10662 /// Profile - Gather unique data for the node. 10663 /// 10664 void SDNode::Profile(FoldingSetNodeID &ID) const { 10665 AddNodeIDNode(ID, this); 10666 } 10667 10668 namespace { 10669 10670 struct EVTArray { 10671 std::vector<EVT> VTs; 10672 10673 EVTArray() { 10674 VTs.reserve(MVT::VALUETYPE_SIZE); 10675 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10676 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10677 } 10678 }; 10679 10680 } // end anonymous namespace 10681 10682 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10683 static ManagedStatic<EVTArray> SimpleVTArray; 10684 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10685 10686 /// getValueTypeList - Return a pointer to the specified value type. 10687 /// 10688 const EVT *SDNode::getValueTypeList(EVT VT) { 10689 if (VT.isExtended()) { 10690 sys::SmartScopedLock<true> Lock(*VTMutex); 10691 return &(*EVTs->insert(VT).first); 10692 } 10693 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10694 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10695 } 10696 10697 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10698 /// indicated value. This method ignores uses of other values defined by this 10699 /// operation. 10700 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10701 assert(Value < getNumValues() && "Bad value!"); 10702 10703 // TODO: Only iterate over uses of a given value of the node 10704 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10705 if (UI.getUse().getResNo() == Value) { 10706 if (NUses == 0) 10707 return false; 10708 --NUses; 10709 } 10710 } 10711 10712 // Found exactly the right number of uses? 10713 return NUses == 0; 10714 } 10715 10716 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10717 /// value. This method ignores uses of other values defined by this operation. 10718 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10719 assert(Value < getNumValues() && "Bad value!"); 10720 10721 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10722 if (UI.getUse().getResNo() == Value) 10723 return true; 10724 10725 return false; 10726 } 10727 10728 /// isOnlyUserOf - Return true if this node is the only use of N. 10729 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10730 bool Seen = false; 10731 for (const SDNode *User : N->uses()) { 10732 if (User == this) 10733 Seen = true; 10734 else 10735 return false; 10736 } 10737 10738 return Seen; 10739 } 10740 10741 /// Return true if the only users of N are contained in Nodes. 10742 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10743 bool Seen = false; 10744 for (const SDNode *User : N->uses()) { 10745 if (llvm::is_contained(Nodes, User)) 10746 Seen = true; 10747 else 10748 return false; 10749 } 10750 10751 return Seen; 10752 } 10753 10754 /// isOperand - Return true if this node is an operand of N. 10755 bool SDValue::isOperandOf(const SDNode *N) const { 10756 return is_contained(N->op_values(), *this); 10757 } 10758 10759 bool SDNode::isOperandOf(const SDNode *N) const { 10760 return any_of(N->op_values(), 10761 [this](SDValue Op) { return this == Op.getNode(); }); 10762 } 10763 10764 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10765 /// be a chain) reaches the specified operand without crossing any 10766 /// side-effecting instructions on any chain path. In practice, this looks 10767 /// through token factors and non-volatile loads. In order to remain efficient, 10768 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10769 /// 10770 /// Note that we only need to examine chains when we're searching for 10771 /// side-effects; SelectionDAG requires that all side-effects are represented 10772 /// by chains, even if another operand would force a specific ordering. This 10773 /// constraint is necessary to allow transformations like splitting loads. 10774 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10775 unsigned Depth) const { 10776 if (*this == Dest) return true; 10777 10778 // Don't search too deeply, we just want to be able to see through 10779 // TokenFactor's etc. 10780 if (Depth == 0) return false; 10781 10782 // If this is a token factor, all inputs to the TF happen in parallel. 10783 if (getOpcode() == ISD::TokenFactor) { 10784 // First, try a shallow search. 10785 if (is_contained((*this)->ops(), Dest)) { 10786 // We found the chain we want as an operand of this TokenFactor. 10787 // Essentially, we reach the chain without side-effects if we could 10788 // serialize the TokenFactor into a simple chain of operations with 10789 // Dest as the last operation. This is automatically true if the 10790 // chain has one use: there are no other ordering constraints. 10791 // If the chain has more than one use, we give up: some other 10792 // use of Dest might force a side-effect between Dest and the current 10793 // node. 10794 if (Dest.hasOneUse()) 10795 return true; 10796 } 10797 // Next, try a deep search: check whether every operand of the TokenFactor 10798 // reaches Dest. 10799 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10800 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10801 }); 10802 } 10803 10804 // Loads don't have side effects, look through them. 10805 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10806 if (Ld->isUnordered()) 10807 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10808 } 10809 return false; 10810 } 10811 10812 bool SDNode::hasPredecessor(const SDNode *N) const { 10813 SmallPtrSet<const SDNode *, 32> Visited; 10814 SmallVector<const SDNode *, 16> Worklist; 10815 Worklist.push_back(this); 10816 return hasPredecessorHelper(N, Visited, Worklist); 10817 } 10818 10819 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10820 this->Flags.intersectWith(Flags); 10821 } 10822 10823 SDValue 10824 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10825 ArrayRef<ISD::NodeType> CandidateBinOps, 10826 bool AllowPartials) { 10827 // The pattern must end in an extract from index 0. 10828 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10829 !isNullConstant(Extract->getOperand(1))) 10830 return SDValue(); 10831 10832 // Match against one of the candidate binary ops. 10833 SDValue Op = Extract->getOperand(0); 10834 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10835 return Op.getOpcode() == unsigned(BinOp); 10836 })) 10837 return SDValue(); 10838 10839 // Floating-point reductions may require relaxed constraints on the final step 10840 // of the reduction because they may reorder intermediate operations. 10841 unsigned CandidateBinOp = Op.getOpcode(); 10842 if (Op.getValueType().isFloatingPoint()) { 10843 SDNodeFlags Flags = Op->getFlags(); 10844 switch (CandidateBinOp) { 10845 case ISD::FADD: 10846 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10847 return SDValue(); 10848 break; 10849 default: 10850 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10851 } 10852 } 10853 10854 // Matching failed - attempt to see if we did enough stages that a partial 10855 // reduction from a subvector is possible. 10856 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10857 if (!AllowPartials || !Op) 10858 return SDValue(); 10859 EVT OpVT = Op.getValueType(); 10860 EVT OpSVT = OpVT.getScalarType(); 10861 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10862 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10863 return SDValue(); 10864 BinOp = (ISD::NodeType)CandidateBinOp; 10865 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10866 getVectorIdxConstant(0, SDLoc(Op))); 10867 }; 10868 10869 // At each stage, we're looking for something that looks like: 10870 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10871 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10872 // i32 undef, i32 undef, i32 undef, i32 undef> 10873 // %a = binop <8 x i32> %op, %s 10874 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10875 // we expect something like: 10876 // <4,5,6,7,u,u,u,u> 10877 // <2,3,u,u,u,u,u,u> 10878 // <1,u,u,u,u,u,u,u> 10879 // While a partial reduction match would be: 10880 // <2,3,u,u,u,u,u,u> 10881 // <1,u,u,u,u,u,u,u> 10882 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10883 SDValue PrevOp; 10884 for (unsigned i = 0; i < Stages; ++i) { 10885 unsigned MaskEnd = (1 << i); 10886 10887 if (Op.getOpcode() != CandidateBinOp) 10888 return PartialReduction(PrevOp, MaskEnd); 10889 10890 SDValue Op0 = Op.getOperand(0); 10891 SDValue Op1 = Op.getOperand(1); 10892 10893 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10894 if (Shuffle) { 10895 Op = Op1; 10896 } else { 10897 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10898 Op = Op0; 10899 } 10900 10901 // The first operand of the shuffle should be the same as the other operand 10902 // of the binop. 10903 if (!Shuffle || Shuffle->getOperand(0) != Op) 10904 return PartialReduction(PrevOp, MaskEnd); 10905 10906 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10907 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10908 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10909 return PartialReduction(PrevOp, MaskEnd); 10910 10911 PrevOp = Op; 10912 } 10913 10914 // Handle subvector reductions, which tend to appear after the shuffle 10915 // reduction stages. 10916 while (Op.getOpcode() == CandidateBinOp) { 10917 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10918 SDValue Op0 = Op.getOperand(0); 10919 SDValue Op1 = Op.getOperand(1); 10920 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10921 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10922 Op0.getOperand(0) != Op1.getOperand(0)) 10923 break; 10924 SDValue Src = Op0.getOperand(0); 10925 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10926 if (NumSrcElts != (2 * NumElts)) 10927 break; 10928 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10929 Op1.getConstantOperandAPInt(1) == NumElts) && 10930 !(Op1.getConstantOperandAPInt(1) == 0 && 10931 Op0.getConstantOperandAPInt(1) == NumElts)) 10932 break; 10933 Op = Src; 10934 } 10935 10936 BinOp = (ISD::NodeType)CandidateBinOp; 10937 return Op; 10938 } 10939 10940 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10941 assert(N->getNumValues() == 1 && 10942 "Can't unroll a vector with multiple results!"); 10943 10944 EVT VT = N->getValueType(0); 10945 unsigned NE = VT.getVectorNumElements(); 10946 EVT EltVT = VT.getVectorElementType(); 10947 SDLoc dl(N); 10948 10949 SmallVector<SDValue, 8> Scalars; 10950 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10951 10952 // If ResNE is 0, fully unroll the vector op. 10953 if (ResNE == 0) 10954 ResNE = NE; 10955 else if (NE > ResNE) 10956 NE = ResNE; 10957 10958 unsigned i; 10959 for (i= 0; i != NE; ++i) { 10960 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10961 SDValue Operand = N->getOperand(j); 10962 EVT OperandVT = Operand.getValueType(); 10963 if (OperandVT.isVector()) { 10964 // A vector operand; extract a single element. 10965 EVT OperandEltVT = OperandVT.getVectorElementType(); 10966 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10967 Operand, getVectorIdxConstant(i, dl)); 10968 } else { 10969 // A scalar operand; just use it as is. 10970 Operands[j] = Operand; 10971 } 10972 } 10973 10974 switch (N->getOpcode()) { 10975 default: { 10976 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10977 N->getFlags())); 10978 break; 10979 } 10980 case ISD::VSELECT: 10981 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10982 break; 10983 case ISD::SHL: 10984 case ISD::SRA: 10985 case ISD::SRL: 10986 case ISD::ROTL: 10987 case ISD::ROTR: 10988 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10989 getShiftAmountOperand(Operands[0].getValueType(), 10990 Operands[1]))); 10991 break; 10992 case ISD::SIGN_EXTEND_INREG: { 10993 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10994 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10995 Operands[0], 10996 getValueType(ExtVT))); 10997 } 10998 } 10999 } 11000 11001 for (; i < ResNE; ++i) 11002 Scalars.push_back(getUNDEF(EltVT)); 11003 11004 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 11005 return getBuildVector(VecVT, dl, Scalars); 11006 } 11007 11008 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 11009 SDNode *N, unsigned ResNE) { 11010 unsigned Opcode = N->getOpcode(); 11011 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 11012 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 11013 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 11014 "Expected an overflow opcode"); 11015 11016 EVT ResVT = N->getValueType(0); 11017 EVT OvVT = N->getValueType(1); 11018 EVT ResEltVT = ResVT.getVectorElementType(); 11019 EVT OvEltVT = OvVT.getVectorElementType(); 11020 SDLoc dl(N); 11021 11022 // If ResNE is 0, fully unroll the vector op. 11023 unsigned NE = ResVT.getVectorNumElements(); 11024 if (ResNE == 0) 11025 ResNE = NE; 11026 else if (NE > ResNE) 11027 NE = ResNE; 11028 11029 SmallVector<SDValue, 8> LHSScalars; 11030 SmallVector<SDValue, 8> RHSScalars; 11031 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 11032 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 11033 11034 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 11035 SDVTList VTs = getVTList(ResEltVT, SVT); 11036 SmallVector<SDValue, 8> ResScalars; 11037 SmallVector<SDValue, 8> OvScalars; 11038 for (unsigned i = 0; i < NE; ++i) { 11039 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 11040 SDValue Ov = 11041 getSelect(dl, OvEltVT, Res.getValue(1), 11042 getBoolConstant(true, dl, OvEltVT, ResVT), 11043 getConstant(0, dl, OvEltVT)); 11044 11045 ResScalars.push_back(Res); 11046 OvScalars.push_back(Ov); 11047 } 11048 11049 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 11050 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 11051 11052 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 11053 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 11054 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 11055 getBuildVector(NewOvVT, dl, OvScalars)); 11056 } 11057 11058 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 11059 LoadSDNode *Base, 11060 unsigned Bytes, 11061 int Dist) const { 11062 if (LD->isVolatile() || Base->isVolatile()) 11063 return false; 11064 // TODO: probably too restrictive for atomics, revisit 11065 if (!LD->isSimple()) 11066 return false; 11067 if (LD->isIndexed() || Base->isIndexed()) 11068 return false; 11069 if (LD->getChain() != Base->getChain()) 11070 return false; 11071 EVT VT = LD->getValueType(0); 11072 if (VT.getSizeInBits() / 8 != Bytes) 11073 return false; 11074 11075 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 11076 auto LocDecomp = BaseIndexOffset::match(LD, *this); 11077 11078 int64_t Offset = 0; 11079 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 11080 return (Dist * Bytes == Offset); 11081 return false; 11082 } 11083 11084 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 11085 /// if it cannot be inferred. 11086 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 11087 // If this is a GlobalAddress + cst, return the alignment. 11088 const GlobalValue *GV = nullptr; 11089 int64_t GVOffset = 0; 11090 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 11091 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 11092 KnownBits Known(PtrWidth); 11093 llvm::computeKnownBits(GV, Known, getDataLayout()); 11094 unsigned AlignBits = Known.countMinTrailingZeros(); 11095 if (AlignBits) 11096 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11097 } 11098 11099 // If this is a direct reference to a stack slot, use information about the 11100 // stack slot's alignment. 11101 int FrameIdx = INT_MIN; 11102 int64_t FrameOffset = 0; 11103 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11104 FrameIdx = FI->getIndex(); 11105 } else if (isBaseWithConstantOffset(Ptr) && 11106 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11107 // Handle FI+Cst 11108 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11109 FrameOffset = Ptr.getConstantOperandVal(1); 11110 } 11111 11112 if (FrameIdx != INT_MIN) { 11113 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11114 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11115 } 11116 11117 return None; 11118 } 11119 11120 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11121 /// which is split (or expanded) into two not necessarily identical pieces. 11122 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11123 // Currently all types are split in half. 11124 EVT LoVT, HiVT; 11125 if (!VT.isVector()) 11126 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11127 else 11128 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11129 11130 return std::make_pair(LoVT, HiVT); 11131 } 11132 11133 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11134 /// type, dependent on an enveloping VT that has been split into two identical 11135 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11136 std::pair<EVT, EVT> 11137 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11138 bool *HiIsEmpty) const { 11139 EVT EltTp = VT.getVectorElementType(); 11140 // Examples: 11141 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11142 // custom VL=9 with enveloping VL=8/8 yields 8/1 11143 // custom VL=10 with enveloping VL=8/8 yields 8/2 11144 // etc. 11145 ElementCount VTNumElts = VT.getVectorElementCount(); 11146 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11147 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11148 "Mixing fixed width and scalable vectors when enveloping a type"); 11149 EVT LoVT, HiVT; 11150 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11151 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11152 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11153 *HiIsEmpty = false; 11154 } else { 11155 // Flag that hi type has zero storage size, but return split envelop type 11156 // (this would be easier if vector types with zero elements were allowed). 11157 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11158 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11159 *HiIsEmpty = true; 11160 } 11161 return std::make_pair(LoVT, HiVT); 11162 } 11163 11164 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11165 /// low/high part. 11166 std::pair<SDValue, SDValue> 11167 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11168 const EVT &HiVT) { 11169 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 11170 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 11171 "Splitting vector with an invalid mixture of fixed and scalable " 11172 "vector types"); 11173 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 11174 N.getValueType().getVectorMinNumElements() && 11175 "More vector elements requested than available!"); 11176 SDValue Lo, Hi; 11177 Lo = 11178 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 11179 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 11180 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 11181 // IDX with the runtime scaling factor of the result vector type. For 11182 // fixed-width result vectors, that runtime scaling factor is 1. 11183 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 11184 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 11185 return std::make_pair(Lo, Hi); 11186 } 11187 11188 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 11189 const SDLoc &DL) { 11190 // Split the vector length parameter. 11191 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 11192 EVT VT = N.getValueType(); 11193 assert(VecVT.getVectorElementCount().isKnownEven() && 11194 "Expecting the mask to be an evenly-sized vector"); 11195 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 11196 SDValue HalfNumElts = 11197 VecVT.isFixedLengthVector() 11198 ? getConstant(HalfMinNumElts, DL, VT) 11199 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 11200 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 11201 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 11202 return std::make_pair(Lo, Hi); 11203 } 11204 11205 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 11206 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 11207 EVT VT = N.getValueType(); 11208 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 11209 NextPowerOf2(VT.getVectorNumElements())); 11210 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 11211 getVectorIdxConstant(0, DL)); 11212 } 11213 11214 void SelectionDAG::ExtractVectorElements(SDValue Op, 11215 SmallVectorImpl<SDValue> &Args, 11216 unsigned Start, unsigned Count, 11217 EVT EltVT) { 11218 EVT VT = Op.getValueType(); 11219 if (Count == 0) 11220 Count = VT.getVectorNumElements(); 11221 if (EltVT == EVT()) 11222 EltVT = VT.getVectorElementType(); 11223 SDLoc SL(Op); 11224 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 11225 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 11226 getVectorIdxConstant(i, SL))); 11227 } 11228 } 11229 11230 // getAddressSpace - Return the address space this GlobalAddress belongs to. 11231 unsigned GlobalAddressSDNode::getAddressSpace() const { 11232 return getGlobal()->getType()->getAddressSpace(); 11233 } 11234 11235 Type *ConstantPoolSDNode::getType() const { 11236 if (isMachineConstantPoolEntry()) 11237 return Val.MachineCPVal->getType(); 11238 return Val.ConstVal->getType(); 11239 } 11240 11241 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 11242 unsigned &SplatBitSize, 11243 bool &HasAnyUndefs, 11244 unsigned MinSplatBits, 11245 bool IsBigEndian) const { 11246 EVT VT = getValueType(0); 11247 assert(VT.isVector() && "Expected a vector type"); 11248 unsigned VecWidth = VT.getSizeInBits(); 11249 if (MinSplatBits > VecWidth) 11250 return false; 11251 11252 // FIXME: The widths are based on this node's type, but build vectors can 11253 // truncate their operands. 11254 SplatValue = APInt(VecWidth, 0); 11255 SplatUndef = APInt(VecWidth, 0); 11256 11257 // Get the bits. Bits with undefined values (when the corresponding element 11258 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 11259 // in SplatValue. If any of the values are not constant, give up and return 11260 // false. 11261 unsigned int NumOps = getNumOperands(); 11262 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 11263 unsigned EltWidth = VT.getScalarSizeInBits(); 11264 11265 for (unsigned j = 0; j < NumOps; ++j) { 11266 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 11267 SDValue OpVal = getOperand(i); 11268 unsigned BitPos = j * EltWidth; 11269 11270 if (OpVal.isUndef()) 11271 SplatUndef.setBits(BitPos, BitPos + EltWidth); 11272 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 11273 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 11274 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 11275 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 11276 else 11277 return false; 11278 } 11279 11280 // The build_vector is all constants or undefs. Find the smallest element 11281 // size that splats the vector. 11282 HasAnyUndefs = (SplatUndef != 0); 11283 11284 // FIXME: This does not work for vectors with elements less than 8 bits. 11285 while (VecWidth > 8) { 11286 unsigned HalfSize = VecWidth / 2; 11287 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 11288 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 11289 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 11290 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 11291 11292 // If the two halves do not match (ignoring undef bits), stop here. 11293 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 11294 MinSplatBits > HalfSize) 11295 break; 11296 11297 SplatValue = HighValue | LowValue; 11298 SplatUndef = HighUndef & LowUndef; 11299 11300 VecWidth = HalfSize; 11301 } 11302 11303 SplatBitSize = VecWidth; 11304 return true; 11305 } 11306 11307 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 11308 BitVector *UndefElements) const { 11309 unsigned NumOps = getNumOperands(); 11310 if (UndefElements) { 11311 UndefElements->clear(); 11312 UndefElements->resize(NumOps); 11313 } 11314 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11315 if (!DemandedElts) 11316 return SDValue(); 11317 SDValue Splatted; 11318 for (unsigned i = 0; i != NumOps; ++i) { 11319 if (!DemandedElts[i]) 11320 continue; 11321 SDValue Op = getOperand(i); 11322 if (Op.isUndef()) { 11323 if (UndefElements) 11324 (*UndefElements)[i] = true; 11325 } else if (!Splatted) { 11326 Splatted = Op; 11327 } else if (Splatted != Op) { 11328 return SDValue(); 11329 } 11330 } 11331 11332 if (!Splatted) { 11333 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 11334 assert(getOperand(FirstDemandedIdx).isUndef() && 11335 "Can only have a splat without a constant for all undefs."); 11336 return getOperand(FirstDemandedIdx); 11337 } 11338 11339 return Splatted; 11340 } 11341 11342 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 11343 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11344 return getSplatValue(DemandedElts, UndefElements); 11345 } 11346 11347 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 11348 SmallVectorImpl<SDValue> &Sequence, 11349 BitVector *UndefElements) const { 11350 unsigned NumOps = getNumOperands(); 11351 Sequence.clear(); 11352 if (UndefElements) { 11353 UndefElements->clear(); 11354 UndefElements->resize(NumOps); 11355 } 11356 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11357 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 11358 return false; 11359 11360 // Set the undefs even if we don't find a sequence (like getSplatValue). 11361 if (UndefElements) 11362 for (unsigned I = 0; I != NumOps; ++I) 11363 if (DemandedElts[I] && getOperand(I).isUndef()) 11364 (*UndefElements)[I] = true; 11365 11366 // Iteratively widen the sequence length looking for repetitions. 11367 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 11368 Sequence.append(SeqLen, SDValue()); 11369 for (unsigned I = 0; I != NumOps; ++I) { 11370 if (!DemandedElts[I]) 11371 continue; 11372 SDValue &SeqOp = Sequence[I % SeqLen]; 11373 SDValue Op = getOperand(I); 11374 if (Op.isUndef()) { 11375 if (!SeqOp) 11376 SeqOp = Op; 11377 continue; 11378 } 11379 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 11380 Sequence.clear(); 11381 break; 11382 } 11383 SeqOp = Op; 11384 } 11385 if (!Sequence.empty()) 11386 return true; 11387 } 11388 11389 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 11390 return false; 11391 } 11392 11393 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 11394 BitVector *UndefElements) const { 11395 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11396 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 11397 } 11398 11399 ConstantSDNode * 11400 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 11401 BitVector *UndefElements) const { 11402 return dyn_cast_or_null<ConstantSDNode>( 11403 getSplatValue(DemandedElts, UndefElements)); 11404 } 11405 11406 ConstantSDNode * 11407 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 11408 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 11409 } 11410 11411 ConstantFPSDNode * 11412 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 11413 BitVector *UndefElements) const { 11414 return dyn_cast_or_null<ConstantFPSDNode>( 11415 getSplatValue(DemandedElts, UndefElements)); 11416 } 11417 11418 ConstantFPSDNode * 11419 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 11420 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 11421 } 11422 11423 int32_t 11424 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 11425 uint32_t BitWidth) const { 11426 if (ConstantFPSDNode *CN = 11427 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 11428 bool IsExact; 11429 APSInt IntVal(BitWidth); 11430 const APFloat &APF = CN->getValueAPF(); 11431 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 11432 APFloat::opOK || 11433 !IsExact) 11434 return -1; 11435 11436 return IntVal.exactLogBase2(); 11437 } 11438 return -1; 11439 } 11440 11441 bool BuildVectorSDNode::getConstantRawBits( 11442 bool IsLittleEndian, unsigned DstEltSizeInBits, 11443 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 11444 // Early-out if this contains anything but Undef/Constant/ConstantFP. 11445 if (!isConstant()) 11446 return false; 11447 11448 unsigned NumSrcOps = getNumOperands(); 11449 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 11450 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11451 "Invalid bitcast scale"); 11452 11453 // Extract raw src bits. 11454 SmallVector<APInt> SrcBitElements(NumSrcOps, 11455 APInt::getNullValue(SrcEltSizeInBits)); 11456 BitVector SrcUndeElements(NumSrcOps, false); 11457 11458 for (unsigned I = 0; I != NumSrcOps; ++I) { 11459 SDValue Op = getOperand(I); 11460 if (Op.isUndef()) { 11461 SrcUndeElements.set(I); 11462 continue; 11463 } 11464 auto *CInt = dyn_cast<ConstantSDNode>(Op); 11465 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 11466 assert((CInt || CFP) && "Unknown constant"); 11467 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits) 11468 : CFP->getValueAPF().bitcastToAPInt(); 11469 } 11470 11471 // Recast to dst width. 11472 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11473 SrcBitElements, UndefElements, SrcUndeElements); 11474 return true; 11475 } 11476 11477 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11478 unsigned DstEltSizeInBits, 11479 SmallVectorImpl<APInt> &DstBitElements, 11480 ArrayRef<APInt> SrcBitElements, 11481 BitVector &DstUndefElements, 11482 const BitVector &SrcUndefElements) { 11483 unsigned NumSrcOps = SrcBitElements.size(); 11484 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11485 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11486 "Invalid bitcast scale"); 11487 assert(NumSrcOps == SrcUndefElements.size() && 11488 "Vector size mismatch"); 11489 11490 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11491 DstUndefElements.clear(); 11492 DstUndefElements.resize(NumDstOps, false); 11493 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11494 11495 // Concatenate src elements constant bits together into dst element. 11496 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11497 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11498 for (unsigned I = 0; I != NumDstOps; ++I) { 11499 DstUndefElements.set(I); 11500 APInt &DstBits = DstBitElements[I]; 11501 for (unsigned J = 0; J != Scale; ++J) { 11502 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11503 if (SrcUndefElements[Idx]) 11504 continue; 11505 DstUndefElements.reset(I); 11506 const APInt &SrcBits = SrcBitElements[Idx]; 11507 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11508 "Illegal constant bitwidths"); 11509 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11510 } 11511 } 11512 return; 11513 } 11514 11515 // Split src element constant bits into dst elements. 11516 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11517 for (unsigned I = 0; I != NumSrcOps; ++I) { 11518 if (SrcUndefElements[I]) { 11519 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11520 continue; 11521 } 11522 const APInt &SrcBits = SrcBitElements[I]; 11523 for (unsigned J = 0; J != Scale; ++J) { 11524 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11525 APInt &DstBits = DstBitElements[Idx]; 11526 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11527 } 11528 } 11529 } 11530 11531 bool BuildVectorSDNode::isConstant() const { 11532 for (const SDValue &Op : op_values()) { 11533 unsigned Opc = Op.getOpcode(); 11534 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11535 return false; 11536 } 11537 return true; 11538 } 11539 11540 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11541 // Find the first non-undef value in the shuffle mask. 11542 unsigned i, e; 11543 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11544 /* search */; 11545 11546 // If all elements are undefined, this shuffle can be considered a splat 11547 // (although it should eventually get simplified away completely). 11548 if (i == e) 11549 return true; 11550 11551 // Make sure all remaining elements are either undef or the same as the first 11552 // non-undef value. 11553 for (int Idx = Mask[i]; i != e; ++i) 11554 if (Mask[i] >= 0 && Mask[i] != Idx) 11555 return false; 11556 return true; 11557 } 11558 11559 // Returns the SDNode if it is a constant integer BuildVector 11560 // or constant integer. 11561 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11562 if (isa<ConstantSDNode>(N)) 11563 return N.getNode(); 11564 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11565 return N.getNode(); 11566 // Treat a GlobalAddress supporting constant offset folding as a 11567 // constant integer. 11568 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11569 if (GA->getOpcode() == ISD::GlobalAddress && 11570 TLI->isOffsetFoldingLegal(GA)) 11571 return GA; 11572 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11573 isa<ConstantSDNode>(N.getOperand(0))) 11574 return N.getNode(); 11575 return nullptr; 11576 } 11577 11578 // Returns the SDNode if it is a constant float BuildVector 11579 // or constant float. 11580 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11581 if (isa<ConstantFPSDNode>(N)) 11582 return N.getNode(); 11583 11584 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11585 return N.getNode(); 11586 11587 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11588 isa<ConstantFPSDNode>(N.getOperand(0))) 11589 return N.getNode(); 11590 11591 return nullptr; 11592 } 11593 11594 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11595 assert(!Node->OperandList && "Node already has operands"); 11596 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11597 "too many operands to fit into SDNode"); 11598 SDUse *Ops = OperandRecycler.allocate( 11599 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11600 11601 bool IsDivergent = false; 11602 for (unsigned I = 0; I != Vals.size(); ++I) { 11603 Ops[I].setUser(Node); 11604 Ops[I].setInitial(Vals[I]); 11605 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11606 IsDivergent |= Ops[I].getNode()->isDivergent(); 11607 } 11608 Node->NumOperands = Vals.size(); 11609 Node->OperandList = Ops; 11610 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11611 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11612 Node->SDNodeBits.IsDivergent = IsDivergent; 11613 } 11614 checkForCycles(Node); 11615 } 11616 11617 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11618 SmallVectorImpl<SDValue> &Vals) { 11619 size_t Limit = SDNode::getMaxNumOperands(); 11620 while (Vals.size() > Limit) { 11621 unsigned SliceIdx = Vals.size() - Limit; 11622 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11623 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11624 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11625 Vals.emplace_back(NewTF); 11626 } 11627 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11628 } 11629 11630 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11631 EVT VT, SDNodeFlags Flags) { 11632 switch (Opcode) { 11633 default: 11634 return SDValue(); 11635 case ISD::ADD: 11636 case ISD::OR: 11637 case ISD::XOR: 11638 case ISD::UMAX: 11639 return getConstant(0, DL, VT); 11640 case ISD::MUL: 11641 return getConstant(1, DL, VT); 11642 case ISD::AND: 11643 case ISD::UMIN: 11644 return getAllOnesConstant(DL, VT); 11645 case ISD::SMAX: 11646 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11647 case ISD::SMIN: 11648 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11649 case ISD::FADD: 11650 return getConstantFP(-0.0, DL, VT); 11651 case ISD::FMUL: 11652 return getConstantFP(1.0, DL, VT); 11653 case ISD::FMINNUM: 11654 case ISD::FMAXNUM: { 11655 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11656 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11657 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11658 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11659 APFloat::getLargest(Semantics); 11660 if (Opcode == ISD::FMAXNUM) 11661 NeutralAF.changeSign(); 11662 11663 return getConstantFP(NeutralAF, DL, VT); 11664 } 11665 } 11666 } 11667 11668 #ifndef NDEBUG 11669 static void checkForCyclesHelper(const SDNode *N, 11670 SmallPtrSetImpl<const SDNode*> &Visited, 11671 SmallPtrSetImpl<const SDNode*> &Checked, 11672 const llvm::SelectionDAG *DAG) { 11673 // If this node has already been checked, don't check it again. 11674 if (Checked.count(N)) 11675 return; 11676 11677 // If a node has already been visited on this depth-first walk, reject it as 11678 // a cycle. 11679 if (!Visited.insert(N).second) { 11680 errs() << "Detected cycle in SelectionDAG\n"; 11681 dbgs() << "Offending node:\n"; 11682 N->dumprFull(DAG); dbgs() << "\n"; 11683 abort(); 11684 } 11685 11686 for (const SDValue &Op : N->op_values()) 11687 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11688 11689 Checked.insert(N); 11690 Visited.erase(N); 11691 } 11692 #endif 11693 11694 void llvm::checkForCycles(const llvm::SDNode *N, 11695 const llvm::SelectionDAG *DAG, 11696 bool force) { 11697 #ifndef NDEBUG 11698 bool check = force; 11699 #ifdef EXPENSIVE_CHECKS 11700 check = true; 11701 #endif // EXPENSIVE_CHECKS 11702 if (check) { 11703 assert(N && "Checking nonexistent SDNode"); 11704 SmallPtrSet<const SDNode*, 32> visited; 11705 SmallPtrSet<const SDNode*, 32> checked; 11706 checkForCyclesHelper(N, visited, checked, DAG); 11707 } 11708 #endif // !NDEBUG 11709 } 11710 11711 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11712 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11713 } 11714