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/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/MemoryLocation.h" 29 #include "llvm/Analysis/ProfileSummaryInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/FunctionLoweringInfo.h" 33 #include "llvm/CodeGen/ISDOpcodes.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineConstantPool.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineMemOperand.h" 39 #include "llvm/CodeGen/RuntimeLibcalls.h" 40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 41 #include "llvm/CodeGen/SelectionDAGNodes.h" 42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 43 #include "llvm/CodeGen/TargetFrameLowering.h" 44 #include "llvm/CodeGen/TargetLowering.h" 45 #include "llvm/CodeGen/TargetRegisterInfo.h" 46 #include "llvm/CodeGen/TargetSubtargetInfo.h" 47 #include "llvm/CodeGen/ValueTypes.h" 48 #include "llvm/IR/Constant.h" 49 #include "llvm/IR/Constants.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DebugInfoMetadata.h" 52 #include "llvm/IR/DebugLoc.h" 53 #include "llvm/IR/DerivedTypes.h" 54 #include "llvm/IR/Function.h" 55 #include "llvm/IR/GlobalValue.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/IR/Type.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CodeGen.h" 61 #include "llvm/Support/Compiler.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/KnownBits.h" 65 #include "llvm/Support/MachineValueType.h" 66 #include "llvm/Support/ManagedStatic.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/Mutex.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include "llvm/Target/TargetMachine.h" 71 #include "llvm/Target/TargetOptions.h" 72 #include "llvm/Transforms/Utils/SizeOpts.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstdint> 76 #include <cstdlib> 77 #include <limits> 78 #include <set> 79 #include <string> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 85 /// makeVTList - Return an instance of the SDVTList struct initialized with the 86 /// specified members. 87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 88 SDVTList Res = {VTs, NumVTs}; 89 return Res; 90 } 91 92 // Default null implementations of the callbacks. 93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 96 97 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 98 99 #define DEBUG_TYPE "selectiondag" 100 101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 102 cl::Hidden, cl::init(true), 103 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 104 105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 106 cl::desc("Number limit for gluing ld/st of memcpy."), 107 cl::Hidden, cl::init(0)); 108 109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 110 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 111 } 112 113 //===----------------------------------------------------------------------===// 114 // ConstantFPSDNode Class 115 //===----------------------------------------------------------------------===// 116 117 /// isExactlyValue - We don't rely on operator== working on double values, as 118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 119 /// As such, this method can be used to do an exact bit-for-bit comparison of 120 /// two floating point values. 121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 122 return getValueAPF().bitwiseIsEqual(V); 123 } 124 125 bool ConstantFPSDNode::isValueValidForType(EVT VT, 126 const APFloat& Val) { 127 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 128 129 // convert modifies in place, so make a copy. 130 APFloat Val2 = APFloat(Val); 131 bool losesInfo; 132 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 133 APFloat::rmNearestTiesToEven, 134 &losesInfo); 135 return !losesInfo; 136 } 137 138 //===----------------------------------------------------------------------===// 139 // ISD Namespace 140 //===----------------------------------------------------------------------===// 141 142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 143 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 144 unsigned EltSize = 145 N->getValueType(0).getVectorElementType().getSizeInBits(); 146 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 147 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize); 148 return true; 149 } 150 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 151 SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize); 152 return true; 153 } 154 } 155 156 auto *BV = dyn_cast<BuildVectorSDNode>(N); 157 if (!BV) 158 return false; 159 160 APInt SplatUndef; 161 unsigned SplatBitSize; 162 bool HasUndefs; 163 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 164 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 165 EltSize) && 166 EltSize == SplatBitSize; 167 } 168 169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 170 // specializations of the more general isConstantSplatVector()? 171 172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 173 // Look through a bit convert. 174 while (N->getOpcode() == ISD::BITCAST) 175 N = N->getOperand(0).getNode(); 176 177 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 178 APInt SplatVal; 179 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 180 } 181 182 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 183 184 unsigned i = 0, e = N->getNumOperands(); 185 186 // Skip over all of the undef values. 187 while (i != e && N->getOperand(i).isUndef()) 188 ++i; 189 190 // Do not accept an all-undef vector. 191 if (i == e) return false; 192 193 // Do not accept build_vectors that aren't all constants or which have non-~0 194 // elements. We have to be a bit careful here, as the type of the constant 195 // may not be the same as the type of the vector elements due to type 196 // legalization (the elements are promoted to a legal type for the target and 197 // a vector of a type may be legal when the base element type is not). 198 // We only want to check enough bits to cover the vector elements, because 199 // we care if the resultant vector is all ones, not whether the individual 200 // constants are. 201 SDValue NotZero = N->getOperand(i); 202 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 203 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 204 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 205 return false; 206 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 207 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 208 return false; 209 } else 210 return false; 211 212 // Okay, we have at least one ~0 value, check to see if the rest match or are 213 // undefs. Even with the above element type twiddling, this should be OK, as 214 // the same type legalization should have applied to all the elements. 215 for (++i; i != e; ++i) 216 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 217 return false; 218 return true; 219 } 220 221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 222 // Look through a bit convert. 223 while (N->getOpcode() == ISD::BITCAST) 224 N = N->getOperand(0).getNode(); 225 226 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 227 APInt SplatVal; 228 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 229 } 230 231 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 232 233 bool IsAllUndef = true; 234 for (const SDValue &Op : N->op_values()) { 235 if (Op.isUndef()) 236 continue; 237 IsAllUndef = false; 238 // Do not accept build_vectors that aren't all constants or which have non-0 239 // elements. We have to be a bit careful here, as the type of the constant 240 // may not be the same as the type of the vector elements due to type 241 // legalization (the elements are promoted to a legal type for the target 242 // and a vector of a type may be legal when the base element type is not). 243 // We only want to check enough bits to cover the vector elements, because 244 // we care if the resultant vector is all zeros, not whether the individual 245 // constants are. 246 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 247 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 248 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 249 return false; 250 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 251 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 252 return false; 253 } else 254 return false; 255 } 256 257 // Do not accept an all-undef vector. 258 if (IsAllUndef) 259 return false; 260 return true; 261 } 262 263 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 264 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 265 } 266 267 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 268 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 269 } 270 271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 272 if (N->getOpcode() != ISD::BUILD_VECTOR) 273 return false; 274 275 for (const SDValue &Op : N->op_values()) { 276 if (Op.isUndef()) 277 continue; 278 if (!isa<ConstantSDNode>(Op)) 279 return false; 280 } 281 return true; 282 } 283 284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 285 if (N->getOpcode() != ISD::BUILD_VECTOR) 286 return false; 287 288 for (const SDValue &Op : N->op_values()) { 289 if (Op.isUndef()) 290 continue; 291 if (!isa<ConstantFPSDNode>(Op)) 292 return false; 293 } 294 return true; 295 } 296 297 bool ISD::allOperandsUndef(const SDNode *N) { 298 // Return false if the node has no operands. 299 // This is "logically inconsistent" with the definition of "all" but 300 // is probably the desired behavior. 301 if (N->getNumOperands() == 0) 302 return false; 303 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 304 } 305 306 bool ISD::matchUnaryPredicate(SDValue Op, 307 std::function<bool(ConstantSDNode *)> Match, 308 bool AllowUndefs) { 309 // FIXME: Add support for scalar UNDEF cases? 310 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 311 return Match(Cst); 312 313 // FIXME: Add support for vector UNDEF cases? 314 if (ISD::BUILD_VECTOR != Op.getOpcode() && 315 ISD::SPLAT_VECTOR != Op.getOpcode()) 316 return false; 317 318 EVT SVT = Op.getValueType().getScalarType(); 319 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 320 if (AllowUndefs && Op.getOperand(i).isUndef()) { 321 if (!Match(nullptr)) 322 return false; 323 continue; 324 } 325 326 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 327 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 328 return false; 329 } 330 return true; 331 } 332 333 bool ISD::matchBinaryPredicate( 334 SDValue LHS, SDValue RHS, 335 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 336 bool AllowUndefs, bool AllowTypeMismatch) { 337 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 338 return false; 339 340 // TODO: Add support for scalar UNDEF cases? 341 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 342 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 343 return Match(LHSCst, RHSCst); 344 345 // TODO: Add support for vector UNDEF cases? 346 if (LHS.getOpcode() != RHS.getOpcode() || 347 (LHS.getOpcode() != ISD::BUILD_VECTOR && 348 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 349 return false; 350 351 EVT SVT = LHS.getValueType().getScalarType(); 352 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 353 SDValue LHSOp = LHS.getOperand(i); 354 SDValue RHSOp = RHS.getOperand(i); 355 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 356 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 357 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 358 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 359 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 360 return false; 361 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 362 LHSOp.getValueType() != RHSOp.getValueType())) 363 return false; 364 if (!Match(LHSCst, RHSCst)) 365 return false; 366 } 367 return true; 368 } 369 370 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 371 switch (VecReduceOpcode) { 372 default: 373 llvm_unreachable("Expected VECREDUCE opcode"); 374 case ISD::VECREDUCE_FADD: 375 case ISD::VECREDUCE_SEQ_FADD: 376 case ISD::VP_REDUCE_FADD: 377 case ISD::VP_REDUCE_SEQ_FADD: 378 return ISD::FADD; 379 case ISD::VECREDUCE_FMUL: 380 case ISD::VECREDUCE_SEQ_FMUL: 381 case ISD::VP_REDUCE_FMUL: 382 case ISD::VP_REDUCE_SEQ_FMUL: 383 return ISD::FMUL; 384 case ISD::VECREDUCE_ADD: 385 case ISD::VP_REDUCE_ADD: 386 return ISD::ADD; 387 case ISD::VECREDUCE_MUL: 388 case ISD::VP_REDUCE_MUL: 389 return ISD::MUL; 390 case ISD::VECREDUCE_AND: 391 case ISD::VP_REDUCE_AND: 392 return ISD::AND; 393 case ISD::VECREDUCE_OR: 394 case ISD::VP_REDUCE_OR: 395 return ISD::OR; 396 case ISD::VECREDUCE_XOR: 397 case ISD::VP_REDUCE_XOR: 398 return ISD::XOR; 399 case ISD::VECREDUCE_SMAX: 400 case ISD::VP_REDUCE_SMAX: 401 return ISD::SMAX; 402 case ISD::VECREDUCE_SMIN: 403 case ISD::VP_REDUCE_SMIN: 404 return ISD::SMIN; 405 case ISD::VECREDUCE_UMAX: 406 case ISD::VP_REDUCE_UMAX: 407 return ISD::UMAX; 408 case ISD::VECREDUCE_UMIN: 409 case ISD::VP_REDUCE_UMIN: 410 return ISD::UMIN; 411 case ISD::VECREDUCE_FMAX: 412 case ISD::VP_REDUCE_FMAX: 413 return ISD::FMAXNUM; 414 case ISD::VECREDUCE_FMIN: 415 case ISD::VP_REDUCE_FMIN: 416 return ISD::FMINNUM; 417 } 418 } 419 420 bool ISD::isVPOpcode(unsigned Opcode) { 421 switch (Opcode) { 422 default: 423 return false; 424 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 425 case ISD::VPSD: \ 426 return true; 427 #include "llvm/IR/VPIntrinsics.def" 428 } 429 } 430 431 bool ISD::isVPBinaryOp(unsigned Opcode) { 432 switch (Opcode) { 433 default: 434 break; 435 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 436 #define VP_PROPERTY_BINARYOP return true; 437 #define END_REGISTER_VP_SDNODE(VPSD) break; 438 #include "llvm/IR/VPIntrinsics.def" 439 } 440 return false; 441 } 442 443 bool ISD::isVPReduction(unsigned Opcode) { 444 switch (Opcode) { 445 default: 446 break; 447 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 448 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 449 #define END_REGISTER_VP_SDNODE(VPSD) break; 450 #include "llvm/IR/VPIntrinsics.def" 451 } 452 return false; 453 } 454 455 /// The operand position of the vector mask. 456 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 457 switch (Opcode) { 458 default: 459 return None; 460 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 461 case ISD::VPSD: \ 462 return MASKPOS; 463 #include "llvm/IR/VPIntrinsics.def" 464 } 465 } 466 467 /// The operand position of the explicit vector length parameter. 468 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 469 switch (Opcode) { 470 default: 471 return None; 472 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 473 case ISD::VPSD: \ 474 return EVLPOS; 475 #include "llvm/IR/VPIntrinsics.def" 476 } 477 } 478 479 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 480 switch (ExtType) { 481 case ISD::EXTLOAD: 482 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 483 case ISD::SEXTLOAD: 484 return ISD::SIGN_EXTEND; 485 case ISD::ZEXTLOAD: 486 return ISD::ZERO_EXTEND; 487 default: 488 break; 489 } 490 491 llvm_unreachable("Invalid LoadExtType"); 492 } 493 494 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 495 // To perform this operation, we just need to swap the L and G bits of the 496 // operation. 497 unsigned OldL = (Operation >> 2) & 1; 498 unsigned OldG = (Operation >> 1) & 1; 499 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 500 (OldL << 1) | // New G bit 501 (OldG << 2)); // New L bit. 502 } 503 504 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 505 unsigned Operation = Op; 506 if (isIntegerLike) 507 Operation ^= 7; // Flip L, G, E bits, but not U. 508 else 509 Operation ^= 15; // Flip all of the condition bits. 510 511 if (Operation > ISD::SETTRUE2) 512 Operation &= ~8; // Don't let N and U bits get set. 513 514 return ISD::CondCode(Operation); 515 } 516 517 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 518 return getSetCCInverseImpl(Op, Type.isInteger()); 519 } 520 521 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 522 bool isIntegerLike) { 523 return getSetCCInverseImpl(Op, isIntegerLike); 524 } 525 526 /// For an integer comparison, return 1 if the comparison is a signed operation 527 /// and 2 if the result is an unsigned comparison. Return zero if the operation 528 /// does not depend on the sign of the input (setne and seteq). 529 static int isSignedOp(ISD::CondCode Opcode) { 530 switch (Opcode) { 531 default: llvm_unreachable("Illegal integer setcc operation!"); 532 case ISD::SETEQ: 533 case ISD::SETNE: return 0; 534 case ISD::SETLT: 535 case ISD::SETLE: 536 case ISD::SETGT: 537 case ISD::SETGE: return 1; 538 case ISD::SETULT: 539 case ISD::SETULE: 540 case ISD::SETUGT: 541 case ISD::SETUGE: return 2; 542 } 543 } 544 545 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 546 EVT Type) { 547 bool IsInteger = Type.isInteger(); 548 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 549 // Cannot fold a signed integer setcc with an unsigned integer setcc. 550 return ISD::SETCC_INVALID; 551 552 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 553 554 // If the N and U bits get set, then the resultant comparison DOES suddenly 555 // care about orderedness, and it is true when ordered. 556 if (Op > ISD::SETTRUE2) 557 Op &= ~16; // Clear the U bit if the N bit is set. 558 559 // Canonicalize illegal integer setcc's. 560 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 561 Op = ISD::SETNE; 562 563 return ISD::CondCode(Op); 564 } 565 566 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 567 EVT Type) { 568 bool IsInteger = Type.isInteger(); 569 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 570 // Cannot fold a signed setcc with an unsigned setcc. 571 return ISD::SETCC_INVALID; 572 573 // Combine all of the condition bits. 574 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 575 576 // Canonicalize illegal integer setcc's. 577 if (IsInteger) { 578 switch (Result) { 579 default: break; 580 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 581 case ISD::SETOEQ: // SETEQ & SETU[LG]E 582 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 583 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 584 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 585 } 586 } 587 588 return Result; 589 } 590 591 //===----------------------------------------------------------------------===// 592 // SDNode Profile Support 593 //===----------------------------------------------------------------------===// 594 595 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 596 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 597 ID.AddInteger(OpC); 598 } 599 600 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 601 /// solely with their pointer. 602 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 603 ID.AddPointer(VTList.VTs); 604 } 605 606 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 607 static void AddNodeIDOperands(FoldingSetNodeID &ID, 608 ArrayRef<SDValue> Ops) { 609 for (auto& Op : Ops) { 610 ID.AddPointer(Op.getNode()); 611 ID.AddInteger(Op.getResNo()); 612 } 613 } 614 615 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 616 static void AddNodeIDOperands(FoldingSetNodeID &ID, 617 ArrayRef<SDUse> Ops) { 618 for (auto& Op : Ops) { 619 ID.AddPointer(Op.getNode()); 620 ID.AddInteger(Op.getResNo()); 621 } 622 } 623 624 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 625 SDVTList VTList, ArrayRef<SDValue> OpList) { 626 AddNodeIDOpcode(ID, OpC); 627 AddNodeIDValueTypes(ID, VTList); 628 AddNodeIDOperands(ID, OpList); 629 } 630 631 /// If this is an SDNode with special info, add this info to the NodeID data. 632 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 633 switch (N->getOpcode()) { 634 case ISD::TargetExternalSymbol: 635 case ISD::ExternalSymbol: 636 case ISD::MCSymbol: 637 llvm_unreachable("Should only be used on nodes with operands"); 638 default: break; // Normal nodes don't need extra info. 639 case ISD::TargetConstant: 640 case ISD::Constant: { 641 const ConstantSDNode *C = cast<ConstantSDNode>(N); 642 ID.AddPointer(C->getConstantIntValue()); 643 ID.AddBoolean(C->isOpaque()); 644 break; 645 } 646 case ISD::TargetConstantFP: 647 case ISD::ConstantFP: 648 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 649 break; 650 case ISD::TargetGlobalAddress: 651 case ISD::GlobalAddress: 652 case ISD::TargetGlobalTLSAddress: 653 case ISD::GlobalTLSAddress: { 654 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 655 ID.AddPointer(GA->getGlobal()); 656 ID.AddInteger(GA->getOffset()); 657 ID.AddInteger(GA->getTargetFlags()); 658 break; 659 } 660 case ISD::BasicBlock: 661 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 662 break; 663 case ISD::Register: 664 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 665 break; 666 case ISD::RegisterMask: 667 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 668 break; 669 case ISD::SRCVALUE: 670 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 671 break; 672 case ISD::FrameIndex: 673 case ISD::TargetFrameIndex: 674 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 675 break; 676 case ISD::LIFETIME_START: 677 case ISD::LIFETIME_END: 678 if (cast<LifetimeSDNode>(N)->hasOffset()) { 679 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 680 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 681 } 682 break; 683 case ISD::PSEUDO_PROBE: 684 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 685 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 686 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 687 break; 688 case ISD::JumpTable: 689 case ISD::TargetJumpTable: 690 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 691 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 692 break; 693 case ISD::ConstantPool: 694 case ISD::TargetConstantPool: { 695 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 696 ID.AddInteger(CP->getAlign().value()); 697 ID.AddInteger(CP->getOffset()); 698 if (CP->isMachineConstantPoolEntry()) 699 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 700 else 701 ID.AddPointer(CP->getConstVal()); 702 ID.AddInteger(CP->getTargetFlags()); 703 break; 704 } 705 case ISD::TargetIndex: { 706 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 707 ID.AddInteger(TI->getIndex()); 708 ID.AddInteger(TI->getOffset()); 709 ID.AddInteger(TI->getTargetFlags()); 710 break; 711 } 712 case ISD::LOAD: { 713 const LoadSDNode *LD = cast<LoadSDNode>(N); 714 ID.AddInteger(LD->getMemoryVT().getRawBits()); 715 ID.AddInteger(LD->getRawSubclassData()); 716 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 717 break; 718 } 719 case ISD::STORE: { 720 const StoreSDNode *ST = cast<StoreSDNode>(N); 721 ID.AddInteger(ST->getMemoryVT().getRawBits()); 722 ID.AddInteger(ST->getRawSubclassData()); 723 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 724 break; 725 } 726 case ISD::VP_LOAD: { 727 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 728 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 729 ID.AddInteger(ELD->getRawSubclassData()); 730 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 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 break; 739 } 740 case ISD::VP_GATHER: { 741 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 742 ID.AddInteger(EG->getMemoryVT().getRawBits()); 743 ID.AddInteger(EG->getRawSubclassData()); 744 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 745 break; 746 } 747 case ISD::VP_SCATTER: { 748 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 749 ID.AddInteger(ES->getMemoryVT().getRawBits()); 750 ID.AddInteger(ES->getRawSubclassData()); 751 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 752 break; 753 } 754 case ISD::MLOAD: { 755 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 756 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 757 ID.AddInteger(MLD->getRawSubclassData()); 758 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 759 break; 760 } 761 case ISD::MSTORE: { 762 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 763 ID.AddInteger(MST->getMemoryVT().getRawBits()); 764 ID.AddInteger(MST->getRawSubclassData()); 765 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 766 break; 767 } 768 case ISD::MGATHER: { 769 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 770 ID.AddInteger(MG->getMemoryVT().getRawBits()); 771 ID.AddInteger(MG->getRawSubclassData()); 772 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 773 break; 774 } 775 case ISD::MSCATTER: { 776 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 777 ID.AddInteger(MS->getMemoryVT().getRawBits()); 778 ID.AddInteger(MS->getRawSubclassData()); 779 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 780 break; 781 } 782 case ISD::ATOMIC_CMP_SWAP: 783 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 784 case ISD::ATOMIC_SWAP: 785 case ISD::ATOMIC_LOAD_ADD: 786 case ISD::ATOMIC_LOAD_SUB: 787 case ISD::ATOMIC_LOAD_AND: 788 case ISD::ATOMIC_LOAD_CLR: 789 case ISD::ATOMIC_LOAD_OR: 790 case ISD::ATOMIC_LOAD_XOR: 791 case ISD::ATOMIC_LOAD_NAND: 792 case ISD::ATOMIC_LOAD_MIN: 793 case ISD::ATOMIC_LOAD_MAX: 794 case ISD::ATOMIC_LOAD_UMIN: 795 case ISD::ATOMIC_LOAD_UMAX: 796 case ISD::ATOMIC_LOAD: 797 case ISD::ATOMIC_STORE: { 798 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 799 ID.AddInteger(AT->getMemoryVT().getRawBits()); 800 ID.AddInteger(AT->getRawSubclassData()); 801 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 802 break; 803 } 804 case ISD::PREFETCH: { 805 const MemSDNode *PF = cast<MemSDNode>(N); 806 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 807 break; 808 } 809 case ISD::VECTOR_SHUFFLE: { 810 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 811 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 812 i != e; ++i) 813 ID.AddInteger(SVN->getMaskElt(i)); 814 break; 815 } 816 case ISD::TargetBlockAddress: 817 case ISD::BlockAddress: { 818 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 819 ID.AddPointer(BA->getBlockAddress()); 820 ID.AddInteger(BA->getOffset()); 821 ID.AddInteger(BA->getTargetFlags()); 822 break; 823 } 824 } // end switch (N->getOpcode()) 825 826 // Target specific memory nodes could also have address spaces to check. 827 if (N->isTargetMemoryOpcode()) 828 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 829 } 830 831 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 832 /// data. 833 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 834 AddNodeIDOpcode(ID, N->getOpcode()); 835 // Add the return value info. 836 AddNodeIDValueTypes(ID, N->getVTList()); 837 // Add the operand info. 838 AddNodeIDOperands(ID, N->ops()); 839 840 // Handle SDNode leafs with special info. 841 AddNodeIDCustom(ID, N); 842 } 843 844 //===----------------------------------------------------------------------===// 845 // SelectionDAG Class 846 //===----------------------------------------------------------------------===// 847 848 /// doNotCSE - Return true if CSE should not be performed for this node. 849 static bool doNotCSE(SDNode *N) { 850 if (N->getValueType(0) == MVT::Glue) 851 return true; // Never CSE anything that produces a flag. 852 853 switch (N->getOpcode()) { 854 default: break; 855 case ISD::HANDLENODE: 856 case ISD::EH_LABEL: 857 return true; // Never CSE these nodes. 858 } 859 860 // Check that remaining values produced are not flags. 861 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 862 if (N->getValueType(i) == MVT::Glue) 863 return true; // Never CSE anything that produces a flag. 864 865 return false; 866 } 867 868 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 869 /// SelectionDAG. 870 void SelectionDAG::RemoveDeadNodes() { 871 // Create a dummy node (which is not added to allnodes), that adds a reference 872 // to the root node, preventing it from being deleted. 873 HandleSDNode Dummy(getRoot()); 874 875 SmallVector<SDNode*, 128> DeadNodes; 876 877 // Add all obviously-dead nodes to the DeadNodes worklist. 878 for (SDNode &Node : allnodes()) 879 if (Node.use_empty()) 880 DeadNodes.push_back(&Node); 881 882 RemoveDeadNodes(DeadNodes); 883 884 // If the root changed (e.g. it was a dead load, update the root). 885 setRoot(Dummy.getValue()); 886 } 887 888 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 889 /// given list, and any nodes that become unreachable as a result. 890 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 891 892 // Process the worklist, deleting the nodes and adding their uses to the 893 // worklist. 894 while (!DeadNodes.empty()) { 895 SDNode *N = DeadNodes.pop_back_val(); 896 // Skip to next node if we've already managed to delete the node. This could 897 // happen if replacing a node causes a node previously added to the node to 898 // be deleted. 899 if (N->getOpcode() == ISD::DELETED_NODE) 900 continue; 901 902 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 903 DUL->NodeDeleted(N, nullptr); 904 905 // Take the node out of the appropriate CSE map. 906 RemoveNodeFromCSEMaps(N); 907 908 // Next, brutally remove the operand list. This is safe to do, as there are 909 // no cycles in the graph. 910 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 911 SDUse &Use = *I++; 912 SDNode *Operand = Use.getNode(); 913 Use.set(SDValue()); 914 915 // Now that we removed this operand, see if there are no uses of it left. 916 if (Operand->use_empty()) 917 DeadNodes.push_back(Operand); 918 } 919 920 DeallocateNode(N); 921 } 922 } 923 924 void SelectionDAG::RemoveDeadNode(SDNode *N){ 925 SmallVector<SDNode*, 16> DeadNodes(1, N); 926 927 // Create a dummy node that adds a reference to the root node, preventing 928 // it from being deleted. (This matters if the root is an operand of the 929 // dead node.) 930 HandleSDNode Dummy(getRoot()); 931 932 RemoveDeadNodes(DeadNodes); 933 } 934 935 void SelectionDAG::DeleteNode(SDNode *N) { 936 // First take this out of the appropriate CSE map. 937 RemoveNodeFromCSEMaps(N); 938 939 // Finally, remove uses due to operands of this node, remove from the 940 // AllNodes list, and delete the node. 941 DeleteNodeNotInCSEMaps(N); 942 } 943 944 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 945 assert(N->getIterator() != AllNodes.begin() && 946 "Cannot delete the entry node!"); 947 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 948 949 // Drop all of the operands and decrement used node's use counts. 950 N->DropOperands(); 951 952 DeallocateNode(N); 953 } 954 955 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 956 assert(!(V->isVariadic() && isParameter)); 957 if (isParameter) 958 ByvalParmDbgValues.push_back(V); 959 else 960 DbgValues.push_back(V); 961 for (const SDNode *Node : V->getSDNodes()) 962 if (Node) 963 DbgValMap[Node].push_back(V); 964 } 965 966 void SDDbgInfo::erase(const SDNode *Node) { 967 DbgValMapType::iterator I = DbgValMap.find(Node); 968 if (I == DbgValMap.end()) 969 return; 970 for (auto &Val: I->second) 971 Val->setIsInvalidated(); 972 DbgValMap.erase(I); 973 } 974 975 void SelectionDAG::DeallocateNode(SDNode *N) { 976 // If we have operands, deallocate them. 977 removeOperands(N); 978 979 NodeAllocator.Deallocate(AllNodes.remove(N)); 980 981 // Set the opcode to DELETED_NODE to help catch bugs when node 982 // memory is reallocated. 983 // FIXME: There are places in SDag that have grown a dependency on the opcode 984 // value in the released node. 985 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 986 N->NodeType = ISD::DELETED_NODE; 987 988 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 989 // them and forget about that node. 990 DbgInfo->erase(N); 991 } 992 993 #ifndef NDEBUG 994 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 995 static void VerifySDNode(SDNode *N) { 996 switch (N->getOpcode()) { 997 default: 998 break; 999 case ISD::BUILD_PAIR: { 1000 EVT VT = N->getValueType(0); 1001 assert(N->getNumValues() == 1 && "Too many results!"); 1002 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1003 "Wrong return type!"); 1004 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1005 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1006 "Mismatched operand types!"); 1007 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1008 "Wrong operand type!"); 1009 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1010 "Wrong return type size"); 1011 break; 1012 } 1013 case ISD::BUILD_VECTOR: { 1014 assert(N->getNumValues() == 1 && "Too many results!"); 1015 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1016 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1017 "Wrong number of operands!"); 1018 EVT EltVT = N->getValueType(0).getVectorElementType(); 1019 for (const SDUse &Op : N->ops()) { 1020 assert((Op.getValueType() == EltVT || 1021 (EltVT.isInteger() && Op.getValueType().isInteger() && 1022 EltVT.bitsLE(Op.getValueType()))) && 1023 "Wrong operand type!"); 1024 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1025 "Operands must all have the same type"); 1026 } 1027 break; 1028 } 1029 } 1030 } 1031 #endif // NDEBUG 1032 1033 /// Insert a newly allocated node into the DAG. 1034 /// 1035 /// Handles insertion into the all nodes list and CSE map, as well as 1036 /// verification and other common operations when a new node is allocated. 1037 void SelectionDAG::InsertNode(SDNode *N) { 1038 AllNodes.push_back(N); 1039 #ifndef NDEBUG 1040 N->PersistentId = NextPersistentId++; 1041 VerifySDNode(N); 1042 #endif 1043 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1044 DUL->NodeInserted(N); 1045 } 1046 1047 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1048 /// correspond to it. This is useful when we're about to delete or repurpose 1049 /// the node. We don't want future request for structurally identical nodes 1050 /// to return N anymore. 1051 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1052 bool Erased = false; 1053 switch (N->getOpcode()) { 1054 case ISD::HANDLENODE: return false; // noop. 1055 case ISD::CONDCODE: 1056 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1057 "Cond code doesn't exist!"); 1058 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1059 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1060 break; 1061 case ISD::ExternalSymbol: 1062 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1063 break; 1064 case ISD::TargetExternalSymbol: { 1065 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1066 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1067 ESN->getSymbol(), ESN->getTargetFlags())); 1068 break; 1069 } 1070 case ISD::MCSymbol: { 1071 auto *MCSN = cast<MCSymbolSDNode>(N); 1072 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1073 break; 1074 } 1075 case ISD::VALUETYPE: { 1076 EVT VT = cast<VTSDNode>(N)->getVT(); 1077 if (VT.isExtended()) { 1078 Erased = ExtendedValueTypeNodes.erase(VT); 1079 } else { 1080 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1081 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1082 } 1083 break; 1084 } 1085 default: 1086 // Remove it from the CSE Map. 1087 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1088 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1089 Erased = CSEMap.RemoveNode(N); 1090 break; 1091 } 1092 #ifndef NDEBUG 1093 // Verify that the node was actually in one of the CSE maps, unless it has a 1094 // flag result (which cannot be CSE'd) or is one of the special cases that are 1095 // not subject to CSE. 1096 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1097 !N->isMachineOpcode() && !doNotCSE(N)) { 1098 N->dump(this); 1099 dbgs() << "\n"; 1100 llvm_unreachable("Node is not in map!"); 1101 } 1102 #endif 1103 return Erased; 1104 } 1105 1106 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1107 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1108 /// node already exists, in which case transfer all its users to the existing 1109 /// node. This transfer can potentially trigger recursive merging. 1110 void 1111 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1112 // For node types that aren't CSE'd, just act as if no identical node 1113 // already exists. 1114 if (!doNotCSE(N)) { 1115 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1116 if (Existing != N) { 1117 // If there was already an existing matching node, use ReplaceAllUsesWith 1118 // to replace the dead one with the existing one. This can cause 1119 // recursive merging of other unrelated nodes down the line. 1120 ReplaceAllUsesWith(N, Existing); 1121 1122 // N is now dead. Inform the listeners and delete it. 1123 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1124 DUL->NodeDeleted(N, Existing); 1125 DeleteNodeNotInCSEMaps(N); 1126 return; 1127 } 1128 } 1129 1130 // If the node doesn't already exist, we updated it. Inform listeners. 1131 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1132 DUL->NodeUpdated(N); 1133 } 1134 1135 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1136 /// were replaced with those specified. If this node is never memoized, 1137 /// return null, otherwise return a pointer to the slot it would take. If a 1138 /// node already exists with these operands, the slot will be non-null. 1139 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1140 void *&InsertPos) { 1141 if (doNotCSE(N)) 1142 return nullptr; 1143 1144 SDValue Ops[] = { Op }; 1145 FoldingSetNodeID ID; 1146 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1147 AddNodeIDCustom(ID, N); 1148 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1149 if (Node) 1150 Node->intersectFlagsWith(N->getFlags()); 1151 return Node; 1152 } 1153 1154 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1155 /// were replaced with those specified. If this node is never memoized, 1156 /// return null, otherwise return a pointer to the slot it would take. If a 1157 /// node already exists with these operands, the slot will be non-null. 1158 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1159 SDValue Op1, SDValue Op2, 1160 void *&InsertPos) { 1161 if (doNotCSE(N)) 1162 return nullptr; 1163 1164 SDValue Ops[] = { Op1, Op2 }; 1165 FoldingSetNodeID ID; 1166 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1167 AddNodeIDCustom(ID, N); 1168 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1169 if (Node) 1170 Node->intersectFlagsWith(N->getFlags()); 1171 return Node; 1172 } 1173 1174 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1175 /// were replaced with those specified. If this node is never memoized, 1176 /// return null, otherwise return a pointer to the slot it would take. If a 1177 /// node already exists with these operands, the slot will be non-null. 1178 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1179 void *&InsertPos) { 1180 if (doNotCSE(N)) 1181 return nullptr; 1182 1183 FoldingSetNodeID ID; 1184 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1185 AddNodeIDCustom(ID, N); 1186 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1187 if (Node) 1188 Node->intersectFlagsWith(N->getFlags()); 1189 return Node; 1190 } 1191 1192 Align SelectionDAG::getEVTAlign(EVT VT) const { 1193 Type *Ty = VT == MVT::iPTR ? 1194 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1195 VT.getTypeForEVT(*getContext()); 1196 1197 return getDataLayout().getABITypeAlign(Ty); 1198 } 1199 1200 // EntryNode could meaningfully have debug info if we can find it... 1201 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1202 : TM(tm), OptLevel(OL), 1203 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1204 Root(getEntryNode()) { 1205 InsertNode(&EntryNode); 1206 DbgInfo = new SDDbgInfo(); 1207 } 1208 1209 void SelectionDAG::init(MachineFunction &NewMF, 1210 OptimizationRemarkEmitter &NewORE, 1211 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1212 LegacyDivergenceAnalysis * Divergence, 1213 ProfileSummaryInfo *PSIin, 1214 BlockFrequencyInfo *BFIin) { 1215 MF = &NewMF; 1216 SDAGISelPass = PassPtr; 1217 ORE = &NewORE; 1218 TLI = getSubtarget().getTargetLowering(); 1219 TSI = getSubtarget().getSelectionDAGInfo(); 1220 LibInfo = LibraryInfo; 1221 Context = &MF->getFunction().getContext(); 1222 DA = Divergence; 1223 PSI = PSIin; 1224 BFI = BFIin; 1225 } 1226 1227 SelectionDAG::~SelectionDAG() { 1228 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1229 allnodes_clear(); 1230 OperandRecycler.clear(OperandAllocator); 1231 delete DbgInfo; 1232 } 1233 1234 bool SelectionDAG::shouldOptForSize() const { 1235 return MF->getFunction().hasOptSize() || 1236 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1237 } 1238 1239 void SelectionDAG::allnodes_clear() { 1240 assert(&*AllNodes.begin() == &EntryNode); 1241 AllNodes.remove(AllNodes.begin()); 1242 while (!AllNodes.empty()) 1243 DeallocateNode(&AllNodes.front()); 1244 #ifndef NDEBUG 1245 NextPersistentId = 0; 1246 #endif 1247 } 1248 1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1250 void *&InsertPos) { 1251 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1252 if (N) { 1253 switch (N->getOpcode()) { 1254 default: break; 1255 case ISD::Constant: 1256 case ISD::ConstantFP: 1257 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1258 "debug location. Use another overload."); 1259 } 1260 } 1261 return N; 1262 } 1263 1264 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1265 const SDLoc &DL, void *&InsertPos) { 1266 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1267 if (N) { 1268 switch (N->getOpcode()) { 1269 case ISD::Constant: 1270 case ISD::ConstantFP: 1271 // Erase debug location from the node if the node is used at several 1272 // different places. Do not propagate one location to all uses as it 1273 // will cause a worse single stepping debugging experience. 1274 if (N->getDebugLoc() != DL.getDebugLoc()) 1275 N->setDebugLoc(DebugLoc()); 1276 break; 1277 default: 1278 // When the node's point of use is located earlier in the instruction 1279 // sequence than its prior point of use, update its debug info to the 1280 // earlier location. 1281 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1282 N->setDebugLoc(DL.getDebugLoc()); 1283 break; 1284 } 1285 } 1286 return N; 1287 } 1288 1289 void SelectionDAG::clear() { 1290 allnodes_clear(); 1291 OperandRecycler.clear(OperandAllocator); 1292 OperandAllocator.Reset(); 1293 CSEMap.clear(); 1294 1295 ExtendedValueTypeNodes.clear(); 1296 ExternalSymbols.clear(); 1297 TargetExternalSymbols.clear(); 1298 MCSymbols.clear(); 1299 SDCallSiteDbgInfo.clear(); 1300 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1301 static_cast<CondCodeSDNode*>(nullptr)); 1302 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1303 static_cast<SDNode*>(nullptr)); 1304 1305 EntryNode.UseList = nullptr; 1306 InsertNode(&EntryNode); 1307 Root = getEntryNode(); 1308 DbgInfo->clear(); 1309 } 1310 1311 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1312 return VT.bitsGT(Op.getValueType()) 1313 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1314 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1315 } 1316 1317 std::pair<SDValue, SDValue> 1318 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1319 const SDLoc &DL, EVT VT) { 1320 assert(!VT.bitsEq(Op.getValueType()) && 1321 "Strict no-op FP extend/round not allowed."); 1322 SDValue Res = 1323 VT.bitsGT(Op.getValueType()) 1324 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1325 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1326 {Chain, Op, getIntPtrConstant(0, DL)}); 1327 1328 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1329 } 1330 1331 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1332 return VT.bitsGT(Op.getValueType()) ? 1333 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1334 getNode(ISD::TRUNCATE, DL, VT, Op); 1335 } 1336 1337 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1338 return VT.bitsGT(Op.getValueType()) ? 1339 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1340 getNode(ISD::TRUNCATE, DL, VT, Op); 1341 } 1342 1343 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1344 return VT.bitsGT(Op.getValueType()) ? 1345 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1346 getNode(ISD::TRUNCATE, DL, VT, Op); 1347 } 1348 1349 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1350 EVT OpVT) { 1351 if (VT.bitsLE(Op.getValueType())) 1352 return getNode(ISD::TRUNCATE, SL, VT, Op); 1353 1354 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1355 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1356 } 1357 1358 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1359 EVT OpVT = Op.getValueType(); 1360 assert(VT.isInteger() && OpVT.isInteger() && 1361 "Cannot getZeroExtendInReg FP types"); 1362 assert(VT.isVector() == OpVT.isVector() && 1363 "getZeroExtendInReg type should be vector iff the operand " 1364 "type is vector!"); 1365 assert((!VT.isVector() || 1366 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1367 "Vector element counts must match in getZeroExtendInReg"); 1368 assert(VT.bitsLE(OpVT) && "Not extending!"); 1369 if (OpVT == VT) 1370 return Op; 1371 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1372 VT.getScalarSizeInBits()); 1373 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1374 } 1375 1376 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1377 // Only unsigned pointer semantics are supported right now. In the future this 1378 // might delegate to TLI to check pointer signedness. 1379 return getZExtOrTrunc(Op, DL, VT); 1380 } 1381 1382 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1383 // Only unsigned pointer semantics are supported right now. In the future this 1384 // might delegate to TLI to check pointer signedness. 1385 return getZeroExtendInReg(Op, DL, VT); 1386 } 1387 1388 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1389 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1390 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1391 } 1392 1393 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1394 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1395 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1396 } 1397 1398 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1399 EVT OpVT) { 1400 if (!V) 1401 return getConstant(0, DL, VT); 1402 1403 switch (TLI->getBooleanContents(OpVT)) { 1404 case TargetLowering::ZeroOrOneBooleanContent: 1405 case TargetLowering::UndefinedBooleanContent: 1406 return getConstant(1, DL, VT); 1407 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1408 return getAllOnesConstant(DL, VT); 1409 } 1410 llvm_unreachable("Unexpected boolean content enum!"); 1411 } 1412 1413 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1414 bool isT, bool isO) { 1415 EVT EltVT = VT.getScalarType(); 1416 assert((EltVT.getSizeInBits() >= 64 || 1417 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1418 "getConstant with a uint64_t value that doesn't fit in the type!"); 1419 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1420 } 1421 1422 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1423 bool isT, bool isO) { 1424 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1425 } 1426 1427 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1428 EVT VT, bool isT, bool isO) { 1429 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1430 1431 EVT EltVT = VT.getScalarType(); 1432 const ConstantInt *Elt = &Val; 1433 1434 // In some cases the vector type is legal but the element type is illegal and 1435 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1436 // inserted value (the type does not need to match the vector element type). 1437 // Any extra bits introduced will be truncated away. 1438 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1439 TargetLowering::TypePromoteInteger) { 1440 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1441 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1442 Elt = ConstantInt::get(*getContext(), NewVal); 1443 } 1444 // In other cases the element type is illegal and needs to be expanded, for 1445 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1446 // the value into n parts and use a vector type with n-times the elements. 1447 // Then bitcast to the type requested. 1448 // Legalizing constants too early makes the DAGCombiner's job harder so we 1449 // only legalize if the DAG tells us we must produce legal types. 1450 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1451 TLI->getTypeAction(*getContext(), EltVT) == 1452 TargetLowering::TypeExpandInteger) { 1453 const APInt &NewVal = Elt->getValue(); 1454 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1455 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1456 1457 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1458 if (VT.isScalableVector()) { 1459 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1460 "Can only handle an even split!"); 1461 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1462 1463 SmallVector<SDValue, 2> ScalarParts; 1464 for (unsigned i = 0; i != Parts; ++i) 1465 ScalarParts.push_back(getConstant( 1466 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1467 ViaEltVT, isT, isO)); 1468 1469 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1470 } 1471 1472 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1473 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1474 1475 // Check the temporary vector is the correct size. If this fails then 1476 // getTypeToTransformTo() probably returned a type whose size (in bits) 1477 // isn't a power-of-2 factor of the requested type size. 1478 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1479 1480 SmallVector<SDValue, 2> EltParts; 1481 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1482 EltParts.push_back(getConstant( 1483 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1484 ViaEltVT, isT, isO)); 1485 1486 // EltParts is currently in little endian order. If we actually want 1487 // big-endian order then reverse it now. 1488 if (getDataLayout().isBigEndian()) 1489 std::reverse(EltParts.begin(), EltParts.end()); 1490 1491 // The elements must be reversed when the element order is different 1492 // to the endianness of the elements (because the BITCAST is itself a 1493 // vector shuffle in this situation). However, we do not need any code to 1494 // perform this reversal because getConstant() is producing a vector 1495 // splat. 1496 // This situation occurs in MIPS MSA. 1497 1498 SmallVector<SDValue, 8> Ops; 1499 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1500 llvm::append_range(Ops, EltParts); 1501 1502 SDValue V = 1503 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1504 return V; 1505 } 1506 1507 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1508 "APInt size does not match type size!"); 1509 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1510 FoldingSetNodeID ID; 1511 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1512 ID.AddPointer(Elt); 1513 ID.AddBoolean(isO); 1514 void *IP = nullptr; 1515 SDNode *N = nullptr; 1516 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1517 if (!VT.isVector()) 1518 return SDValue(N, 0); 1519 1520 if (!N) { 1521 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1522 CSEMap.InsertNode(N, IP); 1523 InsertNode(N); 1524 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1525 } 1526 1527 SDValue Result(N, 0); 1528 if (VT.isScalableVector()) 1529 Result = getSplatVector(VT, DL, Result); 1530 else if (VT.isVector()) 1531 Result = getSplatBuildVector(VT, DL, Result); 1532 1533 return Result; 1534 } 1535 1536 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1537 bool isTarget) { 1538 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1539 } 1540 1541 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1542 const SDLoc &DL, bool LegalTypes) { 1543 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1544 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1545 return getConstant(Val, DL, ShiftVT); 1546 } 1547 1548 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1549 bool isTarget) { 1550 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1551 } 1552 1553 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1554 bool isTarget) { 1555 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1556 } 1557 1558 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1559 EVT VT, bool isTarget) { 1560 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1561 1562 EVT EltVT = VT.getScalarType(); 1563 1564 // Do the map lookup using the actual bit pattern for the floating point 1565 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1566 // we don't have issues with SNANs. 1567 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1568 FoldingSetNodeID ID; 1569 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1570 ID.AddPointer(&V); 1571 void *IP = nullptr; 1572 SDNode *N = nullptr; 1573 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1574 if (!VT.isVector()) 1575 return SDValue(N, 0); 1576 1577 if (!N) { 1578 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1579 CSEMap.InsertNode(N, IP); 1580 InsertNode(N); 1581 } 1582 1583 SDValue Result(N, 0); 1584 if (VT.isScalableVector()) 1585 Result = getSplatVector(VT, DL, Result); 1586 else if (VT.isVector()) 1587 Result = getSplatBuildVector(VT, DL, Result); 1588 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1589 return Result; 1590 } 1591 1592 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1593 bool isTarget) { 1594 EVT EltVT = VT.getScalarType(); 1595 if (EltVT == MVT::f32) 1596 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1597 if (EltVT == MVT::f64) 1598 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1599 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1600 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1601 bool Ignored; 1602 APFloat APF = APFloat(Val); 1603 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1604 &Ignored); 1605 return getConstantFP(APF, DL, VT, isTarget); 1606 } 1607 llvm_unreachable("Unsupported type in getConstantFP"); 1608 } 1609 1610 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1611 EVT VT, int64_t Offset, bool isTargetGA, 1612 unsigned TargetFlags) { 1613 assert((TargetFlags == 0 || isTargetGA) && 1614 "Cannot set target flags on target-independent globals"); 1615 1616 // Truncate (with sign-extension) the offset value to the pointer size. 1617 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1618 if (BitWidth < 64) 1619 Offset = SignExtend64(Offset, BitWidth); 1620 1621 unsigned Opc; 1622 if (GV->isThreadLocal()) 1623 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1624 else 1625 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1626 1627 FoldingSetNodeID ID; 1628 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1629 ID.AddPointer(GV); 1630 ID.AddInteger(Offset); 1631 ID.AddInteger(TargetFlags); 1632 void *IP = nullptr; 1633 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1634 return SDValue(E, 0); 1635 1636 auto *N = newSDNode<GlobalAddressSDNode>( 1637 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1638 CSEMap.InsertNode(N, IP); 1639 InsertNode(N); 1640 return SDValue(N, 0); 1641 } 1642 1643 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1644 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1645 FoldingSetNodeID ID; 1646 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1647 ID.AddInteger(FI); 1648 void *IP = nullptr; 1649 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1650 return SDValue(E, 0); 1651 1652 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1653 CSEMap.InsertNode(N, IP); 1654 InsertNode(N); 1655 return SDValue(N, 0); 1656 } 1657 1658 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1659 unsigned TargetFlags) { 1660 assert((TargetFlags == 0 || isTarget) && 1661 "Cannot set target flags on target-independent jump tables"); 1662 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1663 FoldingSetNodeID ID; 1664 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1665 ID.AddInteger(JTI); 1666 ID.AddInteger(TargetFlags); 1667 void *IP = nullptr; 1668 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1669 return SDValue(E, 0); 1670 1671 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1672 CSEMap.InsertNode(N, IP); 1673 InsertNode(N); 1674 return SDValue(N, 0); 1675 } 1676 1677 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1678 MaybeAlign Alignment, int Offset, 1679 bool isTarget, unsigned TargetFlags) { 1680 assert((TargetFlags == 0 || isTarget) && 1681 "Cannot set target flags on target-independent globals"); 1682 if (!Alignment) 1683 Alignment = shouldOptForSize() 1684 ? getDataLayout().getABITypeAlign(C->getType()) 1685 : getDataLayout().getPrefTypeAlign(C->getType()); 1686 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1687 FoldingSetNodeID ID; 1688 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1689 ID.AddInteger(Alignment->value()); 1690 ID.AddInteger(Offset); 1691 ID.AddPointer(C); 1692 ID.AddInteger(TargetFlags); 1693 void *IP = nullptr; 1694 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1695 return SDValue(E, 0); 1696 1697 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1698 TargetFlags); 1699 CSEMap.InsertNode(N, IP); 1700 InsertNode(N); 1701 SDValue V = SDValue(N, 0); 1702 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1703 return V; 1704 } 1705 1706 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1707 MaybeAlign Alignment, int Offset, 1708 bool isTarget, unsigned TargetFlags) { 1709 assert((TargetFlags == 0 || isTarget) && 1710 "Cannot set target flags on target-independent globals"); 1711 if (!Alignment) 1712 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1713 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1714 FoldingSetNodeID ID; 1715 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1716 ID.AddInteger(Alignment->value()); 1717 ID.AddInteger(Offset); 1718 C->addSelectionDAGCSEId(ID); 1719 ID.AddInteger(TargetFlags); 1720 void *IP = nullptr; 1721 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1722 return SDValue(E, 0); 1723 1724 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1725 TargetFlags); 1726 CSEMap.InsertNode(N, IP); 1727 InsertNode(N); 1728 return SDValue(N, 0); 1729 } 1730 1731 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1732 unsigned TargetFlags) { 1733 FoldingSetNodeID ID; 1734 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1735 ID.AddInteger(Index); 1736 ID.AddInteger(Offset); 1737 ID.AddInteger(TargetFlags); 1738 void *IP = nullptr; 1739 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1740 return SDValue(E, 0); 1741 1742 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1743 CSEMap.InsertNode(N, IP); 1744 InsertNode(N); 1745 return SDValue(N, 0); 1746 } 1747 1748 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1749 FoldingSetNodeID ID; 1750 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1751 ID.AddPointer(MBB); 1752 void *IP = nullptr; 1753 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1754 return SDValue(E, 0); 1755 1756 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1757 CSEMap.InsertNode(N, IP); 1758 InsertNode(N); 1759 return SDValue(N, 0); 1760 } 1761 1762 SDValue SelectionDAG::getValueType(EVT VT) { 1763 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1764 ValueTypeNodes.size()) 1765 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1766 1767 SDNode *&N = VT.isExtended() ? 1768 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1769 1770 if (N) return SDValue(N, 0); 1771 N = newSDNode<VTSDNode>(VT); 1772 InsertNode(N); 1773 return SDValue(N, 0); 1774 } 1775 1776 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1777 SDNode *&N = ExternalSymbols[Sym]; 1778 if (N) return SDValue(N, 0); 1779 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1780 InsertNode(N); 1781 return SDValue(N, 0); 1782 } 1783 1784 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1785 SDNode *&N = MCSymbols[Sym]; 1786 if (N) 1787 return SDValue(N, 0); 1788 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1789 InsertNode(N); 1790 return SDValue(N, 0); 1791 } 1792 1793 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1794 unsigned TargetFlags) { 1795 SDNode *&N = 1796 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1797 if (N) return SDValue(N, 0); 1798 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1799 InsertNode(N); 1800 return SDValue(N, 0); 1801 } 1802 1803 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1804 if ((unsigned)Cond >= CondCodeNodes.size()) 1805 CondCodeNodes.resize(Cond+1); 1806 1807 if (!CondCodeNodes[Cond]) { 1808 auto *N = newSDNode<CondCodeSDNode>(Cond); 1809 CondCodeNodes[Cond] = N; 1810 InsertNode(N); 1811 } 1812 1813 return SDValue(CondCodeNodes[Cond], 0); 1814 } 1815 1816 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1817 APInt One(ResVT.getScalarSizeInBits(), 1); 1818 return getStepVector(DL, ResVT, One); 1819 } 1820 1821 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1822 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1823 if (ResVT.isScalableVector()) 1824 return getNode( 1825 ISD::STEP_VECTOR, DL, ResVT, 1826 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1827 1828 SmallVector<SDValue, 16> OpsStepConstants; 1829 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1830 OpsStepConstants.push_back( 1831 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1832 return getBuildVector(ResVT, DL, OpsStepConstants); 1833 } 1834 1835 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1836 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1837 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1838 std::swap(N1, N2); 1839 ShuffleVectorSDNode::commuteMask(M); 1840 } 1841 1842 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1843 SDValue N2, ArrayRef<int> Mask) { 1844 assert(VT.getVectorNumElements() == Mask.size() && 1845 "Must have the same number of vector elements as mask elements!"); 1846 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1847 "Invalid VECTOR_SHUFFLE"); 1848 1849 // Canonicalize shuffle undef, undef -> undef 1850 if (N1.isUndef() && N2.isUndef()) 1851 return getUNDEF(VT); 1852 1853 // Validate that all indices in Mask are within the range of the elements 1854 // input to the shuffle. 1855 int NElts = Mask.size(); 1856 assert(llvm::all_of(Mask, 1857 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1858 "Index out of range"); 1859 1860 // Copy the mask so we can do any needed cleanup. 1861 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1862 1863 // Canonicalize shuffle v, v -> v, undef 1864 if (N1 == N2) { 1865 N2 = getUNDEF(VT); 1866 for (int i = 0; i != NElts; ++i) 1867 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1868 } 1869 1870 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1871 if (N1.isUndef()) 1872 commuteShuffle(N1, N2, MaskVec); 1873 1874 if (TLI->hasVectorBlend()) { 1875 // If shuffling a splat, try to blend the splat instead. We do this here so 1876 // that even when this arises during lowering we don't have to re-handle it. 1877 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1878 BitVector UndefElements; 1879 SDValue Splat = BV->getSplatValue(&UndefElements); 1880 if (!Splat) 1881 return; 1882 1883 for (int i = 0; i < NElts; ++i) { 1884 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1885 continue; 1886 1887 // If this input comes from undef, mark it as such. 1888 if (UndefElements[MaskVec[i] - Offset]) { 1889 MaskVec[i] = -1; 1890 continue; 1891 } 1892 1893 // If we can blend a non-undef lane, use that instead. 1894 if (!UndefElements[i]) 1895 MaskVec[i] = i + Offset; 1896 } 1897 }; 1898 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1899 BlendSplat(N1BV, 0); 1900 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1901 BlendSplat(N2BV, NElts); 1902 } 1903 1904 // Canonicalize all index into lhs, -> shuffle lhs, undef 1905 // Canonicalize all index into rhs, -> shuffle rhs, undef 1906 bool AllLHS = true, AllRHS = true; 1907 bool N2Undef = N2.isUndef(); 1908 for (int i = 0; i != NElts; ++i) { 1909 if (MaskVec[i] >= NElts) { 1910 if (N2Undef) 1911 MaskVec[i] = -1; 1912 else 1913 AllLHS = false; 1914 } else if (MaskVec[i] >= 0) { 1915 AllRHS = false; 1916 } 1917 } 1918 if (AllLHS && AllRHS) 1919 return getUNDEF(VT); 1920 if (AllLHS && !N2Undef) 1921 N2 = getUNDEF(VT); 1922 if (AllRHS) { 1923 N1 = getUNDEF(VT); 1924 commuteShuffle(N1, N2, MaskVec); 1925 } 1926 // Reset our undef status after accounting for the mask. 1927 N2Undef = N2.isUndef(); 1928 // Re-check whether both sides ended up undef. 1929 if (N1.isUndef() && N2Undef) 1930 return getUNDEF(VT); 1931 1932 // If Identity shuffle return that node. 1933 bool Identity = true, AllSame = true; 1934 for (int i = 0; i != NElts; ++i) { 1935 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1936 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1937 } 1938 if (Identity && NElts) 1939 return N1; 1940 1941 // Shuffling a constant splat doesn't change the result. 1942 if (N2Undef) { 1943 SDValue V = N1; 1944 1945 // Look through any bitcasts. We check that these don't change the number 1946 // (and size) of elements and just changes their types. 1947 while (V.getOpcode() == ISD::BITCAST) 1948 V = V->getOperand(0); 1949 1950 // A splat should always show up as a build vector node. 1951 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1952 BitVector UndefElements; 1953 SDValue Splat = BV->getSplatValue(&UndefElements); 1954 // If this is a splat of an undef, shuffling it is also undef. 1955 if (Splat && Splat.isUndef()) 1956 return getUNDEF(VT); 1957 1958 bool SameNumElts = 1959 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1960 1961 // We only have a splat which can skip shuffles if there is a splatted 1962 // value and no undef lanes rearranged by the shuffle. 1963 if (Splat && UndefElements.none()) { 1964 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1965 // number of elements match or the value splatted is a zero constant. 1966 if (SameNumElts) 1967 return N1; 1968 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1969 if (C->isZero()) 1970 return N1; 1971 } 1972 1973 // If the shuffle itself creates a splat, build the vector directly. 1974 if (AllSame && SameNumElts) { 1975 EVT BuildVT = BV->getValueType(0); 1976 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1977 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1978 1979 // We may have jumped through bitcasts, so the type of the 1980 // BUILD_VECTOR may not match the type of the shuffle. 1981 if (BuildVT != VT) 1982 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1983 return NewBV; 1984 } 1985 } 1986 } 1987 1988 FoldingSetNodeID ID; 1989 SDValue Ops[2] = { N1, N2 }; 1990 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1991 for (int i = 0; i != NElts; ++i) 1992 ID.AddInteger(MaskVec[i]); 1993 1994 void* IP = nullptr; 1995 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1996 return SDValue(E, 0); 1997 1998 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1999 // SDNode doesn't have access to it. This memory will be "leaked" when 2000 // the node is deallocated, but recovered when the NodeAllocator is released. 2001 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2002 llvm::copy(MaskVec, MaskAlloc); 2003 2004 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2005 dl.getDebugLoc(), MaskAlloc); 2006 createOperands(N, Ops); 2007 2008 CSEMap.InsertNode(N, IP); 2009 InsertNode(N); 2010 SDValue V = SDValue(N, 0); 2011 NewSDValueDbgMsg(V, "Creating new node: ", this); 2012 return V; 2013 } 2014 2015 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2016 EVT VT = SV.getValueType(0); 2017 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2018 ShuffleVectorSDNode::commuteMask(MaskVec); 2019 2020 SDValue Op0 = SV.getOperand(0); 2021 SDValue Op1 = SV.getOperand(1); 2022 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2023 } 2024 2025 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2026 FoldingSetNodeID ID; 2027 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2028 ID.AddInteger(RegNo); 2029 void *IP = nullptr; 2030 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2031 return SDValue(E, 0); 2032 2033 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2034 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2035 CSEMap.InsertNode(N, IP); 2036 InsertNode(N); 2037 return SDValue(N, 0); 2038 } 2039 2040 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2041 FoldingSetNodeID ID; 2042 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2043 ID.AddPointer(RegMask); 2044 void *IP = nullptr; 2045 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2046 return SDValue(E, 0); 2047 2048 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2049 CSEMap.InsertNode(N, IP); 2050 InsertNode(N); 2051 return SDValue(N, 0); 2052 } 2053 2054 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2055 MCSymbol *Label) { 2056 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2057 } 2058 2059 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2060 SDValue Root, MCSymbol *Label) { 2061 FoldingSetNodeID ID; 2062 SDValue Ops[] = { Root }; 2063 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2064 ID.AddPointer(Label); 2065 void *IP = nullptr; 2066 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2067 return SDValue(E, 0); 2068 2069 auto *N = 2070 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2071 createOperands(N, Ops); 2072 2073 CSEMap.InsertNode(N, IP); 2074 InsertNode(N); 2075 return SDValue(N, 0); 2076 } 2077 2078 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2079 int64_t Offset, bool isTarget, 2080 unsigned TargetFlags) { 2081 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2082 2083 FoldingSetNodeID ID; 2084 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2085 ID.AddPointer(BA); 2086 ID.AddInteger(Offset); 2087 ID.AddInteger(TargetFlags); 2088 void *IP = nullptr; 2089 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2090 return SDValue(E, 0); 2091 2092 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2093 CSEMap.InsertNode(N, IP); 2094 InsertNode(N); 2095 return SDValue(N, 0); 2096 } 2097 2098 SDValue SelectionDAG::getSrcValue(const Value *V) { 2099 FoldingSetNodeID ID; 2100 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2101 ID.AddPointer(V); 2102 2103 void *IP = nullptr; 2104 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2105 return SDValue(E, 0); 2106 2107 auto *N = newSDNode<SrcValueSDNode>(V); 2108 CSEMap.InsertNode(N, IP); 2109 InsertNode(N); 2110 return SDValue(N, 0); 2111 } 2112 2113 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2114 FoldingSetNodeID ID; 2115 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2116 ID.AddPointer(MD); 2117 2118 void *IP = nullptr; 2119 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2120 return SDValue(E, 0); 2121 2122 auto *N = newSDNode<MDNodeSDNode>(MD); 2123 CSEMap.InsertNode(N, IP); 2124 InsertNode(N); 2125 return SDValue(N, 0); 2126 } 2127 2128 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2129 if (VT == V.getValueType()) 2130 return V; 2131 2132 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2133 } 2134 2135 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2136 unsigned SrcAS, unsigned DestAS) { 2137 SDValue Ops[] = {Ptr}; 2138 FoldingSetNodeID ID; 2139 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2140 ID.AddInteger(SrcAS); 2141 ID.AddInteger(DestAS); 2142 2143 void *IP = nullptr; 2144 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2145 return SDValue(E, 0); 2146 2147 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2148 VT, SrcAS, DestAS); 2149 createOperands(N, Ops); 2150 2151 CSEMap.InsertNode(N, IP); 2152 InsertNode(N); 2153 return SDValue(N, 0); 2154 } 2155 2156 SDValue SelectionDAG::getFreeze(SDValue V) { 2157 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2158 } 2159 2160 /// getShiftAmountOperand - Return the specified value casted to 2161 /// the target's desired shift amount type. 2162 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2163 EVT OpTy = Op.getValueType(); 2164 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2165 if (OpTy == ShTy || OpTy.isVector()) return Op; 2166 2167 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2168 } 2169 2170 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2171 SDLoc dl(Node); 2172 const TargetLowering &TLI = getTargetLoweringInfo(); 2173 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2174 EVT VT = Node->getValueType(0); 2175 SDValue Tmp1 = Node->getOperand(0); 2176 SDValue Tmp2 = Node->getOperand(1); 2177 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2178 2179 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2180 Tmp2, MachinePointerInfo(V)); 2181 SDValue VAList = VAListLoad; 2182 2183 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2184 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2185 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2186 2187 VAList = 2188 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2189 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2190 } 2191 2192 // Increment the pointer, VAList, to the next vaarg 2193 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2194 getConstant(getDataLayout().getTypeAllocSize( 2195 VT.getTypeForEVT(*getContext())), 2196 dl, VAList.getValueType())); 2197 // Store the incremented VAList to the legalized pointer 2198 Tmp1 = 2199 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2200 // Load the actual argument out of the pointer VAList 2201 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2202 } 2203 2204 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2205 SDLoc dl(Node); 2206 const TargetLowering &TLI = getTargetLoweringInfo(); 2207 // This defaults to loading a pointer from the input and storing it to the 2208 // output, returning the chain. 2209 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2210 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2211 SDValue Tmp1 = 2212 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2213 Node->getOperand(2), MachinePointerInfo(VS)); 2214 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2215 MachinePointerInfo(VD)); 2216 } 2217 2218 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2219 const DataLayout &DL = getDataLayout(); 2220 Type *Ty = VT.getTypeForEVT(*getContext()); 2221 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2222 2223 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2224 return RedAlign; 2225 2226 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2227 const Align StackAlign = TFI->getStackAlign(); 2228 2229 // See if we can choose a smaller ABI alignment in cases where it's an 2230 // illegal vector type that will get broken down. 2231 if (RedAlign > StackAlign) { 2232 EVT IntermediateVT; 2233 MVT RegisterVT; 2234 unsigned NumIntermediates; 2235 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2236 NumIntermediates, RegisterVT); 2237 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2238 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2239 if (RedAlign2 < RedAlign) 2240 RedAlign = RedAlign2; 2241 } 2242 2243 return RedAlign; 2244 } 2245 2246 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2247 MachineFrameInfo &MFI = MF->getFrameInfo(); 2248 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2249 int StackID = 0; 2250 if (Bytes.isScalable()) 2251 StackID = TFI->getStackIDForScalableVectors(); 2252 // The stack id gives an indication of whether the object is scalable or 2253 // not, so it's safe to pass in the minimum size here. 2254 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2255 false, nullptr, StackID); 2256 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2257 } 2258 2259 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2260 Type *Ty = VT.getTypeForEVT(*getContext()); 2261 Align StackAlign = 2262 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2263 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2264 } 2265 2266 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2267 TypeSize VT1Size = VT1.getStoreSize(); 2268 TypeSize VT2Size = VT2.getStoreSize(); 2269 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2270 "Don't know how to choose the maximum size when creating a stack " 2271 "temporary"); 2272 TypeSize Bytes = 2273 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2274 2275 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2276 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2277 const DataLayout &DL = getDataLayout(); 2278 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2279 return CreateStackTemporary(Bytes, Align); 2280 } 2281 2282 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2283 ISD::CondCode Cond, const SDLoc &dl) { 2284 EVT OpVT = N1.getValueType(); 2285 2286 // These setcc operations always fold. 2287 switch (Cond) { 2288 default: break; 2289 case ISD::SETFALSE: 2290 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2291 case ISD::SETTRUE: 2292 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2293 2294 case ISD::SETOEQ: 2295 case ISD::SETOGT: 2296 case ISD::SETOGE: 2297 case ISD::SETOLT: 2298 case ISD::SETOLE: 2299 case ISD::SETONE: 2300 case ISD::SETO: 2301 case ISD::SETUO: 2302 case ISD::SETUEQ: 2303 case ISD::SETUNE: 2304 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2305 break; 2306 } 2307 2308 if (OpVT.isInteger()) { 2309 // For EQ and NE, we can always pick a value for the undef to make the 2310 // predicate pass or fail, so we can return undef. 2311 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2312 // icmp eq/ne X, undef -> undef. 2313 if ((N1.isUndef() || N2.isUndef()) && 2314 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2315 return getUNDEF(VT); 2316 2317 // If both operands are undef, we can return undef for int comparison. 2318 // icmp undef, undef -> undef. 2319 if (N1.isUndef() && N2.isUndef()) 2320 return getUNDEF(VT); 2321 2322 // icmp X, X -> true/false 2323 // icmp X, undef -> true/false because undef could be X. 2324 if (N1 == N2) 2325 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2326 } 2327 2328 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2329 const APInt &C2 = N2C->getAPIntValue(); 2330 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2331 const APInt &C1 = N1C->getAPIntValue(); 2332 2333 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2334 dl, VT, OpVT); 2335 } 2336 } 2337 2338 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2339 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2340 2341 if (N1CFP && N2CFP) { 2342 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2343 switch (Cond) { 2344 default: break; 2345 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2346 return getUNDEF(VT); 2347 LLVM_FALLTHROUGH; 2348 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2349 OpVT); 2350 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2351 return getUNDEF(VT); 2352 LLVM_FALLTHROUGH; 2353 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2354 R==APFloat::cmpLessThan, dl, VT, 2355 OpVT); 2356 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2357 return getUNDEF(VT); 2358 LLVM_FALLTHROUGH; 2359 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2360 OpVT); 2361 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2362 return getUNDEF(VT); 2363 LLVM_FALLTHROUGH; 2364 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2365 VT, OpVT); 2366 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2367 return getUNDEF(VT); 2368 LLVM_FALLTHROUGH; 2369 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2370 R==APFloat::cmpEqual, dl, VT, 2371 OpVT); 2372 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2373 return getUNDEF(VT); 2374 LLVM_FALLTHROUGH; 2375 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2376 R==APFloat::cmpEqual, dl, VT, OpVT); 2377 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2378 OpVT); 2379 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2380 OpVT); 2381 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2382 R==APFloat::cmpEqual, dl, VT, 2383 OpVT); 2384 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2385 OpVT); 2386 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2387 R==APFloat::cmpLessThan, dl, VT, 2388 OpVT); 2389 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2390 R==APFloat::cmpUnordered, dl, VT, 2391 OpVT); 2392 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2393 VT, OpVT); 2394 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2395 OpVT); 2396 } 2397 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2398 // Ensure that the constant occurs on the RHS. 2399 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2400 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2401 return SDValue(); 2402 return getSetCC(dl, VT, N2, N1, SwappedCond); 2403 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2404 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2405 // If an operand is known to be a nan (or undef that could be a nan), we can 2406 // fold it. 2407 // Choosing NaN for the undef will always make unordered comparison succeed 2408 // and ordered comparison fails. 2409 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2410 switch (ISD::getUnorderedFlavor(Cond)) { 2411 default: 2412 llvm_unreachable("Unknown flavor!"); 2413 case 0: // Known false. 2414 return getBoolConstant(false, dl, VT, OpVT); 2415 case 1: // Known true. 2416 return getBoolConstant(true, dl, VT, OpVT); 2417 case 2: // Undefined. 2418 return getUNDEF(VT); 2419 } 2420 } 2421 2422 // Could not fold it. 2423 return SDValue(); 2424 } 2425 2426 /// See if the specified operand can be simplified with the knowledge that only 2427 /// the bits specified by DemandedBits are used. 2428 /// TODO: really we should be making this into the DAG equivalent of 2429 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2430 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2431 EVT VT = V.getValueType(); 2432 2433 if (VT.isScalableVector()) 2434 return SDValue(); 2435 2436 APInt DemandedElts = VT.isVector() 2437 ? APInt::getAllOnes(VT.getVectorNumElements()) 2438 : APInt(1, 1); 2439 return GetDemandedBits(V, DemandedBits, DemandedElts); 2440 } 2441 2442 /// See if the specified operand can be simplified with the knowledge that only 2443 /// the bits specified by DemandedBits are used in the elements specified by 2444 /// DemandedElts. 2445 /// TODO: really we should be making this into the DAG equivalent of 2446 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2447 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2448 const APInt &DemandedElts) { 2449 switch (V.getOpcode()) { 2450 default: 2451 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2452 *this); 2453 case ISD::Constant: { 2454 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2455 APInt NewVal = CVal & DemandedBits; 2456 if (NewVal != CVal) 2457 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2458 break; 2459 } 2460 case ISD::SRL: 2461 // Only look at single-use SRLs. 2462 if (!V.getNode()->hasOneUse()) 2463 break; 2464 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2465 // See if we can recursively simplify the LHS. 2466 unsigned Amt = RHSC->getZExtValue(); 2467 2468 // Watch out for shift count overflow though. 2469 if (Amt >= DemandedBits.getBitWidth()) 2470 break; 2471 APInt SrcDemandedBits = DemandedBits << Amt; 2472 if (SDValue SimplifyLHS = 2473 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2474 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2475 V.getOperand(1)); 2476 } 2477 break; 2478 } 2479 return SDValue(); 2480 } 2481 2482 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2483 /// use this predicate to simplify operations downstream. 2484 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2485 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2486 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2487 } 2488 2489 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2490 /// this predicate to simplify operations downstream. Mask is known to be zero 2491 /// for bits that V cannot have. 2492 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2493 unsigned Depth) const { 2494 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2495 } 2496 2497 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2498 /// DemandedElts. We use this predicate to simplify operations downstream. 2499 /// Mask is known to be zero for bits that V cannot have. 2500 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2501 const APInt &DemandedElts, 2502 unsigned Depth) const { 2503 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2504 } 2505 2506 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2507 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2508 unsigned Depth) const { 2509 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2510 } 2511 2512 /// isSplatValue - Return true if the vector V has the same value 2513 /// across all DemandedElts. For scalable vectors it does not make 2514 /// sense to specify which elements are demanded or undefined, therefore 2515 /// they are simply ignored. 2516 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2517 APInt &UndefElts, unsigned Depth) const { 2518 unsigned Opcode = V.getOpcode(); 2519 EVT VT = V.getValueType(); 2520 assert(VT.isVector() && "Vector type expected"); 2521 2522 if (!VT.isScalableVector() && !DemandedElts) 2523 return false; // No demanded elts, better to assume we don't know anything. 2524 2525 if (Depth >= MaxRecursionDepth) 2526 return false; // Limit search depth. 2527 2528 // Deal with some common cases here that work for both fixed and scalable 2529 // vector types. 2530 switch (Opcode) { 2531 case ISD::SPLAT_VECTOR: 2532 UndefElts = V.getOperand(0).isUndef() 2533 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2534 : APInt(DemandedElts.getBitWidth(), 0); 2535 return true; 2536 case ISD::ADD: 2537 case ISD::SUB: 2538 case ISD::AND: 2539 case ISD::XOR: 2540 case ISD::OR: { 2541 APInt UndefLHS, UndefRHS; 2542 SDValue LHS = V.getOperand(0); 2543 SDValue RHS = V.getOperand(1); 2544 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2545 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2546 UndefElts = UndefLHS | UndefRHS; 2547 return true; 2548 } 2549 return false; 2550 } 2551 case ISD::ABS: 2552 case ISD::TRUNCATE: 2553 case ISD::SIGN_EXTEND: 2554 case ISD::ZERO_EXTEND: 2555 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2556 default: 2557 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2558 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2559 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth); 2560 break; 2561 } 2562 2563 // We don't support other cases than those above for scalable vectors at 2564 // the moment. 2565 if (VT.isScalableVector()) 2566 return false; 2567 2568 unsigned NumElts = VT.getVectorNumElements(); 2569 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2570 UndefElts = APInt::getZero(NumElts); 2571 2572 switch (Opcode) { 2573 case ISD::BUILD_VECTOR: { 2574 SDValue Scl; 2575 for (unsigned i = 0; i != NumElts; ++i) { 2576 SDValue Op = V.getOperand(i); 2577 if (Op.isUndef()) { 2578 UndefElts.setBit(i); 2579 continue; 2580 } 2581 if (!DemandedElts[i]) 2582 continue; 2583 if (Scl && Scl != Op) 2584 return false; 2585 Scl = Op; 2586 } 2587 return true; 2588 } 2589 case ISD::VECTOR_SHUFFLE: { 2590 // Check if this is a shuffle node doing a splat. 2591 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2592 int SplatIndex = -1; 2593 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2594 for (int i = 0; i != (int)NumElts; ++i) { 2595 int M = Mask[i]; 2596 if (M < 0) { 2597 UndefElts.setBit(i); 2598 continue; 2599 } 2600 if (!DemandedElts[i]) 2601 continue; 2602 if (0 <= SplatIndex && SplatIndex != M) 2603 return false; 2604 SplatIndex = M; 2605 } 2606 return true; 2607 } 2608 case ISD::EXTRACT_SUBVECTOR: { 2609 // Offset the demanded elts by the subvector index. 2610 SDValue Src = V.getOperand(0); 2611 // We don't support scalable vectors at the moment. 2612 if (Src.getValueType().isScalableVector()) 2613 return false; 2614 uint64_t Idx = V.getConstantOperandVal(1); 2615 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2616 APInt UndefSrcElts; 2617 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2618 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2619 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2620 return true; 2621 } 2622 break; 2623 } 2624 case ISD::ANY_EXTEND_VECTOR_INREG: 2625 case ISD::SIGN_EXTEND_VECTOR_INREG: 2626 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2627 // Widen the demanded elts by the src element count. 2628 SDValue Src = V.getOperand(0); 2629 // We don't support scalable vectors at the moment. 2630 if (Src.getValueType().isScalableVector()) 2631 return false; 2632 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2633 APInt UndefSrcElts; 2634 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 2635 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2636 UndefElts = UndefSrcElts.truncOrSelf(NumElts); 2637 return true; 2638 } 2639 break; 2640 } 2641 } 2642 2643 return false; 2644 } 2645 2646 /// Helper wrapper to main isSplatValue function. 2647 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2648 EVT VT = V.getValueType(); 2649 assert(VT.isVector() && "Vector type expected"); 2650 2651 APInt UndefElts; 2652 APInt DemandedElts; 2653 2654 // For now we don't support this with scalable vectors. 2655 if (!VT.isScalableVector()) 2656 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2657 return isSplatValue(V, DemandedElts, UndefElts) && 2658 (AllowUndefs || !UndefElts); 2659 } 2660 2661 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2662 V = peekThroughExtractSubvectors(V); 2663 2664 EVT VT = V.getValueType(); 2665 unsigned Opcode = V.getOpcode(); 2666 switch (Opcode) { 2667 default: { 2668 APInt UndefElts; 2669 APInt DemandedElts; 2670 2671 if (!VT.isScalableVector()) 2672 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2673 2674 if (isSplatValue(V, DemandedElts, UndefElts)) { 2675 if (VT.isScalableVector()) { 2676 // DemandedElts and UndefElts are ignored for scalable vectors, since 2677 // the only supported cases are SPLAT_VECTOR nodes. 2678 SplatIdx = 0; 2679 } else { 2680 // Handle case where all demanded elements are UNDEF. 2681 if (DemandedElts.isSubsetOf(UndefElts)) { 2682 SplatIdx = 0; 2683 return getUNDEF(VT); 2684 } 2685 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2686 } 2687 return V; 2688 } 2689 break; 2690 } 2691 case ISD::SPLAT_VECTOR: 2692 SplatIdx = 0; 2693 return V; 2694 case ISD::VECTOR_SHUFFLE: { 2695 if (VT.isScalableVector()) 2696 return SDValue(); 2697 2698 // Check if this is a shuffle node doing a splat. 2699 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2700 // getTargetVShiftNode currently struggles without the splat source. 2701 auto *SVN = cast<ShuffleVectorSDNode>(V); 2702 if (!SVN->isSplat()) 2703 break; 2704 int Idx = SVN->getSplatIndex(); 2705 int NumElts = V.getValueType().getVectorNumElements(); 2706 SplatIdx = Idx % NumElts; 2707 return V.getOperand(Idx / NumElts); 2708 } 2709 } 2710 2711 return SDValue(); 2712 } 2713 2714 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2715 int SplatIdx; 2716 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2717 EVT SVT = SrcVector.getValueType().getScalarType(); 2718 EVT LegalSVT = SVT; 2719 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2720 if (!SVT.isInteger()) 2721 return SDValue(); 2722 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2723 if (LegalSVT.bitsLT(SVT)) 2724 return SDValue(); 2725 } 2726 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2727 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2728 } 2729 return SDValue(); 2730 } 2731 2732 const APInt * 2733 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2734 const APInt &DemandedElts) const { 2735 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2736 V.getOpcode() == ISD::SRA) && 2737 "Unknown shift node"); 2738 unsigned BitWidth = V.getScalarValueSizeInBits(); 2739 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2740 // Shifting more than the bitwidth is not valid. 2741 const APInt &ShAmt = SA->getAPIntValue(); 2742 if (ShAmt.ult(BitWidth)) 2743 return &ShAmt; 2744 } 2745 return nullptr; 2746 } 2747 2748 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2749 SDValue V, const APInt &DemandedElts) const { 2750 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2751 V.getOpcode() == ISD::SRA) && 2752 "Unknown shift node"); 2753 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2754 return ValidAmt; 2755 unsigned BitWidth = V.getScalarValueSizeInBits(); 2756 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2757 if (!BV) 2758 return nullptr; 2759 const APInt *MinShAmt = nullptr; 2760 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2761 if (!DemandedElts[i]) 2762 continue; 2763 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2764 if (!SA) 2765 return nullptr; 2766 // Shifting more than the bitwidth is not valid. 2767 const APInt &ShAmt = SA->getAPIntValue(); 2768 if (ShAmt.uge(BitWidth)) 2769 return nullptr; 2770 if (MinShAmt && MinShAmt->ule(ShAmt)) 2771 continue; 2772 MinShAmt = &ShAmt; 2773 } 2774 return MinShAmt; 2775 } 2776 2777 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2778 SDValue V, const APInt &DemandedElts) const { 2779 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2780 V.getOpcode() == ISD::SRA) && 2781 "Unknown shift node"); 2782 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2783 return ValidAmt; 2784 unsigned BitWidth = V.getScalarValueSizeInBits(); 2785 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2786 if (!BV) 2787 return nullptr; 2788 const APInt *MaxShAmt = nullptr; 2789 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2790 if (!DemandedElts[i]) 2791 continue; 2792 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2793 if (!SA) 2794 return nullptr; 2795 // Shifting more than the bitwidth is not valid. 2796 const APInt &ShAmt = SA->getAPIntValue(); 2797 if (ShAmt.uge(BitWidth)) 2798 return nullptr; 2799 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2800 continue; 2801 MaxShAmt = &ShAmt; 2802 } 2803 return MaxShAmt; 2804 } 2805 2806 /// Determine which bits of Op are known to be either zero or one and return 2807 /// them in Known. For vectors, the known bits are those that are shared by 2808 /// every vector element. 2809 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2810 EVT VT = Op.getValueType(); 2811 2812 // TOOD: Until we have a plan for how to represent demanded elements for 2813 // scalable vectors, we can just bail out for now. 2814 if (Op.getValueType().isScalableVector()) { 2815 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2816 return KnownBits(BitWidth); 2817 } 2818 2819 APInt DemandedElts = VT.isVector() 2820 ? APInt::getAllOnes(VT.getVectorNumElements()) 2821 : APInt(1, 1); 2822 return computeKnownBits(Op, DemandedElts, Depth); 2823 } 2824 2825 /// Determine which bits of Op are known to be either zero or one and return 2826 /// them in Known. The DemandedElts argument allows us to only collect the known 2827 /// bits that are shared by the requested vector elements. 2828 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2829 unsigned Depth) const { 2830 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2831 2832 KnownBits Known(BitWidth); // Don't know anything. 2833 2834 // TOOD: Until we have a plan for how to represent demanded elements for 2835 // scalable vectors, we can just bail out for now. 2836 if (Op.getValueType().isScalableVector()) 2837 return Known; 2838 2839 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2840 // We know all of the bits for a constant! 2841 return KnownBits::makeConstant(C->getAPIntValue()); 2842 } 2843 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2844 // We know all of the bits for a constant fp! 2845 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2846 } 2847 2848 if (Depth >= MaxRecursionDepth) 2849 return Known; // Limit search depth. 2850 2851 KnownBits Known2; 2852 unsigned NumElts = DemandedElts.getBitWidth(); 2853 assert((!Op.getValueType().isVector() || 2854 NumElts == Op.getValueType().getVectorNumElements()) && 2855 "Unexpected vector size"); 2856 2857 if (!DemandedElts) 2858 return Known; // No demanded elts, better to assume we don't know anything. 2859 2860 unsigned Opcode = Op.getOpcode(); 2861 switch (Opcode) { 2862 case ISD::BUILD_VECTOR: 2863 // Collect the known bits that are shared by every demanded vector element. 2864 Known.Zero.setAllBits(); Known.One.setAllBits(); 2865 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2866 if (!DemandedElts[i]) 2867 continue; 2868 2869 SDValue SrcOp = Op.getOperand(i); 2870 Known2 = computeKnownBits(SrcOp, Depth + 1); 2871 2872 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2873 if (SrcOp.getValueSizeInBits() != BitWidth) { 2874 assert(SrcOp.getValueSizeInBits() > BitWidth && 2875 "Expected BUILD_VECTOR implicit truncation"); 2876 Known2 = Known2.trunc(BitWidth); 2877 } 2878 2879 // Known bits are the values that are shared by every demanded element. 2880 Known = KnownBits::commonBits(Known, Known2); 2881 2882 // If we don't know any bits, early out. 2883 if (Known.isUnknown()) 2884 break; 2885 } 2886 break; 2887 case ISD::VECTOR_SHUFFLE: { 2888 // Collect the known bits that are shared by every vector element referenced 2889 // by the shuffle. 2890 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2891 Known.Zero.setAllBits(); Known.One.setAllBits(); 2892 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2893 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2894 for (unsigned i = 0; i != NumElts; ++i) { 2895 if (!DemandedElts[i]) 2896 continue; 2897 2898 int M = SVN->getMaskElt(i); 2899 if (M < 0) { 2900 // For UNDEF elements, we don't know anything about the common state of 2901 // the shuffle result. 2902 Known.resetAll(); 2903 DemandedLHS.clearAllBits(); 2904 DemandedRHS.clearAllBits(); 2905 break; 2906 } 2907 2908 if ((unsigned)M < NumElts) 2909 DemandedLHS.setBit((unsigned)M % NumElts); 2910 else 2911 DemandedRHS.setBit((unsigned)M % NumElts); 2912 } 2913 // Known bits are the values that are shared by every demanded element. 2914 if (!!DemandedLHS) { 2915 SDValue LHS = Op.getOperand(0); 2916 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2917 Known = KnownBits::commonBits(Known, Known2); 2918 } 2919 // If we don't know any bits, early out. 2920 if (Known.isUnknown()) 2921 break; 2922 if (!!DemandedRHS) { 2923 SDValue RHS = Op.getOperand(1); 2924 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2925 Known = KnownBits::commonBits(Known, Known2); 2926 } 2927 break; 2928 } 2929 case ISD::CONCAT_VECTORS: { 2930 // Split DemandedElts and test each of the demanded subvectors. 2931 Known.Zero.setAllBits(); Known.One.setAllBits(); 2932 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2933 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2934 unsigned NumSubVectors = Op.getNumOperands(); 2935 for (unsigned i = 0; i != NumSubVectors; ++i) { 2936 APInt DemandedSub = 2937 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 2938 if (!!DemandedSub) { 2939 SDValue Sub = Op.getOperand(i); 2940 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2941 Known = KnownBits::commonBits(Known, Known2); 2942 } 2943 // If we don't know any bits, early out. 2944 if (Known.isUnknown()) 2945 break; 2946 } 2947 break; 2948 } 2949 case ISD::INSERT_SUBVECTOR: { 2950 // Demand any elements from the subvector and the remainder from the src its 2951 // inserted into. 2952 SDValue Src = Op.getOperand(0); 2953 SDValue Sub = Op.getOperand(1); 2954 uint64_t Idx = Op.getConstantOperandVal(2); 2955 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2956 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2957 APInt DemandedSrcElts = DemandedElts; 2958 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 2959 2960 Known.One.setAllBits(); 2961 Known.Zero.setAllBits(); 2962 if (!!DemandedSubElts) { 2963 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2964 if (Known.isUnknown()) 2965 break; // early-out. 2966 } 2967 if (!!DemandedSrcElts) { 2968 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2969 Known = KnownBits::commonBits(Known, Known2); 2970 } 2971 break; 2972 } 2973 case ISD::EXTRACT_SUBVECTOR: { 2974 // Offset the demanded elts by the subvector index. 2975 SDValue Src = Op.getOperand(0); 2976 // Bail until we can represent demanded elements for scalable vectors. 2977 if (Src.getValueType().isScalableVector()) 2978 break; 2979 uint64_t Idx = Op.getConstantOperandVal(1); 2980 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2981 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2982 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2983 break; 2984 } 2985 case ISD::SCALAR_TO_VECTOR: { 2986 // We know about scalar_to_vector as much as we know about it source, 2987 // which becomes the first element of otherwise unknown vector. 2988 if (DemandedElts != 1) 2989 break; 2990 2991 SDValue N0 = Op.getOperand(0); 2992 Known = computeKnownBits(N0, Depth + 1); 2993 if (N0.getValueSizeInBits() != BitWidth) 2994 Known = Known.trunc(BitWidth); 2995 2996 break; 2997 } 2998 case ISD::BITCAST: { 2999 SDValue N0 = Op.getOperand(0); 3000 EVT SubVT = N0.getValueType(); 3001 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3002 3003 // Ignore bitcasts from unsupported types. 3004 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3005 break; 3006 3007 // Fast handling of 'identity' bitcasts. 3008 if (BitWidth == SubBitWidth) { 3009 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3010 break; 3011 } 3012 3013 bool IsLE = getDataLayout().isLittleEndian(); 3014 3015 // Bitcast 'small element' vector to 'large element' scalar/vector. 3016 if ((BitWidth % SubBitWidth) == 0) { 3017 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3018 3019 // Collect known bits for the (larger) output by collecting the known 3020 // bits from each set of sub elements and shift these into place. 3021 // We need to separately call computeKnownBits for each set of 3022 // sub elements as the knownbits for each is likely to be different. 3023 unsigned SubScale = BitWidth / SubBitWidth; 3024 APInt SubDemandedElts(NumElts * SubScale, 0); 3025 for (unsigned i = 0; i != NumElts; ++i) 3026 if (DemandedElts[i]) 3027 SubDemandedElts.setBit(i * SubScale); 3028 3029 for (unsigned i = 0; i != SubScale; ++i) { 3030 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3031 Depth + 1); 3032 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3033 Known.insertBits(Known2, SubBitWidth * Shifts); 3034 } 3035 } 3036 3037 // Bitcast 'large element' scalar/vector to 'small element' vector. 3038 if ((SubBitWidth % BitWidth) == 0) { 3039 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3040 3041 // Collect known bits for the (smaller) output by collecting the known 3042 // bits from the overlapping larger input elements and extracting the 3043 // sub sections we actually care about. 3044 unsigned SubScale = SubBitWidth / BitWidth; 3045 APInt SubDemandedElts = 3046 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3047 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3048 3049 Known.Zero.setAllBits(); Known.One.setAllBits(); 3050 for (unsigned i = 0; i != NumElts; ++i) 3051 if (DemandedElts[i]) { 3052 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3053 unsigned Offset = (Shifts % SubScale) * BitWidth; 3054 Known = KnownBits::commonBits(Known, 3055 Known2.extractBits(BitWidth, Offset)); 3056 // If we don't know any bits, early out. 3057 if (Known.isUnknown()) 3058 break; 3059 } 3060 } 3061 break; 3062 } 3063 case ISD::AND: 3064 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3065 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3066 3067 Known &= Known2; 3068 break; 3069 case ISD::OR: 3070 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3071 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3072 3073 Known |= Known2; 3074 break; 3075 case ISD::XOR: 3076 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3077 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3078 3079 Known ^= Known2; 3080 break; 3081 case ISD::MUL: { 3082 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3083 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3084 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3085 // TODO: SelfMultiply can be poison, but not undef. 3086 if (SelfMultiply) 3087 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3088 Op.getOperand(0), DemandedElts, false, Depth + 1); 3089 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3090 break; 3091 } 3092 case ISD::MULHU: { 3093 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3094 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3095 Known = KnownBits::mulhu(Known, Known2); 3096 break; 3097 } 3098 case ISD::MULHS: { 3099 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3100 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3101 Known = KnownBits::mulhs(Known, Known2); 3102 break; 3103 } 3104 case ISD::UMUL_LOHI: { 3105 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3106 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3107 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3108 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3109 if (Op.getResNo() == 0) 3110 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3111 else 3112 Known = KnownBits::mulhu(Known, Known2); 3113 break; 3114 } 3115 case ISD::SMUL_LOHI: { 3116 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3117 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3118 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3119 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3120 if (Op.getResNo() == 0) 3121 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3122 else 3123 Known = KnownBits::mulhs(Known, Known2); 3124 break; 3125 } 3126 case ISD::UDIV: { 3127 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3128 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3129 Known = KnownBits::udiv(Known, Known2); 3130 break; 3131 } 3132 case ISD::AVGCEILU: { 3133 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3134 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3135 Known = Known.zext(BitWidth + 1); 3136 Known2 = Known2.zext(BitWidth + 1); 3137 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3138 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3139 Known = Known.extractBits(BitWidth, 1); 3140 break; 3141 } 3142 case ISD::SELECT: 3143 case ISD::VSELECT: 3144 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3145 // If we don't know any bits, early out. 3146 if (Known.isUnknown()) 3147 break; 3148 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3149 3150 // Only known if known in both the LHS and RHS. 3151 Known = KnownBits::commonBits(Known, Known2); 3152 break; 3153 case ISD::SELECT_CC: 3154 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3155 // If we don't know any bits, early out. 3156 if (Known.isUnknown()) 3157 break; 3158 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3159 3160 // Only known if known in both the LHS and RHS. 3161 Known = KnownBits::commonBits(Known, Known2); 3162 break; 3163 case ISD::SMULO: 3164 case ISD::UMULO: 3165 if (Op.getResNo() != 1) 3166 break; 3167 // The boolean result conforms to getBooleanContents. 3168 // If we know the result of a setcc has the top bits zero, use this info. 3169 // We know that we have an integer-based boolean since these operations 3170 // are only available for integer. 3171 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3172 TargetLowering::ZeroOrOneBooleanContent && 3173 BitWidth > 1) 3174 Known.Zero.setBitsFrom(1); 3175 break; 3176 case ISD::SETCC: 3177 case ISD::STRICT_FSETCC: 3178 case ISD::STRICT_FSETCCS: { 3179 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3180 // If we know the result of a setcc has the top bits zero, use this info. 3181 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3182 TargetLowering::ZeroOrOneBooleanContent && 3183 BitWidth > 1) 3184 Known.Zero.setBitsFrom(1); 3185 break; 3186 } 3187 case ISD::SHL: 3188 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3189 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3190 Known = KnownBits::shl(Known, Known2); 3191 3192 // Minimum shift low bits are known zero. 3193 if (const APInt *ShMinAmt = 3194 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3195 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3196 break; 3197 case ISD::SRL: 3198 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3199 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3200 Known = KnownBits::lshr(Known, Known2); 3201 3202 // Minimum shift high bits are known zero. 3203 if (const APInt *ShMinAmt = 3204 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3205 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3206 break; 3207 case ISD::SRA: 3208 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3209 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3210 Known = KnownBits::ashr(Known, Known2); 3211 // TODO: Add minimum shift high known sign bits. 3212 break; 3213 case ISD::FSHL: 3214 case ISD::FSHR: 3215 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3216 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3217 3218 // For fshl, 0-shift returns the 1st arg. 3219 // For fshr, 0-shift returns the 2nd arg. 3220 if (Amt == 0) { 3221 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3222 DemandedElts, Depth + 1); 3223 break; 3224 } 3225 3226 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3227 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3228 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3229 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3230 if (Opcode == ISD::FSHL) { 3231 Known.One <<= Amt; 3232 Known.Zero <<= Amt; 3233 Known2.One.lshrInPlace(BitWidth - Amt); 3234 Known2.Zero.lshrInPlace(BitWidth - Amt); 3235 } else { 3236 Known.One <<= BitWidth - Amt; 3237 Known.Zero <<= BitWidth - Amt; 3238 Known2.One.lshrInPlace(Amt); 3239 Known2.Zero.lshrInPlace(Amt); 3240 } 3241 Known.One |= Known2.One; 3242 Known.Zero |= Known2.Zero; 3243 } 3244 break; 3245 case ISD::SIGN_EXTEND_INREG: { 3246 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3247 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3248 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3249 break; 3250 } 3251 case ISD::CTTZ: 3252 case ISD::CTTZ_ZERO_UNDEF: { 3253 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3254 // If we have a known 1, its position is our upper bound. 3255 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3256 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3257 Known.Zero.setBitsFrom(LowBits); 3258 break; 3259 } 3260 case ISD::CTLZ: 3261 case ISD::CTLZ_ZERO_UNDEF: { 3262 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3263 // If we have a known 1, its position is our upper bound. 3264 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3265 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3266 Known.Zero.setBitsFrom(LowBits); 3267 break; 3268 } 3269 case ISD::CTPOP: { 3270 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3271 // If we know some of the bits are zero, they can't be one. 3272 unsigned PossibleOnes = Known2.countMaxPopulation(); 3273 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3274 break; 3275 } 3276 case ISD::PARITY: { 3277 // Parity returns 0 everywhere but the LSB. 3278 Known.Zero.setBitsFrom(1); 3279 break; 3280 } 3281 case ISD::LOAD: { 3282 LoadSDNode *LD = cast<LoadSDNode>(Op); 3283 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3284 if (ISD::isNON_EXTLoad(LD) && Cst) { 3285 // Determine any common known bits from the loaded constant pool value. 3286 Type *CstTy = Cst->getType(); 3287 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3288 // If its a vector splat, then we can (quickly) reuse the scalar path. 3289 // NOTE: We assume all elements match and none are UNDEF. 3290 if (CstTy->isVectorTy()) { 3291 if (const Constant *Splat = Cst->getSplatValue()) { 3292 Cst = Splat; 3293 CstTy = Cst->getType(); 3294 } 3295 } 3296 // TODO - do we need to handle different bitwidths? 3297 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3298 // Iterate across all vector elements finding common known bits. 3299 Known.One.setAllBits(); 3300 Known.Zero.setAllBits(); 3301 for (unsigned i = 0; i != NumElts; ++i) { 3302 if (!DemandedElts[i]) 3303 continue; 3304 if (Constant *Elt = Cst->getAggregateElement(i)) { 3305 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3306 const APInt &Value = CInt->getValue(); 3307 Known.One &= Value; 3308 Known.Zero &= ~Value; 3309 continue; 3310 } 3311 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3312 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3313 Known.One &= Value; 3314 Known.Zero &= ~Value; 3315 continue; 3316 } 3317 } 3318 Known.One.clearAllBits(); 3319 Known.Zero.clearAllBits(); 3320 break; 3321 } 3322 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3323 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3324 Known = KnownBits::makeConstant(CInt->getValue()); 3325 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3326 Known = 3327 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3328 } 3329 } 3330 } 3331 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3332 // If this is a ZEXTLoad and we are looking at the loaded value. 3333 EVT VT = LD->getMemoryVT(); 3334 unsigned MemBits = VT.getScalarSizeInBits(); 3335 Known.Zero.setBitsFrom(MemBits); 3336 } else if (const MDNode *Ranges = LD->getRanges()) { 3337 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3338 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3339 } 3340 break; 3341 } 3342 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3343 EVT InVT = Op.getOperand(0).getValueType(); 3344 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3345 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3346 Known = Known.zext(BitWidth); 3347 break; 3348 } 3349 case ISD::ZERO_EXTEND: { 3350 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3351 Known = Known.zext(BitWidth); 3352 break; 3353 } 3354 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3355 EVT InVT = Op.getOperand(0).getValueType(); 3356 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3357 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3358 // If the sign bit is known to be zero or one, then sext will extend 3359 // it to the top bits, else it will just zext. 3360 Known = Known.sext(BitWidth); 3361 break; 3362 } 3363 case ISD::SIGN_EXTEND: { 3364 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3365 // If the sign bit is known to be zero or one, then sext will extend 3366 // it to the top bits, else it will just zext. 3367 Known = Known.sext(BitWidth); 3368 break; 3369 } 3370 case ISD::ANY_EXTEND_VECTOR_INREG: { 3371 EVT InVT = Op.getOperand(0).getValueType(); 3372 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3373 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3374 Known = Known.anyext(BitWidth); 3375 break; 3376 } 3377 case ISD::ANY_EXTEND: { 3378 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3379 Known = Known.anyext(BitWidth); 3380 break; 3381 } 3382 case ISD::TRUNCATE: { 3383 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3384 Known = Known.trunc(BitWidth); 3385 break; 3386 } 3387 case ISD::AssertZext: { 3388 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3389 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3390 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3391 Known.Zero |= (~InMask); 3392 Known.One &= (~Known.Zero); 3393 break; 3394 } 3395 case ISD::AssertAlign: { 3396 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3397 assert(LogOfAlign != 0); 3398 3399 // TODO: Should use maximum with source 3400 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3401 // well as clearing one bits. 3402 Known.Zero.setLowBits(LogOfAlign); 3403 Known.One.clearLowBits(LogOfAlign); 3404 break; 3405 } 3406 case ISD::FGETSIGN: 3407 // All bits are zero except the low bit. 3408 Known.Zero.setBitsFrom(1); 3409 break; 3410 case ISD::USUBO: 3411 case ISD::SSUBO: 3412 if (Op.getResNo() == 1) { 3413 // If we know the result of a setcc has the top bits zero, use this info. 3414 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3415 TargetLowering::ZeroOrOneBooleanContent && 3416 BitWidth > 1) 3417 Known.Zero.setBitsFrom(1); 3418 break; 3419 } 3420 LLVM_FALLTHROUGH; 3421 case ISD::SUB: 3422 case ISD::SUBC: { 3423 assert(Op.getResNo() == 0 && 3424 "We only compute knownbits for the difference here."); 3425 3426 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3427 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3428 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3429 Known, Known2); 3430 break; 3431 } 3432 case ISD::UADDO: 3433 case ISD::SADDO: 3434 case ISD::ADDCARRY: 3435 if (Op.getResNo() == 1) { 3436 // If we know the result of a setcc has the top bits zero, use this info. 3437 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3438 TargetLowering::ZeroOrOneBooleanContent && 3439 BitWidth > 1) 3440 Known.Zero.setBitsFrom(1); 3441 break; 3442 } 3443 LLVM_FALLTHROUGH; 3444 case ISD::ADD: 3445 case ISD::ADDC: 3446 case ISD::ADDE: { 3447 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3448 3449 // With ADDE and ADDCARRY, a carry bit may be added in. 3450 KnownBits Carry(1); 3451 if (Opcode == ISD::ADDE) 3452 // Can't track carry from glue, set carry to unknown. 3453 Carry.resetAll(); 3454 else if (Opcode == ISD::ADDCARRY) 3455 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3456 // the trouble (how often will we find a known carry bit). And I haven't 3457 // tested this very much yet, but something like this might work: 3458 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3459 // Carry = Carry.zextOrTrunc(1, false); 3460 Carry.resetAll(); 3461 else 3462 Carry.setAllZero(); 3463 3464 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3465 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3466 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3467 break; 3468 } 3469 case ISD::SREM: { 3470 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3471 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3472 Known = KnownBits::srem(Known, Known2); 3473 break; 3474 } 3475 case ISD::UREM: { 3476 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3477 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3478 Known = KnownBits::urem(Known, Known2); 3479 break; 3480 } 3481 case ISD::EXTRACT_ELEMENT: { 3482 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3483 const unsigned Index = Op.getConstantOperandVal(1); 3484 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3485 3486 // Remove low part of known bits mask 3487 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3488 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3489 3490 // Remove high part of known bit mask 3491 Known = Known.trunc(EltBitWidth); 3492 break; 3493 } 3494 case ISD::EXTRACT_VECTOR_ELT: { 3495 SDValue InVec = Op.getOperand(0); 3496 SDValue EltNo = Op.getOperand(1); 3497 EVT VecVT = InVec.getValueType(); 3498 // computeKnownBits not yet implemented for scalable vectors. 3499 if (VecVT.isScalableVector()) 3500 break; 3501 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3502 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3503 3504 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3505 // anything about the extended bits. 3506 if (BitWidth > EltBitWidth) 3507 Known = Known.trunc(EltBitWidth); 3508 3509 // If we know the element index, just demand that vector element, else for 3510 // an unknown element index, ignore DemandedElts and demand them all. 3511 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3512 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3513 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3514 DemandedSrcElts = 3515 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3516 3517 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3518 if (BitWidth > EltBitWidth) 3519 Known = Known.anyext(BitWidth); 3520 break; 3521 } 3522 case ISD::INSERT_VECTOR_ELT: { 3523 // If we know the element index, split the demand between the 3524 // source vector and the inserted element, otherwise assume we need 3525 // the original demanded vector elements and the value. 3526 SDValue InVec = Op.getOperand(0); 3527 SDValue InVal = Op.getOperand(1); 3528 SDValue EltNo = Op.getOperand(2); 3529 bool DemandedVal = true; 3530 APInt DemandedVecElts = DemandedElts; 3531 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3532 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3533 unsigned EltIdx = CEltNo->getZExtValue(); 3534 DemandedVal = !!DemandedElts[EltIdx]; 3535 DemandedVecElts.clearBit(EltIdx); 3536 } 3537 Known.One.setAllBits(); 3538 Known.Zero.setAllBits(); 3539 if (DemandedVal) { 3540 Known2 = computeKnownBits(InVal, Depth + 1); 3541 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3542 } 3543 if (!!DemandedVecElts) { 3544 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3545 Known = KnownBits::commonBits(Known, Known2); 3546 } 3547 break; 3548 } 3549 case ISD::BITREVERSE: { 3550 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3551 Known = Known2.reverseBits(); 3552 break; 3553 } 3554 case ISD::BSWAP: { 3555 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3556 Known = Known2.byteSwap(); 3557 break; 3558 } 3559 case ISD::ABS: { 3560 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3561 Known = Known2.abs(); 3562 break; 3563 } 3564 case ISD::USUBSAT: { 3565 // The result of usubsat will never be larger than the LHS. 3566 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3567 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3568 break; 3569 } 3570 case ISD::UMIN: { 3571 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3572 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3573 Known = KnownBits::umin(Known, Known2); 3574 break; 3575 } 3576 case ISD::UMAX: { 3577 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3578 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3579 Known = KnownBits::umax(Known, Known2); 3580 break; 3581 } 3582 case ISD::SMIN: 3583 case ISD::SMAX: { 3584 // If we have a clamp pattern, we know that the number of sign bits will be 3585 // the minimum of the clamp min/max range. 3586 bool IsMax = (Opcode == ISD::SMAX); 3587 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3588 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3589 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3590 CstHigh = 3591 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3592 if (CstLow && CstHigh) { 3593 if (!IsMax) 3594 std::swap(CstLow, CstHigh); 3595 3596 const APInt &ValueLow = CstLow->getAPIntValue(); 3597 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3598 if (ValueLow.sle(ValueHigh)) { 3599 unsigned LowSignBits = ValueLow.getNumSignBits(); 3600 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3601 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3602 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3603 Known.One.setHighBits(MinSignBits); 3604 break; 3605 } 3606 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3607 Known.Zero.setHighBits(MinSignBits); 3608 break; 3609 } 3610 } 3611 } 3612 3613 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3614 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3615 if (IsMax) 3616 Known = KnownBits::smax(Known, Known2); 3617 else 3618 Known = KnownBits::smin(Known, Known2); 3619 break; 3620 } 3621 case ISD::FP_TO_UINT_SAT: { 3622 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3623 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3624 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3625 break; 3626 } 3627 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3628 if (Op.getResNo() == 1) { 3629 // The boolean result conforms to getBooleanContents. 3630 // If we know the result of a setcc has the top bits zero, use this info. 3631 // We know that we have an integer-based boolean since these operations 3632 // are only available for integer. 3633 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3634 TargetLowering::ZeroOrOneBooleanContent && 3635 BitWidth > 1) 3636 Known.Zero.setBitsFrom(1); 3637 break; 3638 } 3639 LLVM_FALLTHROUGH; 3640 case ISD::ATOMIC_CMP_SWAP: 3641 case ISD::ATOMIC_SWAP: 3642 case ISD::ATOMIC_LOAD_ADD: 3643 case ISD::ATOMIC_LOAD_SUB: 3644 case ISD::ATOMIC_LOAD_AND: 3645 case ISD::ATOMIC_LOAD_CLR: 3646 case ISD::ATOMIC_LOAD_OR: 3647 case ISD::ATOMIC_LOAD_XOR: 3648 case ISD::ATOMIC_LOAD_NAND: 3649 case ISD::ATOMIC_LOAD_MIN: 3650 case ISD::ATOMIC_LOAD_MAX: 3651 case ISD::ATOMIC_LOAD_UMIN: 3652 case ISD::ATOMIC_LOAD_UMAX: 3653 case ISD::ATOMIC_LOAD: { 3654 unsigned MemBits = 3655 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3656 // If we are looking at the loaded value. 3657 if (Op.getResNo() == 0) { 3658 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3659 Known.Zero.setBitsFrom(MemBits); 3660 } 3661 break; 3662 } 3663 case ISD::FrameIndex: 3664 case ISD::TargetFrameIndex: 3665 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3666 Known, getMachineFunction()); 3667 break; 3668 3669 default: 3670 if (Opcode < ISD::BUILTIN_OP_END) 3671 break; 3672 LLVM_FALLTHROUGH; 3673 case ISD::INTRINSIC_WO_CHAIN: 3674 case ISD::INTRINSIC_W_CHAIN: 3675 case ISD::INTRINSIC_VOID: 3676 // Allow the target to implement this method for its nodes. 3677 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3678 break; 3679 } 3680 3681 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3682 return Known; 3683 } 3684 3685 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3686 SDValue N1) const { 3687 // X + 0 never overflow 3688 if (isNullConstant(N1)) 3689 return OFK_Never; 3690 3691 KnownBits N1Known = computeKnownBits(N1); 3692 if (N1Known.Zero.getBoolValue()) { 3693 KnownBits N0Known = computeKnownBits(N0); 3694 3695 bool overflow; 3696 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3697 if (!overflow) 3698 return OFK_Never; 3699 } 3700 3701 // mulhi + 1 never overflow 3702 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3703 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3704 return OFK_Never; 3705 3706 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3707 KnownBits N0Known = computeKnownBits(N0); 3708 3709 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3710 return OFK_Never; 3711 } 3712 3713 return OFK_Sometime; 3714 } 3715 3716 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3717 EVT OpVT = Val.getValueType(); 3718 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3719 3720 // Is the constant a known power of 2? 3721 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3722 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3723 3724 // A left-shift of a constant one will have exactly one bit set because 3725 // shifting the bit off the end is undefined. 3726 if (Val.getOpcode() == ISD::SHL) { 3727 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3728 if (C && C->getAPIntValue() == 1) 3729 return true; 3730 } 3731 3732 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3733 // one bit set. 3734 if (Val.getOpcode() == ISD::SRL) { 3735 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3736 if (C && C->getAPIntValue().isSignMask()) 3737 return true; 3738 } 3739 3740 // Are all operands of a build vector constant powers of two? 3741 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3742 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3743 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3744 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3745 return false; 3746 })) 3747 return true; 3748 3749 // Is the operand of a splat vector a constant power of two? 3750 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3751 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3752 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3753 return true; 3754 3755 // More could be done here, though the above checks are enough 3756 // to handle some common cases. 3757 3758 // Fall back to computeKnownBits to catch other known cases. 3759 KnownBits Known = computeKnownBits(Val); 3760 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3761 } 3762 3763 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3764 EVT VT = Op.getValueType(); 3765 3766 // TODO: Assume we don't know anything for now. 3767 if (VT.isScalableVector()) 3768 return 1; 3769 3770 APInt DemandedElts = VT.isVector() 3771 ? APInt::getAllOnes(VT.getVectorNumElements()) 3772 : APInt(1, 1); 3773 return ComputeNumSignBits(Op, DemandedElts, Depth); 3774 } 3775 3776 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3777 unsigned Depth) const { 3778 EVT VT = Op.getValueType(); 3779 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3780 unsigned VTBits = VT.getScalarSizeInBits(); 3781 unsigned NumElts = DemandedElts.getBitWidth(); 3782 unsigned Tmp, Tmp2; 3783 unsigned FirstAnswer = 1; 3784 3785 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3786 const APInt &Val = C->getAPIntValue(); 3787 return Val.getNumSignBits(); 3788 } 3789 3790 if (Depth >= MaxRecursionDepth) 3791 return 1; // Limit search depth. 3792 3793 if (!DemandedElts || VT.isScalableVector()) 3794 return 1; // No demanded elts, better to assume we don't know anything. 3795 3796 unsigned Opcode = Op.getOpcode(); 3797 switch (Opcode) { 3798 default: break; 3799 case ISD::AssertSext: 3800 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3801 return VTBits-Tmp+1; 3802 case ISD::AssertZext: 3803 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3804 return VTBits-Tmp; 3805 3806 case ISD::BUILD_VECTOR: 3807 Tmp = VTBits; 3808 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3809 if (!DemandedElts[i]) 3810 continue; 3811 3812 SDValue SrcOp = Op.getOperand(i); 3813 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3814 3815 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3816 if (SrcOp.getValueSizeInBits() != VTBits) { 3817 assert(SrcOp.getValueSizeInBits() > VTBits && 3818 "Expected BUILD_VECTOR implicit truncation"); 3819 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3820 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3821 } 3822 Tmp = std::min(Tmp, Tmp2); 3823 } 3824 return Tmp; 3825 3826 case ISD::VECTOR_SHUFFLE: { 3827 // Collect the minimum number of sign bits that are shared by every vector 3828 // element referenced by the shuffle. 3829 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3830 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3831 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3832 for (unsigned i = 0; i != NumElts; ++i) { 3833 int M = SVN->getMaskElt(i); 3834 if (!DemandedElts[i]) 3835 continue; 3836 // For UNDEF elements, we don't know anything about the common state of 3837 // the shuffle result. 3838 if (M < 0) 3839 return 1; 3840 if ((unsigned)M < NumElts) 3841 DemandedLHS.setBit((unsigned)M % NumElts); 3842 else 3843 DemandedRHS.setBit((unsigned)M % NumElts); 3844 } 3845 Tmp = std::numeric_limits<unsigned>::max(); 3846 if (!!DemandedLHS) 3847 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3848 if (!!DemandedRHS) { 3849 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3850 Tmp = std::min(Tmp, Tmp2); 3851 } 3852 // If we don't know anything, early out and try computeKnownBits fall-back. 3853 if (Tmp == 1) 3854 break; 3855 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3856 return Tmp; 3857 } 3858 3859 case ISD::BITCAST: { 3860 SDValue N0 = Op.getOperand(0); 3861 EVT SrcVT = N0.getValueType(); 3862 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3863 3864 // Ignore bitcasts from unsupported types.. 3865 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3866 break; 3867 3868 // Fast handling of 'identity' bitcasts. 3869 if (VTBits == SrcBits) 3870 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3871 3872 bool IsLE = getDataLayout().isLittleEndian(); 3873 3874 // Bitcast 'large element' scalar/vector to 'small element' vector. 3875 if ((SrcBits % VTBits) == 0) { 3876 assert(VT.isVector() && "Expected bitcast to vector"); 3877 3878 unsigned Scale = SrcBits / VTBits; 3879 APInt SrcDemandedElts = 3880 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3881 3882 // Fast case - sign splat can be simply split across the small elements. 3883 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3884 if (Tmp == SrcBits) 3885 return VTBits; 3886 3887 // Slow case - determine how far the sign extends into each sub-element. 3888 Tmp2 = VTBits; 3889 for (unsigned i = 0; i != NumElts; ++i) 3890 if (DemandedElts[i]) { 3891 unsigned SubOffset = i % Scale; 3892 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3893 SubOffset = SubOffset * VTBits; 3894 if (Tmp <= SubOffset) 3895 return 1; 3896 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3897 } 3898 return Tmp2; 3899 } 3900 break; 3901 } 3902 3903 case ISD::FP_TO_SINT_SAT: 3904 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 3905 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3906 return VTBits - Tmp + 1; 3907 case ISD::SIGN_EXTEND: 3908 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3909 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3910 case ISD::SIGN_EXTEND_INREG: 3911 // Max of the input and what this extends. 3912 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3913 Tmp = VTBits-Tmp+1; 3914 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3915 return std::max(Tmp, Tmp2); 3916 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3917 SDValue Src = Op.getOperand(0); 3918 EVT SrcVT = Src.getValueType(); 3919 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3920 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3921 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3922 } 3923 case ISD::SRA: 3924 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3925 // SRA X, C -> adds C sign bits. 3926 if (const APInt *ShAmt = 3927 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3928 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3929 return Tmp; 3930 case ISD::SHL: 3931 if (const APInt *ShAmt = 3932 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3933 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3934 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3935 if (ShAmt->ult(Tmp)) 3936 return Tmp - ShAmt->getZExtValue(); 3937 } 3938 break; 3939 case ISD::AND: 3940 case ISD::OR: 3941 case ISD::XOR: // NOT is handled here. 3942 // Logical binary ops preserve the number of sign bits at the worst. 3943 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3944 if (Tmp != 1) { 3945 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3946 FirstAnswer = std::min(Tmp, Tmp2); 3947 // We computed what we know about the sign bits as our first 3948 // answer. Now proceed to the generic code that uses 3949 // computeKnownBits, and pick whichever answer is better. 3950 } 3951 break; 3952 3953 case ISD::SELECT: 3954 case ISD::VSELECT: 3955 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3956 if (Tmp == 1) return 1; // Early out. 3957 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3958 return std::min(Tmp, Tmp2); 3959 case ISD::SELECT_CC: 3960 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3961 if (Tmp == 1) return 1; // Early out. 3962 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3963 return std::min(Tmp, Tmp2); 3964 3965 case ISD::SMIN: 3966 case ISD::SMAX: { 3967 // If we have a clamp pattern, we know that the number of sign bits will be 3968 // the minimum of the clamp min/max range. 3969 bool IsMax = (Opcode == ISD::SMAX); 3970 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3971 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3972 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3973 CstHigh = 3974 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3975 if (CstLow && CstHigh) { 3976 if (!IsMax) 3977 std::swap(CstLow, CstHigh); 3978 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3979 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3980 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3981 return std::min(Tmp, Tmp2); 3982 } 3983 } 3984 3985 // Fallback - just get the minimum number of sign bits of the operands. 3986 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3987 if (Tmp == 1) 3988 return 1; // Early out. 3989 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3990 return std::min(Tmp, Tmp2); 3991 } 3992 case ISD::UMIN: 3993 case ISD::UMAX: 3994 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3995 if (Tmp == 1) 3996 return 1; // Early out. 3997 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3998 return std::min(Tmp, Tmp2); 3999 case ISD::SADDO: 4000 case ISD::UADDO: 4001 case ISD::SSUBO: 4002 case ISD::USUBO: 4003 case ISD::SMULO: 4004 case ISD::UMULO: 4005 if (Op.getResNo() != 1) 4006 break; 4007 // The boolean result conforms to getBooleanContents. Fall through. 4008 // If setcc returns 0/-1, all bits are sign bits. 4009 // We know that we have an integer-based boolean since these operations 4010 // are only available for integer. 4011 if (TLI->getBooleanContents(VT.isVector(), false) == 4012 TargetLowering::ZeroOrNegativeOneBooleanContent) 4013 return VTBits; 4014 break; 4015 case ISD::SETCC: 4016 case ISD::STRICT_FSETCC: 4017 case ISD::STRICT_FSETCCS: { 4018 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4019 // If setcc returns 0/-1, all bits are sign bits. 4020 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4021 TargetLowering::ZeroOrNegativeOneBooleanContent) 4022 return VTBits; 4023 break; 4024 } 4025 case ISD::ROTL: 4026 case ISD::ROTR: 4027 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4028 4029 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4030 if (Tmp == VTBits) 4031 return VTBits; 4032 4033 if (ConstantSDNode *C = 4034 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4035 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4036 4037 // Handle rotate right by N like a rotate left by 32-N. 4038 if (Opcode == ISD::ROTR) 4039 RotAmt = (VTBits - RotAmt) % VTBits; 4040 4041 // If we aren't rotating out all of the known-in sign bits, return the 4042 // number that are left. This handles rotl(sext(x), 1) for example. 4043 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4044 } 4045 break; 4046 case ISD::ADD: 4047 case ISD::ADDC: 4048 // Add can have at most one carry bit. Thus we know that the output 4049 // is, at worst, one more bit than the inputs. 4050 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4051 if (Tmp == 1) return 1; // Early out. 4052 4053 // Special case decrementing a value (ADD X, -1): 4054 if (ConstantSDNode *CRHS = 4055 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4056 if (CRHS->isAllOnes()) { 4057 KnownBits Known = 4058 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4059 4060 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4061 // sign bits set. 4062 if ((Known.Zero | 1).isAllOnes()) 4063 return VTBits; 4064 4065 // If we are subtracting one from a positive number, there is no carry 4066 // out of the result. 4067 if (Known.isNonNegative()) 4068 return Tmp; 4069 } 4070 4071 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4072 if (Tmp2 == 1) return 1; // Early out. 4073 return std::min(Tmp, Tmp2) - 1; 4074 case ISD::SUB: 4075 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4076 if (Tmp2 == 1) return 1; // Early out. 4077 4078 // Handle NEG. 4079 if (ConstantSDNode *CLHS = 4080 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4081 if (CLHS->isZero()) { 4082 KnownBits Known = 4083 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4084 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4085 // sign bits set. 4086 if ((Known.Zero | 1).isAllOnes()) 4087 return VTBits; 4088 4089 // If the input is known to be positive (the sign bit is known clear), 4090 // the output of the NEG has the same number of sign bits as the input. 4091 if (Known.isNonNegative()) 4092 return Tmp2; 4093 4094 // Otherwise, we treat this like a SUB. 4095 } 4096 4097 // Sub can have at most one carry bit. Thus we know that the output 4098 // is, at worst, one more bit than the inputs. 4099 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4100 if (Tmp == 1) return 1; // Early out. 4101 return std::min(Tmp, Tmp2) - 1; 4102 case ISD::MUL: { 4103 // The output of the Mul can be at most twice the valid bits in the inputs. 4104 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4105 if (SignBitsOp0 == 1) 4106 break; 4107 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4108 if (SignBitsOp1 == 1) 4109 break; 4110 unsigned OutValidBits = 4111 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4112 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4113 } 4114 case ISD::SREM: 4115 // The sign bit is the LHS's sign bit, except when the result of the 4116 // remainder is zero. The magnitude of the result should be less than or 4117 // equal to the magnitude of the LHS. Therefore, the result should have 4118 // at least as many sign bits as the left hand side. 4119 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4120 case ISD::TRUNCATE: { 4121 // Check if the sign bits of source go down as far as the truncated value. 4122 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4123 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4124 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4125 return NumSrcSignBits - (NumSrcBits - VTBits); 4126 break; 4127 } 4128 case ISD::EXTRACT_ELEMENT: { 4129 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4130 const int BitWidth = Op.getValueSizeInBits(); 4131 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4132 4133 // Get reverse index (starting from 1), Op1 value indexes elements from 4134 // little end. Sign starts at big end. 4135 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4136 4137 // If the sign portion ends in our element the subtraction gives correct 4138 // result. Otherwise it gives either negative or > bitwidth result 4139 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4140 } 4141 case ISD::INSERT_VECTOR_ELT: { 4142 // If we know the element index, split the demand between the 4143 // source vector and the inserted element, otherwise assume we need 4144 // the original demanded vector elements and the value. 4145 SDValue InVec = Op.getOperand(0); 4146 SDValue InVal = Op.getOperand(1); 4147 SDValue EltNo = Op.getOperand(2); 4148 bool DemandedVal = true; 4149 APInt DemandedVecElts = DemandedElts; 4150 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4151 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4152 unsigned EltIdx = CEltNo->getZExtValue(); 4153 DemandedVal = !!DemandedElts[EltIdx]; 4154 DemandedVecElts.clearBit(EltIdx); 4155 } 4156 Tmp = std::numeric_limits<unsigned>::max(); 4157 if (DemandedVal) { 4158 // TODO - handle implicit truncation of inserted elements. 4159 if (InVal.getScalarValueSizeInBits() != VTBits) 4160 break; 4161 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4162 Tmp = std::min(Tmp, Tmp2); 4163 } 4164 if (!!DemandedVecElts) { 4165 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4166 Tmp = std::min(Tmp, Tmp2); 4167 } 4168 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4169 return Tmp; 4170 } 4171 case ISD::EXTRACT_VECTOR_ELT: { 4172 SDValue InVec = Op.getOperand(0); 4173 SDValue EltNo = Op.getOperand(1); 4174 EVT VecVT = InVec.getValueType(); 4175 // ComputeNumSignBits not yet implemented for scalable vectors. 4176 if (VecVT.isScalableVector()) 4177 break; 4178 const unsigned BitWidth = Op.getValueSizeInBits(); 4179 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4180 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4181 4182 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4183 // anything about sign bits. But if the sizes match we can derive knowledge 4184 // about sign bits from the vector operand. 4185 if (BitWidth != EltBitWidth) 4186 break; 4187 4188 // If we know the element index, just demand that vector element, else for 4189 // an unknown element index, ignore DemandedElts and demand them all. 4190 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4191 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4192 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4193 DemandedSrcElts = 4194 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4195 4196 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4197 } 4198 case ISD::EXTRACT_SUBVECTOR: { 4199 // Offset the demanded elts by the subvector index. 4200 SDValue Src = Op.getOperand(0); 4201 // Bail until we can represent demanded elements for scalable vectors. 4202 if (Src.getValueType().isScalableVector()) 4203 break; 4204 uint64_t Idx = Op.getConstantOperandVal(1); 4205 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4206 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4207 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4208 } 4209 case ISD::CONCAT_VECTORS: { 4210 // Determine the minimum number of sign bits across all demanded 4211 // elts of the input vectors. Early out if the result is already 1. 4212 Tmp = std::numeric_limits<unsigned>::max(); 4213 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4214 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4215 unsigned NumSubVectors = Op.getNumOperands(); 4216 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4217 APInt DemandedSub = 4218 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4219 if (!DemandedSub) 4220 continue; 4221 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4222 Tmp = std::min(Tmp, Tmp2); 4223 } 4224 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4225 return Tmp; 4226 } 4227 case ISD::INSERT_SUBVECTOR: { 4228 // Demand any elements from the subvector and the remainder from the src its 4229 // inserted into. 4230 SDValue Src = Op.getOperand(0); 4231 SDValue Sub = Op.getOperand(1); 4232 uint64_t Idx = Op.getConstantOperandVal(2); 4233 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4234 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4235 APInt DemandedSrcElts = DemandedElts; 4236 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4237 4238 Tmp = std::numeric_limits<unsigned>::max(); 4239 if (!!DemandedSubElts) { 4240 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4241 if (Tmp == 1) 4242 return 1; // early-out 4243 } 4244 if (!!DemandedSrcElts) { 4245 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4246 Tmp = std::min(Tmp, Tmp2); 4247 } 4248 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4249 return Tmp; 4250 } 4251 case ISD::ATOMIC_CMP_SWAP: 4252 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4253 case ISD::ATOMIC_SWAP: 4254 case ISD::ATOMIC_LOAD_ADD: 4255 case ISD::ATOMIC_LOAD_SUB: 4256 case ISD::ATOMIC_LOAD_AND: 4257 case ISD::ATOMIC_LOAD_CLR: 4258 case ISD::ATOMIC_LOAD_OR: 4259 case ISD::ATOMIC_LOAD_XOR: 4260 case ISD::ATOMIC_LOAD_NAND: 4261 case ISD::ATOMIC_LOAD_MIN: 4262 case ISD::ATOMIC_LOAD_MAX: 4263 case ISD::ATOMIC_LOAD_UMIN: 4264 case ISD::ATOMIC_LOAD_UMAX: 4265 case ISD::ATOMIC_LOAD: { 4266 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4267 // If we are looking at the loaded value. 4268 if (Op.getResNo() == 0) { 4269 if (Tmp == VTBits) 4270 return 1; // early-out 4271 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4272 return VTBits - Tmp + 1; 4273 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4274 return VTBits - Tmp; 4275 } 4276 break; 4277 } 4278 } 4279 4280 // If we are looking at the loaded value of the SDNode. 4281 if (Op.getResNo() == 0) { 4282 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4283 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4284 unsigned ExtType = LD->getExtensionType(); 4285 switch (ExtType) { 4286 default: break; 4287 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4288 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4289 return VTBits - Tmp + 1; 4290 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4291 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4292 return VTBits - Tmp; 4293 case ISD::NON_EXTLOAD: 4294 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4295 // We only need to handle vectors - computeKnownBits should handle 4296 // scalar cases. 4297 Type *CstTy = Cst->getType(); 4298 if (CstTy->isVectorTy() && 4299 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4300 VTBits == CstTy->getScalarSizeInBits()) { 4301 Tmp = VTBits; 4302 for (unsigned i = 0; i != NumElts; ++i) { 4303 if (!DemandedElts[i]) 4304 continue; 4305 if (Constant *Elt = Cst->getAggregateElement(i)) { 4306 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4307 const APInt &Value = CInt->getValue(); 4308 Tmp = std::min(Tmp, Value.getNumSignBits()); 4309 continue; 4310 } 4311 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4312 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4313 Tmp = std::min(Tmp, Value.getNumSignBits()); 4314 continue; 4315 } 4316 } 4317 // Unknown type. Conservatively assume no bits match sign bit. 4318 return 1; 4319 } 4320 return Tmp; 4321 } 4322 } 4323 break; 4324 } 4325 } 4326 } 4327 4328 // Allow the target to implement this method for its nodes. 4329 if (Opcode >= ISD::BUILTIN_OP_END || 4330 Opcode == ISD::INTRINSIC_WO_CHAIN || 4331 Opcode == ISD::INTRINSIC_W_CHAIN || 4332 Opcode == ISD::INTRINSIC_VOID) { 4333 unsigned NumBits = 4334 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4335 if (NumBits > 1) 4336 FirstAnswer = std::max(FirstAnswer, NumBits); 4337 } 4338 4339 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4340 // use this information. 4341 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4342 return std::max(FirstAnswer, Known.countMinSignBits()); 4343 } 4344 4345 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4346 unsigned Depth) const { 4347 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4348 return Op.getScalarValueSizeInBits() - SignBits + 1; 4349 } 4350 4351 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4352 const APInt &DemandedElts, 4353 unsigned Depth) const { 4354 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4355 return Op.getScalarValueSizeInBits() - SignBits + 1; 4356 } 4357 4358 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4359 unsigned Depth) const { 4360 // Early out for FREEZE. 4361 if (Op.getOpcode() == ISD::FREEZE) 4362 return true; 4363 4364 // TODO: Assume we don't know anything for now. 4365 EVT VT = Op.getValueType(); 4366 if (VT.isScalableVector()) 4367 return false; 4368 4369 APInt DemandedElts = VT.isVector() 4370 ? APInt::getAllOnes(VT.getVectorNumElements()) 4371 : APInt(1, 1); 4372 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4373 } 4374 4375 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4376 const APInt &DemandedElts, 4377 bool PoisonOnly, 4378 unsigned Depth) const { 4379 unsigned Opcode = Op.getOpcode(); 4380 4381 // Early out for FREEZE. 4382 if (Opcode == ISD::FREEZE) 4383 return true; 4384 4385 if (Depth >= MaxRecursionDepth) 4386 return false; // Limit search depth. 4387 4388 if (isIntOrFPConstant(Op)) 4389 return true; 4390 4391 switch (Opcode) { 4392 case ISD::UNDEF: 4393 return PoisonOnly; 4394 4395 case ISD::BUILD_VECTOR: 4396 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4397 // this shouldn't affect the result. 4398 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4399 if (!DemandedElts[i]) 4400 continue; 4401 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4402 Depth + 1)) 4403 return false; 4404 } 4405 return true; 4406 4407 // TODO: Search for noundef attributes from library functions. 4408 4409 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4410 4411 default: 4412 // Allow the target to implement this method for its nodes. 4413 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4414 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4415 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4416 Op, DemandedElts, *this, PoisonOnly, Depth); 4417 break; 4418 } 4419 4420 return false; 4421 } 4422 4423 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4424 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4425 !isa<ConstantSDNode>(Op.getOperand(1))) 4426 return false; 4427 4428 if (Op.getOpcode() == ISD::OR && 4429 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4430 return false; 4431 4432 return true; 4433 } 4434 4435 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4436 // If we're told that NaNs won't happen, assume they won't. 4437 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4438 return true; 4439 4440 if (Depth >= MaxRecursionDepth) 4441 return false; // Limit search depth. 4442 4443 // TODO: Handle vectors. 4444 // If the value is a constant, we can obviously see if it is a NaN or not. 4445 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4446 return !C->getValueAPF().isNaN() || 4447 (SNaN && !C->getValueAPF().isSignaling()); 4448 } 4449 4450 unsigned Opcode = Op.getOpcode(); 4451 switch (Opcode) { 4452 case ISD::FADD: 4453 case ISD::FSUB: 4454 case ISD::FMUL: 4455 case ISD::FDIV: 4456 case ISD::FREM: 4457 case ISD::FSIN: 4458 case ISD::FCOS: { 4459 if (SNaN) 4460 return true; 4461 // TODO: Need isKnownNeverInfinity 4462 return false; 4463 } 4464 case ISD::FCANONICALIZE: 4465 case ISD::FEXP: 4466 case ISD::FEXP2: 4467 case ISD::FTRUNC: 4468 case ISD::FFLOOR: 4469 case ISD::FCEIL: 4470 case ISD::FROUND: 4471 case ISD::FROUNDEVEN: 4472 case ISD::FRINT: 4473 case ISD::FNEARBYINT: { 4474 if (SNaN) 4475 return true; 4476 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4477 } 4478 case ISD::FABS: 4479 case ISD::FNEG: 4480 case ISD::FCOPYSIGN: { 4481 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4482 } 4483 case ISD::SELECT: 4484 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4485 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4486 case ISD::FP_EXTEND: 4487 case ISD::FP_ROUND: { 4488 if (SNaN) 4489 return true; 4490 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4491 } 4492 case ISD::SINT_TO_FP: 4493 case ISD::UINT_TO_FP: 4494 return true; 4495 case ISD::FMA: 4496 case ISD::FMAD: { 4497 if (SNaN) 4498 return true; 4499 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4500 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4501 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4502 } 4503 case ISD::FSQRT: // Need is known positive 4504 case ISD::FLOG: 4505 case ISD::FLOG2: 4506 case ISD::FLOG10: 4507 case ISD::FPOWI: 4508 case ISD::FPOW: { 4509 if (SNaN) 4510 return true; 4511 // TODO: Refine on operand 4512 return false; 4513 } 4514 case ISD::FMINNUM: 4515 case ISD::FMAXNUM: { 4516 // Only one needs to be known not-nan, since it will be returned if the 4517 // other ends up being one. 4518 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4519 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4520 } 4521 case ISD::FMINNUM_IEEE: 4522 case ISD::FMAXNUM_IEEE: { 4523 if (SNaN) 4524 return true; 4525 // This can return a NaN if either operand is an sNaN, or if both operands 4526 // are NaN. 4527 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4528 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4529 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4530 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4531 } 4532 case ISD::FMINIMUM: 4533 case ISD::FMAXIMUM: { 4534 // TODO: Does this quiet or return the origina NaN as-is? 4535 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4536 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4537 } 4538 case ISD::EXTRACT_VECTOR_ELT: { 4539 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4540 } 4541 default: 4542 if (Opcode >= ISD::BUILTIN_OP_END || 4543 Opcode == ISD::INTRINSIC_WO_CHAIN || 4544 Opcode == ISD::INTRINSIC_W_CHAIN || 4545 Opcode == ISD::INTRINSIC_VOID) { 4546 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4547 } 4548 4549 return false; 4550 } 4551 } 4552 4553 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4554 assert(Op.getValueType().isFloatingPoint() && 4555 "Floating point type expected"); 4556 4557 // If the value is a constant, we can obviously see if it is a zero or not. 4558 // TODO: Add BuildVector support. 4559 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4560 return !C->isZero(); 4561 return false; 4562 } 4563 4564 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4565 assert(!Op.getValueType().isFloatingPoint() && 4566 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4567 4568 // If the value is a constant, we can obviously see if it is a zero or not. 4569 if (ISD::matchUnaryPredicate(Op, 4570 [](ConstantSDNode *C) { return !C->isZero(); })) 4571 return true; 4572 4573 // TODO: Recognize more cases here. 4574 switch (Op.getOpcode()) { 4575 default: break; 4576 case ISD::OR: 4577 if (isKnownNeverZero(Op.getOperand(1)) || 4578 isKnownNeverZero(Op.getOperand(0))) 4579 return true; 4580 break; 4581 } 4582 4583 return false; 4584 } 4585 4586 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4587 // Check the obvious case. 4588 if (A == B) return true; 4589 4590 // For for negative and positive zero. 4591 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4592 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4593 if (CA->isZero() && CB->isZero()) return true; 4594 4595 // Otherwise they may not be equal. 4596 return false; 4597 } 4598 4599 // FIXME: unify with llvm::haveNoCommonBitsSet. 4600 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4601 assert(A.getValueType() == B.getValueType() && 4602 "Values must have the same type"); 4603 // Match masked merge pattern (X & ~M) op (Y & M) 4604 if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) { 4605 auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) { 4606 if (isBitwiseNot(NotM, true)) { 4607 SDValue NotOperand = NotM->getOperand(0); 4608 return NotOperand == And->getOperand(0) || 4609 NotOperand == And->getOperand(1); 4610 } 4611 return false; 4612 }; 4613 if (MatchNoCommonBitsPattern(A->getOperand(0), B) || 4614 MatchNoCommonBitsPattern(A->getOperand(1), B) || 4615 MatchNoCommonBitsPattern(B->getOperand(0), A) || 4616 MatchNoCommonBitsPattern(B->getOperand(1), A)) 4617 return true; 4618 } 4619 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4620 computeKnownBits(B)); 4621 } 4622 4623 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4624 SelectionDAG &DAG) { 4625 if (cast<ConstantSDNode>(Step)->isZero()) 4626 return DAG.getConstant(0, DL, VT); 4627 4628 return SDValue(); 4629 } 4630 4631 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4632 ArrayRef<SDValue> Ops, 4633 SelectionDAG &DAG) { 4634 int NumOps = Ops.size(); 4635 assert(NumOps != 0 && "Can't build an empty vector!"); 4636 assert(!VT.isScalableVector() && 4637 "BUILD_VECTOR cannot be used with scalable types"); 4638 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4639 "Incorrect element count in BUILD_VECTOR!"); 4640 4641 // BUILD_VECTOR of UNDEFs is UNDEF. 4642 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4643 return DAG.getUNDEF(VT); 4644 4645 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4646 SDValue IdentitySrc; 4647 bool IsIdentity = true; 4648 for (int i = 0; i != NumOps; ++i) { 4649 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4650 Ops[i].getOperand(0).getValueType() != VT || 4651 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4652 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4653 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4654 IsIdentity = false; 4655 break; 4656 } 4657 IdentitySrc = Ops[i].getOperand(0); 4658 } 4659 if (IsIdentity) 4660 return IdentitySrc; 4661 4662 return SDValue(); 4663 } 4664 4665 /// Try to simplify vector concatenation to an input value, undef, or build 4666 /// vector. 4667 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4668 ArrayRef<SDValue> Ops, 4669 SelectionDAG &DAG) { 4670 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4671 assert(llvm::all_of(Ops, 4672 [Ops](SDValue Op) { 4673 return Ops[0].getValueType() == Op.getValueType(); 4674 }) && 4675 "Concatenation of vectors with inconsistent value types!"); 4676 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4677 VT.getVectorElementCount() && 4678 "Incorrect element count in vector concatenation!"); 4679 4680 if (Ops.size() == 1) 4681 return Ops[0]; 4682 4683 // Concat of UNDEFs is UNDEF. 4684 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4685 return DAG.getUNDEF(VT); 4686 4687 // Scan the operands and look for extract operations from a single source 4688 // that correspond to insertion at the same location via this concatenation: 4689 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4690 SDValue IdentitySrc; 4691 bool IsIdentity = true; 4692 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4693 SDValue Op = Ops[i]; 4694 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4695 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4696 Op.getOperand(0).getValueType() != VT || 4697 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4698 Op.getConstantOperandVal(1) != IdentityIndex) { 4699 IsIdentity = false; 4700 break; 4701 } 4702 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4703 "Unexpected identity source vector for concat of extracts"); 4704 IdentitySrc = Op.getOperand(0); 4705 } 4706 if (IsIdentity) { 4707 assert(IdentitySrc && "Failed to set source vector of extracts"); 4708 return IdentitySrc; 4709 } 4710 4711 // The code below this point is only designed to work for fixed width 4712 // vectors, so we bail out for now. 4713 if (VT.isScalableVector()) 4714 return SDValue(); 4715 4716 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4717 // simplified to one big BUILD_VECTOR. 4718 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4719 EVT SVT = VT.getScalarType(); 4720 SmallVector<SDValue, 16> Elts; 4721 for (SDValue Op : Ops) { 4722 EVT OpVT = Op.getValueType(); 4723 if (Op.isUndef()) 4724 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4725 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4726 Elts.append(Op->op_begin(), Op->op_end()); 4727 else 4728 return SDValue(); 4729 } 4730 4731 // BUILD_VECTOR requires all inputs to be of the same type, find the 4732 // maximum type and extend them all. 4733 for (SDValue Op : Elts) 4734 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4735 4736 if (SVT.bitsGT(VT.getScalarType())) { 4737 for (SDValue &Op : Elts) { 4738 if (Op.isUndef()) 4739 Op = DAG.getUNDEF(SVT); 4740 else 4741 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4742 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4743 : DAG.getSExtOrTrunc(Op, DL, SVT); 4744 } 4745 } 4746 4747 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4748 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4749 return V; 4750 } 4751 4752 /// Gets or creates the specified node. 4753 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4754 FoldingSetNodeID ID; 4755 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4756 void *IP = nullptr; 4757 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4758 return SDValue(E, 0); 4759 4760 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4761 getVTList(VT)); 4762 CSEMap.InsertNode(N, IP); 4763 4764 InsertNode(N); 4765 SDValue V = SDValue(N, 0); 4766 NewSDValueDbgMsg(V, "Creating new node: ", this); 4767 return V; 4768 } 4769 4770 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4771 SDValue Operand) { 4772 SDNodeFlags Flags; 4773 if (Inserter) 4774 Flags = Inserter->getFlags(); 4775 return getNode(Opcode, DL, VT, Operand, Flags); 4776 } 4777 4778 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4779 SDValue Operand, const SDNodeFlags Flags) { 4780 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4781 "Operand is DELETED_NODE!"); 4782 // Constant fold unary operations with an integer constant operand. Even 4783 // opaque constant will be folded, because the folding of unary operations 4784 // doesn't create new constants with different values. Nevertheless, the 4785 // opaque flag is preserved during folding to prevent future folding with 4786 // other constants. 4787 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4788 const APInt &Val = C->getAPIntValue(); 4789 switch (Opcode) { 4790 default: break; 4791 case ISD::SIGN_EXTEND: 4792 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4793 C->isTargetOpcode(), C->isOpaque()); 4794 case ISD::TRUNCATE: 4795 if (C->isOpaque()) 4796 break; 4797 LLVM_FALLTHROUGH; 4798 case ISD::ZERO_EXTEND: 4799 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4800 C->isTargetOpcode(), C->isOpaque()); 4801 case ISD::ANY_EXTEND: 4802 // Some targets like RISCV prefer to sign extend some types. 4803 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4804 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4805 C->isTargetOpcode(), C->isOpaque()); 4806 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4807 C->isTargetOpcode(), C->isOpaque()); 4808 case ISD::UINT_TO_FP: 4809 case ISD::SINT_TO_FP: { 4810 APFloat apf(EVTToAPFloatSemantics(VT), 4811 APInt::getZero(VT.getSizeInBits())); 4812 (void)apf.convertFromAPInt(Val, 4813 Opcode==ISD::SINT_TO_FP, 4814 APFloat::rmNearestTiesToEven); 4815 return getConstantFP(apf, DL, VT); 4816 } 4817 case ISD::BITCAST: 4818 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4819 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4820 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4821 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4822 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4823 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4824 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4825 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4826 break; 4827 case ISD::ABS: 4828 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4829 C->isOpaque()); 4830 case ISD::BITREVERSE: 4831 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4832 C->isOpaque()); 4833 case ISD::BSWAP: 4834 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4835 C->isOpaque()); 4836 case ISD::CTPOP: 4837 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4838 C->isOpaque()); 4839 case ISD::CTLZ: 4840 case ISD::CTLZ_ZERO_UNDEF: 4841 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4842 C->isOpaque()); 4843 case ISD::CTTZ: 4844 case ISD::CTTZ_ZERO_UNDEF: 4845 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4846 C->isOpaque()); 4847 case ISD::FP16_TO_FP: { 4848 bool Ignored; 4849 APFloat FPV(APFloat::IEEEhalf(), 4850 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4851 4852 // This can return overflow, underflow, or inexact; we don't care. 4853 // FIXME need to be more flexible about rounding mode. 4854 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4855 APFloat::rmNearestTiesToEven, &Ignored); 4856 return getConstantFP(FPV, DL, VT); 4857 } 4858 case ISD::STEP_VECTOR: { 4859 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4860 return V; 4861 break; 4862 } 4863 } 4864 } 4865 4866 // Constant fold unary operations with a floating point constant operand. 4867 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4868 APFloat V = C->getValueAPF(); // make copy 4869 switch (Opcode) { 4870 case ISD::FNEG: 4871 V.changeSign(); 4872 return getConstantFP(V, DL, VT); 4873 case ISD::FABS: 4874 V.clearSign(); 4875 return getConstantFP(V, DL, VT); 4876 case ISD::FCEIL: { 4877 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4878 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4879 return getConstantFP(V, DL, VT); 4880 break; 4881 } 4882 case ISD::FTRUNC: { 4883 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4884 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4885 return getConstantFP(V, DL, VT); 4886 break; 4887 } 4888 case ISD::FFLOOR: { 4889 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4890 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4891 return getConstantFP(V, DL, VT); 4892 break; 4893 } 4894 case ISD::FP_EXTEND: { 4895 bool ignored; 4896 // This can return overflow, underflow, or inexact; we don't care. 4897 // FIXME need to be more flexible about rounding mode. 4898 (void)V.convert(EVTToAPFloatSemantics(VT), 4899 APFloat::rmNearestTiesToEven, &ignored); 4900 return getConstantFP(V, DL, VT); 4901 } 4902 case ISD::FP_TO_SINT: 4903 case ISD::FP_TO_UINT: { 4904 bool ignored; 4905 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4906 // FIXME need to be more flexible about rounding mode. 4907 APFloat::opStatus s = 4908 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4909 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4910 break; 4911 return getConstant(IntVal, DL, VT); 4912 } 4913 case ISD::BITCAST: 4914 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4915 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4916 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4917 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4918 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4919 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4920 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4921 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4922 break; 4923 case ISD::FP_TO_FP16: { 4924 bool Ignored; 4925 // This can return overflow, underflow, or inexact; we don't care. 4926 // FIXME need to be more flexible about rounding mode. 4927 (void)V.convert(APFloat::IEEEhalf(), 4928 APFloat::rmNearestTiesToEven, &Ignored); 4929 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4930 } 4931 } 4932 } 4933 4934 // Constant fold unary operations with a vector integer or float operand. 4935 switch (Opcode) { 4936 default: 4937 // FIXME: Entirely reasonable to perform folding of other unary 4938 // operations here as the need arises. 4939 break; 4940 case ISD::FNEG: 4941 case ISD::FABS: 4942 case ISD::FCEIL: 4943 case ISD::FTRUNC: 4944 case ISD::FFLOOR: 4945 case ISD::FP_EXTEND: 4946 case ISD::FP_TO_SINT: 4947 case ISD::FP_TO_UINT: 4948 case ISD::TRUNCATE: 4949 case ISD::ANY_EXTEND: 4950 case ISD::ZERO_EXTEND: 4951 case ISD::SIGN_EXTEND: 4952 case ISD::UINT_TO_FP: 4953 case ISD::SINT_TO_FP: 4954 case ISD::ABS: 4955 case ISD::BITREVERSE: 4956 case ISD::BSWAP: 4957 case ISD::CTLZ: 4958 case ISD::CTLZ_ZERO_UNDEF: 4959 case ISD::CTTZ: 4960 case ISD::CTTZ_ZERO_UNDEF: 4961 case ISD::CTPOP: { 4962 SDValue Ops = {Operand}; 4963 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 4964 return Fold; 4965 } 4966 } 4967 4968 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4969 switch (Opcode) { 4970 case ISD::STEP_VECTOR: 4971 assert(VT.isScalableVector() && 4972 "STEP_VECTOR can only be used with scalable types"); 4973 assert(OpOpcode == ISD::TargetConstant && 4974 VT.getVectorElementType() == Operand.getValueType() && 4975 "Unexpected step operand"); 4976 break; 4977 case ISD::FREEZE: 4978 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4979 break; 4980 case ISD::TokenFactor: 4981 case ISD::MERGE_VALUES: 4982 case ISD::CONCAT_VECTORS: 4983 return Operand; // Factor, merge or concat of one node? No need. 4984 case ISD::BUILD_VECTOR: { 4985 // Attempt to simplify BUILD_VECTOR. 4986 SDValue Ops[] = {Operand}; 4987 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4988 return V; 4989 break; 4990 } 4991 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4992 case ISD::FP_EXTEND: 4993 assert(VT.isFloatingPoint() && 4994 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4995 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4996 assert((!VT.isVector() || 4997 VT.getVectorElementCount() == 4998 Operand.getValueType().getVectorElementCount()) && 4999 "Vector element count mismatch!"); 5000 assert(Operand.getValueType().bitsLT(VT) && 5001 "Invalid fpext node, dst < src!"); 5002 if (Operand.isUndef()) 5003 return getUNDEF(VT); 5004 break; 5005 case ISD::FP_TO_SINT: 5006 case ISD::FP_TO_UINT: 5007 if (Operand.isUndef()) 5008 return getUNDEF(VT); 5009 break; 5010 case ISD::SINT_TO_FP: 5011 case ISD::UINT_TO_FP: 5012 // [us]itofp(undef) = 0, because the result value is bounded. 5013 if (Operand.isUndef()) 5014 return getConstantFP(0.0, DL, VT); 5015 break; 5016 case ISD::SIGN_EXTEND: 5017 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5018 "Invalid SIGN_EXTEND!"); 5019 assert(VT.isVector() == Operand.getValueType().isVector() && 5020 "SIGN_EXTEND result type type should be vector iff the operand " 5021 "type is vector!"); 5022 if (Operand.getValueType() == VT) return Operand; // noop extension 5023 assert((!VT.isVector() || 5024 VT.getVectorElementCount() == 5025 Operand.getValueType().getVectorElementCount()) && 5026 "Vector element count mismatch!"); 5027 assert(Operand.getValueType().bitsLT(VT) && 5028 "Invalid sext node, dst < src!"); 5029 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5030 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5031 if (OpOpcode == ISD::UNDEF) 5032 // sext(undef) = 0, because the top bits will all be the same. 5033 return getConstant(0, DL, VT); 5034 break; 5035 case ISD::ZERO_EXTEND: 5036 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5037 "Invalid ZERO_EXTEND!"); 5038 assert(VT.isVector() == Operand.getValueType().isVector() && 5039 "ZERO_EXTEND result type type should be vector iff the operand " 5040 "type is vector!"); 5041 if (Operand.getValueType() == VT) return Operand; // noop extension 5042 assert((!VT.isVector() || 5043 VT.getVectorElementCount() == 5044 Operand.getValueType().getVectorElementCount()) && 5045 "Vector element count mismatch!"); 5046 assert(Operand.getValueType().bitsLT(VT) && 5047 "Invalid zext node, dst < src!"); 5048 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5049 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5050 if (OpOpcode == ISD::UNDEF) 5051 // zext(undef) = 0, because the top bits will be zero. 5052 return getConstant(0, DL, VT); 5053 break; 5054 case ISD::ANY_EXTEND: 5055 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5056 "Invalid ANY_EXTEND!"); 5057 assert(VT.isVector() == Operand.getValueType().isVector() && 5058 "ANY_EXTEND result type type should be vector iff the operand " 5059 "type is vector!"); 5060 if (Operand.getValueType() == VT) return Operand; // noop extension 5061 assert((!VT.isVector() || 5062 VT.getVectorElementCount() == 5063 Operand.getValueType().getVectorElementCount()) && 5064 "Vector element count mismatch!"); 5065 assert(Operand.getValueType().bitsLT(VT) && 5066 "Invalid anyext node, dst < src!"); 5067 5068 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5069 OpOpcode == ISD::ANY_EXTEND) 5070 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5071 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5072 if (OpOpcode == ISD::UNDEF) 5073 return getUNDEF(VT); 5074 5075 // (ext (trunc x)) -> x 5076 if (OpOpcode == ISD::TRUNCATE) { 5077 SDValue OpOp = Operand.getOperand(0); 5078 if (OpOp.getValueType() == VT) { 5079 transferDbgValues(Operand, OpOp); 5080 return OpOp; 5081 } 5082 } 5083 break; 5084 case ISD::TRUNCATE: 5085 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5086 "Invalid TRUNCATE!"); 5087 assert(VT.isVector() == Operand.getValueType().isVector() && 5088 "TRUNCATE result type type should be vector iff the operand " 5089 "type is vector!"); 5090 if (Operand.getValueType() == VT) return Operand; // noop truncate 5091 assert((!VT.isVector() || 5092 VT.getVectorElementCount() == 5093 Operand.getValueType().getVectorElementCount()) && 5094 "Vector element count mismatch!"); 5095 assert(Operand.getValueType().bitsGT(VT) && 5096 "Invalid truncate node, src < dst!"); 5097 if (OpOpcode == ISD::TRUNCATE) 5098 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5099 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5100 OpOpcode == ISD::ANY_EXTEND) { 5101 // If the source is smaller than the dest, we still need an extend. 5102 if (Operand.getOperand(0).getValueType().getScalarType() 5103 .bitsLT(VT.getScalarType())) 5104 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5105 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5106 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5107 return Operand.getOperand(0); 5108 } 5109 if (OpOpcode == ISD::UNDEF) 5110 return getUNDEF(VT); 5111 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5112 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5113 break; 5114 case ISD::ANY_EXTEND_VECTOR_INREG: 5115 case ISD::ZERO_EXTEND_VECTOR_INREG: 5116 case ISD::SIGN_EXTEND_VECTOR_INREG: 5117 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5118 assert(Operand.getValueType().bitsLE(VT) && 5119 "The input must be the same size or smaller than the result."); 5120 assert(VT.getVectorMinNumElements() < 5121 Operand.getValueType().getVectorMinNumElements() && 5122 "The destination vector type must have fewer lanes than the input."); 5123 break; 5124 case ISD::ABS: 5125 assert(VT.isInteger() && VT == Operand.getValueType() && 5126 "Invalid ABS!"); 5127 if (OpOpcode == ISD::UNDEF) 5128 return getUNDEF(VT); 5129 break; 5130 case ISD::BSWAP: 5131 assert(VT.isInteger() && VT == Operand.getValueType() && 5132 "Invalid BSWAP!"); 5133 assert((VT.getScalarSizeInBits() % 16 == 0) && 5134 "BSWAP types must be a multiple of 16 bits!"); 5135 if (OpOpcode == ISD::UNDEF) 5136 return getUNDEF(VT); 5137 // bswap(bswap(X)) -> X. 5138 if (OpOpcode == ISD::BSWAP) 5139 return Operand.getOperand(0); 5140 break; 5141 case ISD::BITREVERSE: 5142 assert(VT.isInteger() && VT == Operand.getValueType() && 5143 "Invalid BITREVERSE!"); 5144 if (OpOpcode == ISD::UNDEF) 5145 return getUNDEF(VT); 5146 break; 5147 case ISD::BITCAST: 5148 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5149 "Cannot BITCAST between types of different sizes!"); 5150 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5151 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5152 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5153 if (OpOpcode == ISD::UNDEF) 5154 return getUNDEF(VT); 5155 break; 5156 case ISD::SCALAR_TO_VECTOR: 5157 assert(VT.isVector() && !Operand.getValueType().isVector() && 5158 (VT.getVectorElementType() == Operand.getValueType() || 5159 (VT.getVectorElementType().isInteger() && 5160 Operand.getValueType().isInteger() && 5161 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5162 "Illegal SCALAR_TO_VECTOR node!"); 5163 if (OpOpcode == ISD::UNDEF) 5164 return getUNDEF(VT); 5165 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5166 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5167 isa<ConstantSDNode>(Operand.getOperand(1)) && 5168 Operand.getConstantOperandVal(1) == 0 && 5169 Operand.getOperand(0).getValueType() == VT) 5170 return Operand.getOperand(0); 5171 break; 5172 case ISD::FNEG: 5173 // Negation of an unknown bag of bits is still completely undefined. 5174 if (OpOpcode == ISD::UNDEF) 5175 return getUNDEF(VT); 5176 5177 if (OpOpcode == ISD::FNEG) // --X -> X 5178 return Operand.getOperand(0); 5179 break; 5180 case ISD::FABS: 5181 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5182 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5183 break; 5184 case ISD::VSCALE: 5185 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5186 break; 5187 case ISD::CTPOP: 5188 if (Operand.getValueType().getScalarType() == MVT::i1) 5189 return Operand; 5190 break; 5191 case ISD::CTLZ: 5192 case ISD::CTTZ: 5193 if (Operand.getValueType().getScalarType() == MVT::i1) 5194 return getNOT(DL, Operand, Operand.getValueType()); 5195 break; 5196 case ISD::VECREDUCE_SMIN: 5197 case ISD::VECREDUCE_UMAX: 5198 if (Operand.getValueType().getScalarType() == MVT::i1) 5199 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5200 break; 5201 case ISD::VECREDUCE_SMAX: 5202 case ISD::VECREDUCE_UMIN: 5203 if (Operand.getValueType().getScalarType() == MVT::i1) 5204 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5205 break; 5206 } 5207 5208 SDNode *N; 5209 SDVTList VTs = getVTList(VT); 5210 SDValue Ops[] = {Operand}; 5211 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5212 FoldingSetNodeID ID; 5213 AddNodeIDNode(ID, Opcode, VTs, Ops); 5214 void *IP = nullptr; 5215 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5216 E->intersectFlagsWith(Flags); 5217 return SDValue(E, 0); 5218 } 5219 5220 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5221 N->setFlags(Flags); 5222 createOperands(N, Ops); 5223 CSEMap.InsertNode(N, IP); 5224 } else { 5225 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5226 createOperands(N, Ops); 5227 } 5228 5229 InsertNode(N); 5230 SDValue V = SDValue(N, 0); 5231 NewSDValueDbgMsg(V, "Creating new node: ", this); 5232 return V; 5233 } 5234 5235 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5236 const APInt &C2) { 5237 switch (Opcode) { 5238 case ISD::ADD: return C1 + C2; 5239 case ISD::SUB: return C1 - C2; 5240 case ISD::MUL: return C1 * C2; 5241 case ISD::AND: return C1 & C2; 5242 case ISD::OR: return C1 | C2; 5243 case ISD::XOR: return C1 ^ C2; 5244 case ISD::SHL: return C1 << C2; 5245 case ISD::SRL: return C1.lshr(C2); 5246 case ISD::SRA: return C1.ashr(C2); 5247 case ISD::ROTL: return C1.rotl(C2); 5248 case ISD::ROTR: return C1.rotr(C2); 5249 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5250 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5251 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5252 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5253 case ISD::SADDSAT: return C1.sadd_sat(C2); 5254 case ISD::UADDSAT: return C1.uadd_sat(C2); 5255 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5256 case ISD::USUBSAT: return C1.usub_sat(C2); 5257 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5258 case ISD::USHLSAT: return C1.ushl_sat(C2); 5259 case ISD::UDIV: 5260 if (!C2.getBoolValue()) 5261 break; 5262 return C1.udiv(C2); 5263 case ISD::UREM: 5264 if (!C2.getBoolValue()) 5265 break; 5266 return C1.urem(C2); 5267 case ISD::SDIV: 5268 if (!C2.getBoolValue()) 5269 break; 5270 return C1.sdiv(C2); 5271 case ISD::SREM: 5272 if (!C2.getBoolValue()) 5273 break; 5274 return C1.srem(C2); 5275 case ISD::MULHS: { 5276 unsigned FullWidth = C1.getBitWidth() * 2; 5277 APInt C1Ext = C1.sext(FullWidth); 5278 APInt C2Ext = C2.sext(FullWidth); 5279 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5280 } 5281 case ISD::MULHU: { 5282 unsigned FullWidth = C1.getBitWidth() * 2; 5283 APInt C1Ext = C1.zext(FullWidth); 5284 APInt C2Ext = C2.zext(FullWidth); 5285 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5286 } 5287 case ISD::AVGFLOORS: { 5288 unsigned FullWidth = C1.getBitWidth() + 1; 5289 APInt C1Ext = C1.sext(FullWidth); 5290 APInt C2Ext = C2.sext(FullWidth); 5291 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5292 } 5293 case ISD::AVGFLOORU: { 5294 unsigned FullWidth = C1.getBitWidth() + 1; 5295 APInt C1Ext = C1.zext(FullWidth); 5296 APInt C2Ext = C2.zext(FullWidth); 5297 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5298 } 5299 case ISD::AVGCEILS: { 5300 unsigned FullWidth = C1.getBitWidth() + 1; 5301 APInt C1Ext = C1.sext(FullWidth); 5302 APInt C2Ext = C2.sext(FullWidth); 5303 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5304 } 5305 case ISD::AVGCEILU: { 5306 unsigned FullWidth = C1.getBitWidth() + 1; 5307 APInt C1Ext = C1.zext(FullWidth); 5308 APInt C2Ext = C2.zext(FullWidth); 5309 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5310 } 5311 } 5312 return llvm::None; 5313 } 5314 5315 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5316 const GlobalAddressSDNode *GA, 5317 const SDNode *N2) { 5318 if (GA->getOpcode() != ISD::GlobalAddress) 5319 return SDValue(); 5320 if (!TLI->isOffsetFoldingLegal(GA)) 5321 return SDValue(); 5322 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5323 if (!C2) 5324 return SDValue(); 5325 int64_t Offset = C2->getSExtValue(); 5326 switch (Opcode) { 5327 case ISD::ADD: break; 5328 case ISD::SUB: Offset = -uint64_t(Offset); break; 5329 default: return SDValue(); 5330 } 5331 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5332 GA->getOffset() + uint64_t(Offset)); 5333 } 5334 5335 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5336 switch (Opcode) { 5337 case ISD::SDIV: 5338 case ISD::UDIV: 5339 case ISD::SREM: 5340 case ISD::UREM: { 5341 // If a divisor is zero/undef or any element of a divisor vector is 5342 // zero/undef, the whole op is undef. 5343 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5344 SDValue Divisor = Ops[1]; 5345 if (Divisor.isUndef() || isNullConstant(Divisor)) 5346 return true; 5347 5348 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5349 llvm::any_of(Divisor->op_values(), 5350 [](SDValue V) { return V.isUndef() || 5351 isNullConstant(V); }); 5352 // TODO: Handle signed overflow. 5353 } 5354 // TODO: Handle oversized shifts. 5355 default: 5356 return false; 5357 } 5358 } 5359 5360 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5361 EVT VT, ArrayRef<SDValue> Ops) { 5362 // If the opcode is a target-specific ISD node, there's nothing we can 5363 // do here and the operand rules may not line up with the below, so 5364 // bail early. 5365 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5366 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5367 // foldCONCAT_VECTORS in getNode before this is called. 5368 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5369 return SDValue(); 5370 5371 unsigned NumOps = Ops.size(); 5372 if (NumOps == 0) 5373 return SDValue(); 5374 5375 if (isUndef(Opcode, Ops)) 5376 return getUNDEF(VT); 5377 5378 // Handle binops special cases. 5379 if (NumOps == 2) { 5380 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5381 return CFP; 5382 5383 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5384 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5385 if (C1->isOpaque() || C2->isOpaque()) 5386 return SDValue(); 5387 5388 Optional<APInt> FoldAttempt = 5389 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5390 if (!FoldAttempt) 5391 return SDValue(); 5392 5393 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5394 assert((!Folded || !VT.isVector()) && 5395 "Can't fold vectors ops with scalar operands"); 5396 return Folded; 5397 } 5398 } 5399 5400 // fold (add Sym, c) -> Sym+c 5401 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5402 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5403 if (TLI->isCommutativeBinOp(Opcode)) 5404 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5405 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5406 } 5407 5408 // This is for vector folding only from here on. 5409 if (!VT.isVector()) 5410 return SDValue(); 5411 5412 ElementCount NumElts = VT.getVectorElementCount(); 5413 5414 // See if we can fold through bitcasted integer ops. 5415 // TODO: Can we handle undef elements? 5416 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5417 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5418 Ops[0].getOpcode() == ISD::BITCAST && 5419 Ops[1].getOpcode() == ISD::BITCAST) { 5420 SDValue N1 = peekThroughBitcasts(Ops[0]); 5421 SDValue N2 = peekThroughBitcasts(Ops[1]); 5422 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5423 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5424 EVT BVVT = N1.getValueType(); 5425 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5426 bool IsLE = getDataLayout().isLittleEndian(); 5427 unsigned EltBits = VT.getScalarSizeInBits(); 5428 SmallVector<APInt> RawBits1, RawBits2; 5429 BitVector UndefElts1, UndefElts2; 5430 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5431 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5432 UndefElts1.none() && UndefElts2.none()) { 5433 SmallVector<APInt> RawBits; 5434 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5435 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5436 if (!Fold) 5437 break; 5438 RawBits.push_back(Fold.getValue()); 5439 } 5440 if (RawBits.size() == NumElts.getFixedValue()) { 5441 // We have constant folded, but we need to cast this again back to 5442 // the original (possibly legalized) type. 5443 SmallVector<APInt> DstBits; 5444 BitVector DstUndefs; 5445 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5446 DstBits, RawBits, DstUndefs, 5447 BitVector(RawBits.size(), false)); 5448 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5449 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5450 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5451 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5452 if (DstUndefs[I]) 5453 continue; 5454 Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT); 5455 } 5456 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5457 } 5458 } 5459 } 5460 } 5461 5462 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5463 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5464 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5465 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5466 APInt RHSVal; 5467 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5468 APInt NewStep = Opcode == ISD::MUL 5469 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5470 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5471 return getStepVector(DL, VT, NewStep); 5472 } 5473 } 5474 5475 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5476 return !Op.getValueType().isVector() || 5477 Op.getValueType().getVectorElementCount() == NumElts; 5478 }; 5479 5480 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5481 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5482 Op.getOpcode() == ISD::BUILD_VECTOR || 5483 Op.getOpcode() == ISD::SPLAT_VECTOR; 5484 }; 5485 5486 // All operands must be vector types with the same number of elements as 5487 // the result type and must be either UNDEF or a build/splat vector 5488 // or UNDEF scalars. 5489 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5490 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5491 return SDValue(); 5492 5493 // If we are comparing vectors, then the result needs to be a i1 boolean 5494 // that is then sign-extended back to the legal result type. 5495 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5496 5497 // Find legal integer scalar type for constant promotion and 5498 // ensure that its scalar size is at least as large as source. 5499 EVT LegalSVT = VT.getScalarType(); 5500 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5501 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5502 if (LegalSVT.bitsLT(VT.getScalarType())) 5503 return SDValue(); 5504 } 5505 5506 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5507 // only have one operand to check. For fixed-length vector types we may have 5508 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5509 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5510 5511 // Constant fold each scalar lane separately. 5512 SmallVector<SDValue, 4> ScalarResults; 5513 for (unsigned I = 0; I != NumVectorElts; I++) { 5514 SmallVector<SDValue, 4> ScalarOps; 5515 for (SDValue Op : Ops) { 5516 EVT InSVT = Op.getValueType().getScalarType(); 5517 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5518 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5519 if (Op.isUndef()) 5520 ScalarOps.push_back(getUNDEF(InSVT)); 5521 else 5522 ScalarOps.push_back(Op); 5523 continue; 5524 } 5525 5526 SDValue ScalarOp = 5527 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5528 EVT ScalarVT = ScalarOp.getValueType(); 5529 5530 // Build vector (integer) scalar operands may need implicit 5531 // truncation - do this before constant folding. 5532 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5533 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5534 5535 ScalarOps.push_back(ScalarOp); 5536 } 5537 5538 // Constant fold the scalar operands. 5539 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5540 5541 // Legalize the (integer) scalar constant if necessary. 5542 if (LegalSVT != SVT) 5543 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5544 5545 // Scalar folding only succeeded if the result is a constant or UNDEF. 5546 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5547 ScalarResult.getOpcode() != ISD::ConstantFP) 5548 return SDValue(); 5549 ScalarResults.push_back(ScalarResult); 5550 } 5551 5552 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5553 : getBuildVector(VT, DL, ScalarResults); 5554 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5555 return V; 5556 } 5557 5558 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5559 EVT VT, SDValue N1, SDValue N2) { 5560 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5561 // should. That will require dealing with a potentially non-default 5562 // rounding mode, checking the "opStatus" return value from the APFloat 5563 // math calculations, and possibly other variations. 5564 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5565 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5566 if (N1CFP && N2CFP) { 5567 APFloat C1 = N1CFP->getValueAPF(); // make copy 5568 const APFloat &C2 = N2CFP->getValueAPF(); 5569 switch (Opcode) { 5570 case ISD::FADD: 5571 C1.add(C2, APFloat::rmNearestTiesToEven); 5572 return getConstantFP(C1, DL, VT); 5573 case ISD::FSUB: 5574 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5575 return getConstantFP(C1, DL, VT); 5576 case ISD::FMUL: 5577 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5578 return getConstantFP(C1, DL, VT); 5579 case ISD::FDIV: 5580 C1.divide(C2, APFloat::rmNearestTiesToEven); 5581 return getConstantFP(C1, DL, VT); 5582 case ISD::FREM: 5583 C1.mod(C2); 5584 return getConstantFP(C1, DL, VT); 5585 case ISD::FCOPYSIGN: 5586 C1.copySign(C2); 5587 return getConstantFP(C1, DL, VT); 5588 case ISD::FMINNUM: 5589 return getConstantFP(minnum(C1, C2), DL, VT); 5590 case ISD::FMAXNUM: 5591 return getConstantFP(maxnum(C1, C2), DL, VT); 5592 case ISD::FMINIMUM: 5593 return getConstantFP(minimum(C1, C2), DL, VT); 5594 case ISD::FMAXIMUM: 5595 return getConstantFP(maximum(C1, C2), DL, VT); 5596 default: break; 5597 } 5598 } 5599 if (N1CFP && Opcode == ISD::FP_ROUND) { 5600 APFloat C1 = N1CFP->getValueAPF(); // make copy 5601 bool Unused; 5602 // This can return overflow, underflow, or inexact; we don't care. 5603 // FIXME need to be more flexible about rounding mode. 5604 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5605 &Unused); 5606 return getConstantFP(C1, DL, VT); 5607 } 5608 5609 switch (Opcode) { 5610 case ISD::FSUB: 5611 // -0.0 - undef --> undef (consistent with "fneg undef") 5612 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5613 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5614 return getUNDEF(VT); 5615 LLVM_FALLTHROUGH; 5616 5617 case ISD::FADD: 5618 case ISD::FMUL: 5619 case ISD::FDIV: 5620 case ISD::FREM: 5621 // If both operands are undef, the result is undef. If 1 operand is undef, 5622 // the result is NaN. This should match the behavior of the IR optimizer. 5623 if (N1.isUndef() && N2.isUndef()) 5624 return getUNDEF(VT); 5625 if (N1.isUndef() || N2.isUndef()) 5626 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5627 } 5628 return SDValue(); 5629 } 5630 5631 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5632 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5633 5634 // There's no need to assert on a byte-aligned pointer. All pointers are at 5635 // least byte aligned. 5636 if (A == Align(1)) 5637 return Val; 5638 5639 FoldingSetNodeID ID; 5640 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5641 ID.AddInteger(A.value()); 5642 5643 void *IP = nullptr; 5644 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5645 return SDValue(E, 0); 5646 5647 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5648 Val.getValueType(), A); 5649 createOperands(N, {Val}); 5650 5651 CSEMap.InsertNode(N, IP); 5652 InsertNode(N); 5653 5654 SDValue V(N, 0); 5655 NewSDValueDbgMsg(V, "Creating new node: ", this); 5656 return V; 5657 } 5658 5659 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5660 SDValue N1, SDValue N2) { 5661 SDNodeFlags Flags; 5662 if (Inserter) 5663 Flags = Inserter->getFlags(); 5664 return getNode(Opcode, DL, VT, N1, N2, Flags); 5665 } 5666 5667 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5668 SDValue &N2) const { 5669 if (!TLI->isCommutativeBinOp(Opcode)) 5670 return; 5671 5672 // Canonicalize: 5673 // binop(const, nonconst) -> binop(nonconst, const) 5674 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5675 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5676 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5677 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5678 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5679 std::swap(N1, N2); 5680 5681 // Canonicalize: 5682 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5683 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5684 N2.getOpcode() == ISD::STEP_VECTOR) 5685 std::swap(N1, N2); 5686 } 5687 5688 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5689 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5690 assert(N1.getOpcode() != ISD::DELETED_NODE && 5691 N2.getOpcode() != ISD::DELETED_NODE && 5692 "Operand is DELETED_NODE!"); 5693 5694 canonicalizeCommutativeBinop(Opcode, N1, N2); 5695 5696 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5697 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5698 5699 // Don't allow undefs in vector splats - we might be returning N2 when folding 5700 // to zero etc. 5701 ConstantSDNode *N2CV = 5702 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5703 5704 switch (Opcode) { 5705 default: break; 5706 case ISD::TokenFactor: 5707 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5708 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5709 // Fold trivial token factors. 5710 if (N1.getOpcode() == ISD::EntryToken) return N2; 5711 if (N2.getOpcode() == ISD::EntryToken) return N1; 5712 if (N1 == N2) return N1; 5713 break; 5714 case ISD::BUILD_VECTOR: { 5715 // Attempt to simplify BUILD_VECTOR. 5716 SDValue Ops[] = {N1, N2}; 5717 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5718 return V; 5719 break; 5720 } 5721 case ISD::CONCAT_VECTORS: { 5722 SDValue Ops[] = {N1, N2}; 5723 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5724 return V; 5725 break; 5726 } 5727 case ISD::AND: 5728 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5729 assert(N1.getValueType() == N2.getValueType() && 5730 N1.getValueType() == VT && "Binary operator types must match!"); 5731 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5732 // worth handling here. 5733 if (N2CV && N2CV->isZero()) 5734 return N2; 5735 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5736 return N1; 5737 break; 5738 case ISD::OR: 5739 case ISD::XOR: 5740 case ISD::ADD: 5741 case ISD::SUB: 5742 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5743 assert(N1.getValueType() == N2.getValueType() && 5744 N1.getValueType() == VT && "Binary operator types must match!"); 5745 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5746 // it's worth handling here. 5747 if (N2CV && N2CV->isZero()) 5748 return N1; 5749 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5750 VT.getVectorElementType() == MVT::i1) 5751 return getNode(ISD::XOR, DL, VT, N1, N2); 5752 break; 5753 case ISD::MUL: 5754 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5755 assert(N1.getValueType() == N2.getValueType() && 5756 N1.getValueType() == VT && "Binary operator types must match!"); 5757 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5758 return getNode(ISD::AND, DL, VT, N1, N2); 5759 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5760 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5761 const APInt &N2CImm = N2C->getAPIntValue(); 5762 return getVScale(DL, VT, MulImm * N2CImm); 5763 } 5764 break; 5765 case ISD::UDIV: 5766 case ISD::UREM: 5767 case ISD::MULHU: 5768 case ISD::MULHS: 5769 case ISD::SDIV: 5770 case ISD::SREM: 5771 case ISD::SADDSAT: 5772 case ISD::SSUBSAT: 5773 case ISD::UADDSAT: 5774 case ISD::USUBSAT: 5775 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5776 assert(N1.getValueType() == N2.getValueType() && 5777 N1.getValueType() == VT && "Binary operator types must match!"); 5778 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5779 // fold (add_sat x, y) -> (or x, y) for bool types. 5780 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5781 return getNode(ISD::OR, DL, VT, N1, N2); 5782 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5783 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5784 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5785 } 5786 break; 5787 case ISD::SMIN: 5788 case ISD::UMAX: 5789 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5790 assert(N1.getValueType() == N2.getValueType() && 5791 N1.getValueType() == VT && "Binary operator types must match!"); 5792 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5793 return getNode(ISD::OR, DL, VT, N1, N2); 5794 break; 5795 case ISD::SMAX: 5796 case ISD::UMIN: 5797 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5798 assert(N1.getValueType() == N2.getValueType() && 5799 N1.getValueType() == VT && "Binary operator types must match!"); 5800 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5801 return getNode(ISD::AND, DL, VT, N1, N2); 5802 break; 5803 case ISD::FADD: 5804 case ISD::FSUB: 5805 case ISD::FMUL: 5806 case ISD::FDIV: 5807 case ISD::FREM: 5808 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5809 assert(N1.getValueType() == N2.getValueType() && 5810 N1.getValueType() == VT && "Binary operator types must match!"); 5811 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5812 return V; 5813 break; 5814 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5815 assert(N1.getValueType() == VT && 5816 N1.getValueType().isFloatingPoint() && 5817 N2.getValueType().isFloatingPoint() && 5818 "Invalid FCOPYSIGN!"); 5819 break; 5820 case ISD::SHL: 5821 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5822 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5823 const APInt &ShiftImm = N2C->getAPIntValue(); 5824 return getVScale(DL, VT, MulImm << ShiftImm); 5825 } 5826 LLVM_FALLTHROUGH; 5827 case ISD::SRA: 5828 case ISD::SRL: 5829 if (SDValue V = simplifyShift(N1, N2)) 5830 return V; 5831 LLVM_FALLTHROUGH; 5832 case ISD::ROTL: 5833 case ISD::ROTR: 5834 assert(VT == N1.getValueType() && 5835 "Shift operators return type must be the same as their first arg"); 5836 assert(VT.isInteger() && N2.getValueType().isInteger() && 5837 "Shifts only work on integers"); 5838 assert((!VT.isVector() || VT == N2.getValueType()) && 5839 "Vector shift amounts must be in the same as their first arg"); 5840 // Verify that the shift amount VT is big enough to hold valid shift 5841 // amounts. This catches things like trying to shift an i1024 value by an 5842 // i8, which is easy to fall into in generic code that uses 5843 // TLI.getShiftAmount(). 5844 assert(N2.getValueType().getScalarSizeInBits() >= 5845 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5846 "Invalid use of small shift amount with oversized value!"); 5847 5848 // Always fold shifts of i1 values so the code generator doesn't need to 5849 // handle them. Since we know the size of the shift has to be less than the 5850 // size of the value, the shift/rotate count is guaranteed to be zero. 5851 if (VT == MVT::i1) 5852 return N1; 5853 if (N2CV && N2CV->isZero()) 5854 return N1; 5855 break; 5856 case ISD::FP_ROUND: 5857 assert(VT.isFloatingPoint() && 5858 N1.getValueType().isFloatingPoint() && 5859 VT.bitsLE(N1.getValueType()) && 5860 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5861 "Invalid FP_ROUND!"); 5862 if (N1.getValueType() == VT) return N1; // noop conversion. 5863 break; 5864 case ISD::AssertSext: 5865 case ISD::AssertZext: { 5866 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5867 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5868 assert(VT.isInteger() && EVT.isInteger() && 5869 "Cannot *_EXTEND_INREG FP types"); 5870 assert(!EVT.isVector() && 5871 "AssertSExt/AssertZExt type should be the vector element type " 5872 "rather than the vector type!"); 5873 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5874 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5875 break; 5876 } 5877 case ISD::SIGN_EXTEND_INREG: { 5878 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5879 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5880 assert(VT.isInteger() && EVT.isInteger() && 5881 "Cannot *_EXTEND_INREG FP types"); 5882 assert(EVT.isVector() == VT.isVector() && 5883 "SIGN_EXTEND_INREG type should be vector iff the operand " 5884 "type is vector!"); 5885 assert((!EVT.isVector() || 5886 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5887 "Vector element counts must match in SIGN_EXTEND_INREG"); 5888 assert(EVT.bitsLE(VT) && "Not extending!"); 5889 if (EVT == VT) return N1; // Not actually extending 5890 5891 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5892 unsigned FromBits = EVT.getScalarSizeInBits(); 5893 Val <<= Val.getBitWidth() - FromBits; 5894 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5895 return getConstant(Val, DL, ConstantVT); 5896 }; 5897 5898 if (N1C) { 5899 const APInt &Val = N1C->getAPIntValue(); 5900 return SignExtendInReg(Val, VT); 5901 } 5902 5903 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5904 SmallVector<SDValue, 8> Ops; 5905 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5906 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5907 SDValue Op = N1.getOperand(i); 5908 if (Op.isUndef()) { 5909 Ops.push_back(getUNDEF(OpVT)); 5910 continue; 5911 } 5912 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5913 APInt Val = C->getAPIntValue(); 5914 Ops.push_back(SignExtendInReg(Val, OpVT)); 5915 } 5916 return getBuildVector(VT, DL, Ops); 5917 } 5918 break; 5919 } 5920 case ISD::FP_TO_SINT_SAT: 5921 case ISD::FP_TO_UINT_SAT: { 5922 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 5923 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 5924 assert(N1.getValueType().isVector() == VT.isVector() && 5925 "FP_TO_*INT_SAT type should be vector iff the operand type is " 5926 "vector!"); 5927 assert((!VT.isVector() || VT.getVectorNumElements() == 5928 N1.getValueType().getVectorNumElements()) && 5929 "Vector element counts must match in FP_TO_*INT_SAT"); 5930 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 5931 "Type to saturate to must be a scalar."); 5932 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 5933 "Not extending!"); 5934 break; 5935 } 5936 case ISD::EXTRACT_VECTOR_ELT: 5937 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5938 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5939 element type of the vector."); 5940 5941 // Extract from an undefined value or using an undefined index is undefined. 5942 if (N1.isUndef() || N2.isUndef()) 5943 return getUNDEF(VT); 5944 5945 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5946 // vectors. For scalable vectors we will provide appropriate support for 5947 // dealing with arbitrary indices. 5948 if (N2C && N1.getValueType().isFixedLengthVector() && 5949 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5950 return getUNDEF(VT); 5951 5952 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5953 // expanding copies of large vectors from registers. This only works for 5954 // fixed length vectors, since we need to know the exact number of 5955 // elements. 5956 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5957 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5958 unsigned Factor = 5959 N1.getOperand(0).getValueType().getVectorNumElements(); 5960 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5961 N1.getOperand(N2C->getZExtValue() / Factor), 5962 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5963 } 5964 5965 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5966 // lowering is expanding large vector constants. 5967 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5968 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5969 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5970 N1.getValueType().isFixedLengthVector()) && 5971 "BUILD_VECTOR used for scalable vectors"); 5972 unsigned Index = 5973 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5974 SDValue Elt = N1.getOperand(Index); 5975 5976 if (VT != Elt.getValueType()) 5977 // If the vector element type is not legal, the BUILD_VECTOR operands 5978 // are promoted and implicitly truncated, and the result implicitly 5979 // extended. Make that explicit here. 5980 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5981 5982 return Elt; 5983 } 5984 5985 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5986 // operations are lowered to scalars. 5987 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5988 // If the indices are the same, return the inserted element else 5989 // if the indices are known different, extract the element from 5990 // the original vector. 5991 SDValue N1Op2 = N1.getOperand(2); 5992 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5993 5994 if (N1Op2C && N2C) { 5995 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5996 if (VT == N1.getOperand(1).getValueType()) 5997 return N1.getOperand(1); 5998 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5999 } 6000 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6001 } 6002 } 6003 6004 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6005 // when vector types are scalarized and v1iX is legal. 6006 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6007 // Here we are completely ignoring the extract element index (N2), 6008 // which is fine for fixed width vectors, since any index other than 0 6009 // is undefined anyway. However, this cannot be ignored for scalable 6010 // vectors - in theory we could support this, but we don't want to do this 6011 // without a profitability check. 6012 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6013 N1.getValueType().isFixedLengthVector() && 6014 N1.getValueType().getVectorNumElements() == 1) { 6015 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6016 N1.getOperand(1)); 6017 } 6018 break; 6019 case ISD::EXTRACT_ELEMENT: 6020 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6021 assert(!N1.getValueType().isVector() && !VT.isVector() && 6022 (N1.getValueType().isInteger() == VT.isInteger()) && 6023 N1.getValueType() != VT && 6024 "Wrong types for EXTRACT_ELEMENT!"); 6025 6026 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6027 // 64-bit integers into 32-bit parts. Instead of building the extract of 6028 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6029 if (N1.getOpcode() == ISD::BUILD_PAIR) 6030 return N1.getOperand(N2C->getZExtValue()); 6031 6032 // EXTRACT_ELEMENT of a constant int is also very common. 6033 if (N1C) { 6034 unsigned ElementSize = VT.getSizeInBits(); 6035 unsigned Shift = ElementSize * N2C->getZExtValue(); 6036 const APInt &Val = N1C->getAPIntValue(); 6037 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6038 } 6039 break; 6040 case ISD::EXTRACT_SUBVECTOR: { 6041 EVT N1VT = N1.getValueType(); 6042 assert(VT.isVector() && N1VT.isVector() && 6043 "Extract subvector VTs must be vectors!"); 6044 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6045 "Extract subvector VTs must have the same element type!"); 6046 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6047 "Cannot extract a scalable vector from a fixed length vector!"); 6048 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6049 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6050 "Extract subvector must be from larger vector to smaller vector!"); 6051 assert(N2C && "Extract subvector index must be a constant"); 6052 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6053 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6054 N1VT.getVectorMinNumElements()) && 6055 "Extract subvector overflow!"); 6056 assert(N2C->getAPIntValue().getBitWidth() == 6057 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6058 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6059 6060 // Trivial extraction. 6061 if (VT == N1VT) 6062 return N1; 6063 6064 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6065 if (N1.isUndef()) 6066 return getUNDEF(VT); 6067 6068 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6069 // the concat have the same type as the extract. 6070 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6071 VT == N1.getOperand(0).getValueType()) { 6072 unsigned Factor = VT.getVectorMinNumElements(); 6073 return N1.getOperand(N2C->getZExtValue() / Factor); 6074 } 6075 6076 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6077 // during shuffle legalization. 6078 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6079 VT == N1.getOperand(1).getValueType()) 6080 return N1.getOperand(1); 6081 break; 6082 } 6083 } 6084 6085 // Perform trivial constant folding. 6086 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6087 return SV; 6088 6089 // Canonicalize an UNDEF to the RHS, even over a constant. 6090 if (N1.isUndef()) { 6091 if (TLI->isCommutativeBinOp(Opcode)) { 6092 std::swap(N1, N2); 6093 } else { 6094 switch (Opcode) { 6095 case ISD::SIGN_EXTEND_INREG: 6096 case ISD::SUB: 6097 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6098 case ISD::UDIV: 6099 case ISD::SDIV: 6100 case ISD::UREM: 6101 case ISD::SREM: 6102 case ISD::SSUBSAT: 6103 case ISD::USUBSAT: 6104 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6105 } 6106 } 6107 } 6108 6109 // Fold a bunch of operators when the RHS is undef. 6110 if (N2.isUndef()) { 6111 switch (Opcode) { 6112 case ISD::XOR: 6113 if (N1.isUndef()) 6114 // Handle undef ^ undef -> 0 special case. This is a common 6115 // idiom (misuse). 6116 return getConstant(0, DL, VT); 6117 LLVM_FALLTHROUGH; 6118 case ISD::ADD: 6119 case ISD::SUB: 6120 case ISD::UDIV: 6121 case ISD::SDIV: 6122 case ISD::UREM: 6123 case ISD::SREM: 6124 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6125 case ISD::MUL: 6126 case ISD::AND: 6127 case ISD::SSUBSAT: 6128 case ISD::USUBSAT: 6129 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6130 case ISD::OR: 6131 case ISD::SADDSAT: 6132 case ISD::UADDSAT: 6133 return getAllOnesConstant(DL, VT); 6134 } 6135 } 6136 6137 // Memoize this node if possible. 6138 SDNode *N; 6139 SDVTList VTs = getVTList(VT); 6140 SDValue Ops[] = {N1, N2}; 6141 if (VT != MVT::Glue) { 6142 FoldingSetNodeID ID; 6143 AddNodeIDNode(ID, Opcode, VTs, Ops); 6144 void *IP = nullptr; 6145 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6146 E->intersectFlagsWith(Flags); 6147 return SDValue(E, 0); 6148 } 6149 6150 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6151 N->setFlags(Flags); 6152 createOperands(N, Ops); 6153 CSEMap.InsertNode(N, IP); 6154 } else { 6155 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6156 createOperands(N, Ops); 6157 } 6158 6159 InsertNode(N); 6160 SDValue V = SDValue(N, 0); 6161 NewSDValueDbgMsg(V, "Creating new node: ", this); 6162 return V; 6163 } 6164 6165 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6166 SDValue N1, SDValue N2, SDValue N3) { 6167 SDNodeFlags Flags; 6168 if (Inserter) 6169 Flags = Inserter->getFlags(); 6170 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6171 } 6172 6173 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6174 SDValue N1, SDValue N2, SDValue N3, 6175 const SDNodeFlags Flags) { 6176 assert(N1.getOpcode() != ISD::DELETED_NODE && 6177 N2.getOpcode() != ISD::DELETED_NODE && 6178 N3.getOpcode() != ISD::DELETED_NODE && 6179 "Operand is DELETED_NODE!"); 6180 // Perform various simplifications. 6181 switch (Opcode) { 6182 case ISD::FMA: { 6183 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6184 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6185 N3.getValueType() == VT && "FMA types must match!"); 6186 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6187 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6188 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6189 if (N1CFP && N2CFP && N3CFP) { 6190 APFloat V1 = N1CFP->getValueAPF(); 6191 const APFloat &V2 = N2CFP->getValueAPF(); 6192 const APFloat &V3 = N3CFP->getValueAPF(); 6193 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6194 return getConstantFP(V1, DL, VT); 6195 } 6196 break; 6197 } 6198 case ISD::BUILD_VECTOR: { 6199 // Attempt to simplify BUILD_VECTOR. 6200 SDValue Ops[] = {N1, N2, N3}; 6201 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6202 return V; 6203 break; 6204 } 6205 case ISD::CONCAT_VECTORS: { 6206 SDValue Ops[] = {N1, N2, N3}; 6207 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6208 return V; 6209 break; 6210 } 6211 case ISD::SETCC: { 6212 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6213 assert(N1.getValueType() == N2.getValueType() && 6214 "SETCC operands must have the same type!"); 6215 assert(VT.isVector() == N1.getValueType().isVector() && 6216 "SETCC type should be vector iff the operand type is vector!"); 6217 assert((!VT.isVector() || VT.getVectorElementCount() == 6218 N1.getValueType().getVectorElementCount()) && 6219 "SETCC vector element counts must match!"); 6220 // Use FoldSetCC to simplify SETCC's. 6221 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6222 return V; 6223 // Vector constant folding. 6224 SDValue Ops[] = {N1, N2, N3}; 6225 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6226 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6227 return V; 6228 } 6229 break; 6230 } 6231 case ISD::SELECT: 6232 case ISD::VSELECT: 6233 if (SDValue V = simplifySelect(N1, N2, N3)) 6234 return V; 6235 break; 6236 case ISD::VECTOR_SHUFFLE: 6237 llvm_unreachable("should use getVectorShuffle constructor!"); 6238 case ISD::VECTOR_SPLICE: { 6239 if (cast<ConstantSDNode>(N3)->isNullValue()) 6240 return N1; 6241 break; 6242 } 6243 case ISD::INSERT_VECTOR_ELT: { 6244 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6245 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6246 // for scalable vectors where we will generate appropriate code to 6247 // deal with out-of-bounds cases correctly. 6248 if (N3C && N1.getValueType().isFixedLengthVector() && 6249 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6250 return getUNDEF(VT); 6251 6252 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6253 if (N3.isUndef()) 6254 return getUNDEF(VT); 6255 6256 // If the inserted element is an UNDEF, just use the input vector. 6257 if (N2.isUndef()) 6258 return N1; 6259 6260 break; 6261 } 6262 case ISD::INSERT_SUBVECTOR: { 6263 // Inserting undef into undef is still undef. 6264 if (N1.isUndef() && N2.isUndef()) 6265 return getUNDEF(VT); 6266 6267 EVT N2VT = N2.getValueType(); 6268 assert(VT == N1.getValueType() && 6269 "Dest and insert subvector source types must match!"); 6270 assert(VT.isVector() && N2VT.isVector() && 6271 "Insert subvector VTs must be vectors!"); 6272 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6273 "Cannot insert a scalable vector into a fixed length vector!"); 6274 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6275 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6276 "Insert subvector must be from smaller vector to larger vector!"); 6277 assert(isa<ConstantSDNode>(N3) && 6278 "Insert subvector index must be constant"); 6279 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6280 (N2VT.getVectorMinNumElements() + 6281 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6282 VT.getVectorMinNumElements()) && 6283 "Insert subvector overflow!"); 6284 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6285 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6286 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6287 6288 // Trivial insertion. 6289 if (VT == N2VT) 6290 return N2; 6291 6292 // If this is an insert of an extracted vector into an undef vector, we 6293 // can just use the input to the extract. 6294 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6295 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6296 return N2.getOperand(0); 6297 break; 6298 } 6299 case ISD::BITCAST: 6300 // Fold bit_convert nodes from a type to themselves. 6301 if (N1.getValueType() == VT) 6302 return N1; 6303 break; 6304 } 6305 6306 // Memoize node if it doesn't produce a flag. 6307 SDNode *N; 6308 SDVTList VTs = getVTList(VT); 6309 SDValue Ops[] = {N1, N2, N3}; 6310 if (VT != MVT::Glue) { 6311 FoldingSetNodeID ID; 6312 AddNodeIDNode(ID, Opcode, VTs, Ops); 6313 void *IP = nullptr; 6314 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6315 E->intersectFlagsWith(Flags); 6316 return SDValue(E, 0); 6317 } 6318 6319 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6320 N->setFlags(Flags); 6321 createOperands(N, Ops); 6322 CSEMap.InsertNode(N, IP); 6323 } else { 6324 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6325 createOperands(N, Ops); 6326 } 6327 6328 InsertNode(N); 6329 SDValue V = SDValue(N, 0); 6330 NewSDValueDbgMsg(V, "Creating new node: ", this); 6331 return V; 6332 } 6333 6334 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6335 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6336 SDValue Ops[] = { N1, N2, N3, N4 }; 6337 return getNode(Opcode, DL, VT, Ops); 6338 } 6339 6340 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6341 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6342 SDValue N5) { 6343 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6344 return getNode(Opcode, DL, VT, Ops); 6345 } 6346 6347 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6348 /// the incoming stack arguments to be loaded from the stack. 6349 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6350 SmallVector<SDValue, 8> ArgChains; 6351 6352 // Include the original chain at the beginning of the list. When this is 6353 // used by target LowerCall hooks, this helps legalize find the 6354 // CALLSEQ_BEGIN node. 6355 ArgChains.push_back(Chain); 6356 6357 // Add a chain value for each stack argument. 6358 for (SDNode *U : getEntryNode().getNode()->uses()) 6359 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6360 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6361 if (FI->getIndex() < 0) 6362 ArgChains.push_back(SDValue(L, 1)); 6363 6364 // Build a tokenfactor for all the chains. 6365 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6366 } 6367 6368 /// getMemsetValue - Vectorized representation of the memset value 6369 /// operand. 6370 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6371 const SDLoc &dl) { 6372 assert(!Value.isUndef()); 6373 6374 unsigned NumBits = VT.getScalarSizeInBits(); 6375 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6376 assert(C->getAPIntValue().getBitWidth() == 8); 6377 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6378 if (VT.isInteger()) { 6379 bool IsOpaque = VT.getSizeInBits() > 64 || 6380 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6381 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6382 } 6383 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6384 VT); 6385 } 6386 6387 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6388 EVT IntVT = VT.getScalarType(); 6389 if (!IntVT.isInteger()) 6390 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6391 6392 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6393 if (NumBits > 8) { 6394 // Use a multiplication with 0x010101... to extend the input to the 6395 // required length. 6396 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6397 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6398 DAG.getConstant(Magic, dl, IntVT)); 6399 } 6400 6401 if (VT != Value.getValueType() && !VT.isInteger()) 6402 Value = DAG.getBitcast(VT.getScalarType(), Value); 6403 if (VT != Value.getValueType()) 6404 Value = DAG.getSplatBuildVector(VT, dl, Value); 6405 6406 return Value; 6407 } 6408 6409 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6410 /// used when a memcpy is turned into a memset when the source is a constant 6411 /// string ptr. 6412 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6413 const TargetLowering &TLI, 6414 const ConstantDataArraySlice &Slice) { 6415 // Handle vector with all elements zero. 6416 if (Slice.Array == nullptr) { 6417 if (VT.isInteger()) 6418 return DAG.getConstant(0, dl, VT); 6419 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6420 return DAG.getConstantFP(0.0, dl, VT); 6421 if (VT.isVector()) { 6422 unsigned NumElts = VT.getVectorNumElements(); 6423 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6424 return DAG.getNode(ISD::BITCAST, dl, VT, 6425 DAG.getConstant(0, dl, 6426 EVT::getVectorVT(*DAG.getContext(), 6427 EltVT, NumElts))); 6428 } 6429 llvm_unreachable("Expected type!"); 6430 } 6431 6432 assert(!VT.isVector() && "Can't handle vector type here!"); 6433 unsigned NumVTBits = VT.getSizeInBits(); 6434 unsigned NumVTBytes = NumVTBits / 8; 6435 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6436 6437 APInt Val(NumVTBits, 0); 6438 if (DAG.getDataLayout().isLittleEndian()) { 6439 for (unsigned i = 0; i != NumBytes; ++i) 6440 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6441 } else { 6442 for (unsigned i = 0; i != NumBytes; ++i) 6443 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6444 } 6445 6446 // If the "cost" of materializing the integer immediate is less than the cost 6447 // of a load, then it is cost effective to turn the load into the immediate. 6448 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6449 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6450 return DAG.getConstant(Val, dl, VT); 6451 return SDValue(); 6452 } 6453 6454 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6455 const SDLoc &DL, 6456 const SDNodeFlags Flags) { 6457 EVT VT = Base.getValueType(); 6458 SDValue Index; 6459 6460 if (Offset.isScalable()) 6461 Index = getVScale(DL, Base.getValueType(), 6462 APInt(Base.getValueSizeInBits().getFixedSize(), 6463 Offset.getKnownMinSize())); 6464 else 6465 Index = getConstant(Offset.getFixedSize(), DL, VT); 6466 6467 return getMemBasePlusOffset(Base, Index, DL, Flags); 6468 } 6469 6470 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6471 const SDLoc &DL, 6472 const SDNodeFlags Flags) { 6473 assert(Offset.getValueType().isInteger()); 6474 EVT BasePtrVT = Ptr.getValueType(); 6475 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6476 } 6477 6478 /// Returns true if memcpy source is constant data. 6479 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6480 uint64_t SrcDelta = 0; 6481 GlobalAddressSDNode *G = nullptr; 6482 if (Src.getOpcode() == ISD::GlobalAddress) 6483 G = cast<GlobalAddressSDNode>(Src); 6484 else if (Src.getOpcode() == ISD::ADD && 6485 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6486 Src.getOperand(1).getOpcode() == ISD::Constant) { 6487 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6488 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6489 } 6490 if (!G) 6491 return false; 6492 6493 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6494 SrcDelta + G->getOffset()); 6495 } 6496 6497 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6498 SelectionDAG &DAG) { 6499 // On Darwin, -Os means optimize for size without hurting performance, so 6500 // only really optimize for size when -Oz (MinSize) is used. 6501 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6502 return MF.getFunction().hasMinSize(); 6503 return DAG.shouldOptForSize(); 6504 } 6505 6506 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6507 SmallVector<SDValue, 32> &OutChains, unsigned From, 6508 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6509 SmallVector<SDValue, 16> &OutStoreChains) { 6510 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6511 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6512 SmallVector<SDValue, 16> GluedLoadChains; 6513 for (unsigned i = From; i < To; ++i) { 6514 OutChains.push_back(OutLoadChains[i]); 6515 GluedLoadChains.push_back(OutLoadChains[i]); 6516 } 6517 6518 // Chain for all loads. 6519 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6520 GluedLoadChains); 6521 6522 for (unsigned i = From; i < To; ++i) { 6523 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6524 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6525 ST->getBasePtr(), ST->getMemoryVT(), 6526 ST->getMemOperand()); 6527 OutChains.push_back(NewStore); 6528 } 6529 } 6530 6531 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6532 SDValue Chain, SDValue Dst, SDValue Src, 6533 uint64_t Size, Align Alignment, 6534 bool isVol, bool AlwaysInline, 6535 MachinePointerInfo DstPtrInfo, 6536 MachinePointerInfo SrcPtrInfo, 6537 const AAMDNodes &AAInfo) { 6538 // Turn a memcpy of undef to nop. 6539 // FIXME: We need to honor volatile even is Src is undef. 6540 if (Src.isUndef()) 6541 return Chain; 6542 6543 // Expand memcpy to a series of load and store ops if the size operand falls 6544 // below a certain threshold. 6545 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6546 // rather than maybe a humongous number of loads and stores. 6547 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6548 const DataLayout &DL = DAG.getDataLayout(); 6549 LLVMContext &C = *DAG.getContext(); 6550 std::vector<EVT> MemOps; 6551 bool DstAlignCanChange = false; 6552 MachineFunction &MF = DAG.getMachineFunction(); 6553 MachineFrameInfo &MFI = MF.getFrameInfo(); 6554 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6555 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6556 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6557 DstAlignCanChange = true; 6558 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6559 if (!SrcAlign || Alignment > *SrcAlign) 6560 SrcAlign = Alignment; 6561 assert(SrcAlign && "SrcAlign must be set"); 6562 ConstantDataArraySlice Slice; 6563 // If marked as volatile, perform a copy even when marked as constant. 6564 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6565 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6566 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6567 const MemOp Op = isZeroConstant 6568 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6569 /*IsZeroMemset*/ true, isVol) 6570 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6571 *SrcAlign, isVol, CopyFromConstant); 6572 if (!TLI.findOptimalMemOpLowering( 6573 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6574 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6575 return SDValue(); 6576 6577 if (DstAlignCanChange) { 6578 Type *Ty = MemOps[0].getTypeForEVT(C); 6579 Align NewAlign = DL.getABITypeAlign(Ty); 6580 6581 // Don't promote to an alignment that would require dynamic stack 6582 // realignment. 6583 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6584 if (!TRI->hasStackRealignment(MF)) 6585 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6586 NewAlign = NewAlign / 2; 6587 6588 if (NewAlign > Alignment) { 6589 // Give the stack frame object a larger alignment if needed. 6590 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6591 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6592 Alignment = NewAlign; 6593 } 6594 } 6595 6596 // Prepare AAInfo for loads/stores after lowering this memcpy. 6597 AAMDNodes NewAAInfo = AAInfo; 6598 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6599 6600 MachineMemOperand::Flags MMOFlags = 6601 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6602 SmallVector<SDValue, 16> OutLoadChains; 6603 SmallVector<SDValue, 16> OutStoreChains; 6604 SmallVector<SDValue, 32> OutChains; 6605 unsigned NumMemOps = MemOps.size(); 6606 uint64_t SrcOff = 0, DstOff = 0; 6607 for (unsigned i = 0; i != NumMemOps; ++i) { 6608 EVT VT = MemOps[i]; 6609 unsigned VTSize = VT.getSizeInBits() / 8; 6610 SDValue Value, Store; 6611 6612 if (VTSize > Size) { 6613 // Issuing an unaligned load / store pair that overlaps with the previous 6614 // pair. Adjust the offset accordingly. 6615 assert(i == NumMemOps-1 && i != 0); 6616 SrcOff -= VTSize - Size; 6617 DstOff -= VTSize - Size; 6618 } 6619 6620 if (CopyFromConstant && 6621 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6622 // It's unlikely a store of a vector immediate can be done in a single 6623 // instruction. It would require a load from a constantpool first. 6624 // We only handle zero vectors here. 6625 // FIXME: Handle other cases where store of vector immediate is done in 6626 // a single instruction. 6627 ConstantDataArraySlice SubSlice; 6628 if (SrcOff < Slice.Length) { 6629 SubSlice = Slice; 6630 SubSlice.move(SrcOff); 6631 } else { 6632 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6633 SubSlice.Array = nullptr; 6634 SubSlice.Offset = 0; 6635 SubSlice.Length = VTSize; 6636 } 6637 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6638 if (Value.getNode()) { 6639 Store = DAG.getStore( 6640 Chain, dl, Value, 6641 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6642 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6643 OutChains.push_back(Store); 6644 } 6645 } 6646 6647 if (!Store.getNode()) { 6648 // The type might not be legal for the target. This should only happen 6649 // if the type is smaller than a legal type, as on PPC, so the right 6650 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6651 // to Load/Store if NVT==VT. 6652 // FIXME does the case above also need this? 6653 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6654 assert(NVT.bitsGE(VT)); 6655 6656 bool isDereferenceable = 6657 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6658 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6659 if (isDereferenceable) 6660 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6661 6662 Value = DAG.getExtLoad( 6663 ISD::EXTLOAD, dl, NVT, Chain, 6664 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6665 SrcPtrInfo.getWithOffset(SrcOff), VT, 6666 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6667 OutLoadChains.push_back(Value.getValue(1)); 6668 6669 Store = DAG.getTruncStore( 6670 Chain, dl, Value, 6671 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6672 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6673 OutStoreChains.push_back(Store); 6674 } 6675 SrcOff += VTSize; 6676 DstOff += VTSize; 6677 Size -= VTSize; 6678 } 6679 6680 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6681 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6682 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6683 6684 if (NumLdStInMemcpy) { 6685 // It may be that memcpy might be converted to memset if it's memcpy 6686 // of constants. In such a case, we won't have loads and stores, but 6687 // just stores. In the absence of loads, there is nothing to gang up. 6688 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6689 // If target does not care, just leave as it. 6690 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6691 OutChains.push_back(OutLoadChains[i]); 6692 OutChains.push_back(OutStoreChains[i]); 6693 } 6694 } else { 6695 // Ld/St less than/equal limit set by target. 6696 if (NumLdStInMemcpy <= GluedLdStLimit) { 6697 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6698 NumLdStInMemcpy, OutLoadChains, 6699 OutStoreChains); 6700 } else { 6701 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6702 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6703 unsigned GlueIter = 0; 6704 6705 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6706 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6707 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6708 6709 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6710 OutLoadChains, OutStoreChains); 6711 GlueIter += GluedLdStLimit; 6712 } 6713 6714 // Residual ld/st. 6715 if (RemainingLdStInMemcpy) { 6716 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6717 RemainingLdStInMemcpy, OutLoadChains, 6718 OutStoreChains); 6719 } 6720 } 6721 } 6722 } 6723 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6724 } 6725 6726 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6727 SDValue Chain, SDValue Dst, SDValue Src, 6728 uint64_t Size, Align Alignment, 6729 bool isVol, bool AlwaysInline, 6730 MachinePointerInfo DstPtrInfo, 6731 MachinePointerInfo SrcPtrInfo, 6732 const AAMDNodes &AAInfo) { 6733 // Turn a memmove of undef to nop. 6734 // FIXME: We need to honor volatile even is Src is undef. 6735 if (Src.isUndef()) 6736 return Chain; 6737 6738 // Expand memmove to a series of load and store ops if the size operand falls 6739 // below a certain threshold. 6740 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6741 const DataLayout &DL = DAG.getDataLayout(); 6742 LLVMContext &C = *DAG.getContext(); 6743 std::vector<EVT> MemOps; 6744 bool DstAlignCanChange = false; 6745 MachineFunction &MF = DAG.getMachineFunction(); 6746 MachineFrameInfo &MFI = MF.getFrameInfo(); 6747 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6748 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6749 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6750 DstAlignCanChange = true; 6751 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6752 if (!SrcAlign || Alignment > *SrcAlign) 6753 SrcAlign = Alignment; 6754 assert(SrcAlign && "SrcAlign must be set"); 6755 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6756 if (!TLI.findOptimalMemOpLowering( 6757 MemOps, Limit, 6758 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6759 /*IsVolatile*/ true), 6760 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6761 MF.getFunction().getAttributes())) 6762 return SDValue(); 6763 6764 if (DstAlignCanChange) { 6765 Type *Ty = MemOps[0].getTypeForEVT(C); 6766 Align NewAlign = DL.getABITypeAlign(Ty); 6767 if (NewAlign > Alignment) { 6768 // Give the stack frame object a larger alignment if needed. 6769 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6770 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6771 Alignment = NewAlign; 6772 } 6773 } 6774 6775 // Prepare AAInfo for loads/stores after lowering this memmove. 6776 AAMDNodes NewAAInfo = AAInfo; 6777 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6778 6779 MachineMemOperand::Flags MMOFlags = 6780 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6781 uint64_t SrcOff = 0, DstOff = 0; 6782 SmallVector<SDValue, 8> LoadValues; 6783 SmallVector<SDValue, 8> LoadChains; 6784 SmallVector<SDValue, 8> OutChains; 6785 unsigned NumMemOps = MemOps.size(); 6786 for (unsigned i = 0; i < NumMemOps; i++) { 6787 EVT VT = MemOps[i]; 6788 unsigned VTSize = VT.getSizeInBits() / 8; 6789 SDValue Value; 6790 6791 bool isDereferenceable = 6792 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6793 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6794 if (isDereferenceable) 6795 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6796 6797 Value = DAG.getLoad( 6798 VT, dl, Chain, 6799 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6800 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6801 LoadValues.push_back(Value); 6802 LoadChains.push_back(Value.getValue(1)); 6803 SrcOff += VTSize; 6804 } 6805 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6806 OutChains.clear(); 6807 for (unsigned i = 0; i < NumMemOps; i++) { 6808 EVT VT = MemOps[i]; 6809 unsigned VTSize = VT.getSizeInBits() / 8; 6810 SDValue Store; 6811 6812 Store = DAG.getStore( 6813 Chain, dl, LoadValues[i], 6814 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6815 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6816 OutChains.push_back(Store); 6817 DstOff += VTSize; 6818 } 6819 6820 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6821 } 6822 6823 /// Lower the call to 'memset' intrinsic function into a series of store 6824 /// operations. 6825 /// 6826 /// \param DAG Selection DAG where lowered code is placed. 6827 /// \param dl Link to corresponding IR location. 6828 /// \param Chain Control flow dependency. 6829 /// \param Dst Pointer to destination memory location. 6830 /// \param Src Value of byte to write into the memory. 6831 /// \param Size Number of bytes to write. 6832 /// \param Alignment Alignment of the destination in bytes. 6833 /// \param isVol True if destination is volatile. 6834 /// \param DstPtrInfo IR information on the memory pointer. 6835 /// \returns New head in the control flow, if lowering was successful, empty 6836 /// SDValue otherwise. 6837 /// 6838 /// The function tries to replace 'llvm.memset' intrinsic with several store 6839 /// operations and value calculation code. This is usually profitable for small 6840 /// memory size. 6841 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6842 SDValue Chain, SDValue Dst, SDValue Src, 6843 uint64_t Size, Align Alignment, bool isVol, 6844 MachinePointerInfo DstPtrInfo, 6845 const AAMDNodes &AAInfo) { 6846 // Turn a memset of undef to nop. 6847 // FIXME: We need to honor volatile even is Src is undef. 6848 if (Src.isUndef()) 6849 return Chain; 6850 6851 // Expand memset to a series of load/store ops if the size operand 6852 // falls below a certain threshold. 6853 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6854 std::vector<EVT> MemOps; 6855 bool DstAlignCanChange = false; 6856 MachineFunction &MF = DAG.getMachineFunction(); 6857 MachineFrameInfo &MFI = MF.getFrameInfo(); 6858 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6859 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6860 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6861 DstAlignCanChange = true; 6862 bool IsZeroVal = 6863 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6864 if (!TLI.findOptimalMemOpLowering( 6865 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6866 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6867 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6868 return SDValue(); 6869 6870 if (DstAlignCanChange) { 6871 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6872 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6873 if (NewAlign > Alignment) { 6874 // Give the stack frame object a larger alignment if needed. 6875 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6876 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6877 Alignment = NewAlign; 6878 } 6879 } 6880 6881 SmallVector<SDValue, 8> OutChains; 6882 uint64_t DstOff = 0; 6883 unsigned NumMemOps = MemOps.size(); 6884 6885 // Find the largest store and generate the bit pattern for it. 6886 EVT LargestVT = MemOps[0]; 6887 for (unsigned i = 1; i < NumMemOps; i++) 6888 if (MemOps[i].bitsGT(LargestVT)) 6889 LargestVT = MemOps[i]; 6890 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6891 6892 // Prepare AAInfo for loads/stores after lowering this memset. 6893 AAMDNodes NewAAInfo = AAInfo; 6894 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6895 6896 for (unsigned i = 0; i < NumMemOps; i++) { 6897 EVT VT = MemOps[i]; 6898 unsigned VTSize = VT.getSizeInBits() / 8; 6899 if (VTSize > Size) { 6900 // Issuing an unaligned load / store pair that overlaps with the previous 6901 // pair. Adjust the offset accordingly. 6902 assert(i == NumMemOps-1 && i != 0); 6903 DstOff -= VTSize - Size; 6904 } 6905 6906 // If this store is smaller than the largest store see whether we can get 6907 // the smaller value for free with a truncate. 6908 SDValue Value = MemSetValue; 6909 if (VT.bitsLT(LargestVT)) { 6910 if (!LargestVT.isVector() && !VT.isVector() && 6911 TLI.isTruncateFree(LargestVT, VT)) 6912 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6913 else 6914 Value = getMemsetValue(Src, VT, DAG, dl); 6915 } 6916 assert(Value.getValueType() == VT && "Value with wrong type."); 6917 SDValue Store = DAG.getStore( 6918 Chain, dl, Value, 6919 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6920 DstPtrInfo.getWithOffset(DstOff), Alignment, 6921 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 6922 NewAAInfo); 6923 OutChains.push_back(Store); 6924 DstOff += VT.getSizeInBits() / 8; 6925 Size -= VTSize; 6926 } 6927 6928 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6929 } 6930 6931 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6932 unsigned AS) { 6933 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6934 // pointer operands can be losslessly bitcasted to pointers of address space 0 6935 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6936 report_fatal_error("cannot lower memory intrinsic in address space " + 6937 Twine(AS)); 6938 } 6939 } 6940 6941 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6942 SDValue Src, SDValue Size, Align Alignment, 6943 bool isVol, bool AlwaysInline, bool isTailCall, 6944 MachinePointerInfo DstPtrInfo, 6945 MachinePointerInfo SrcPtrInfo, 6946 const AAMDNodes &AAInfo) { 6947 // Check to see if we should lower the memcpy to loads and stores first. 6948 // For cases within the target-specified limits, this is the best choice. 6949 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6950 if (ConstantSize) { 6951 // Memcpy with size zero? Just return the original chain. 6952 if (ConstantSize->isZero()) 6953 return Chain; 6954 6955 SDValue Result = getMemcpyLoadsAndStores( 6956 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6957 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6958 if (Result.getNode()) 6959 return Result; 6960 } 6961 6962 // Then check to see if we should lower the memcpy with target-specific 6963 // code. If the target chooses to do this, this is the next best. 6964 if (TSI) { 6965 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6966 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6967 DstPtrInfo, SrcPtrInfo); 6968 if (Result.getNode()) 6969 return Result; 6970 } 6971 6972 // If we really need inline code and the target declined to provide it, 6973 // use a (potentially long) sequence of loads and stores. 6974 if (AlwaysInline) { 6975 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6976 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6977 ConstantSize->getZExtValue(), Alignment, 6978 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 6979 } 6980 6981 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6982 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6983 6984 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6985 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6986 // respect volatile, so they may do things like read or write memory 6987 // beyond the given memory regions. But fixing this isn't easy, and most 6988 // people don't care. 6989 6990 // Emit a library call. 6991 TargetLowering::ArgListTy Args; 6992 TargetLowering::ArgListEntry Entry; 6993 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6994 Entry.Node = Dst; Args.push_back(Entry); 6995 Entry.Node = Src; Args.push_back(Entry); 6996 6997 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6998 Entry.Node = Size; Args.push_back(Entry); 6999 // FIXME: pass in SDLoc 7000 TargetLowering::CallLoweringInfo CLI(*this); 7001 CLI.setDebugLoc(dl) 7002 .setChain(Chain) 7003 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7004 Dst.getValueType().getTypeForEVT(*getContext()), 7005 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7006 TLI->getPointerTy(getDataLayout())), 7007 std::move(Args)) 7008 .setDiscardResult() 7009 .setTailCall(isTailCall); 7010 7011 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7012 return CallResult.second; 7013 } 7014 7015 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7016 SDValue Dst, unsigned DstAlign, 7017 SDValue Src, unsigned SrcAlign, 7018 SDValue Size, Type *SizeTy, 7019 unsigned ElemSz, bool isTailCall, 7020 MachinePointerInfo DstPtrInfo, 7021 MachinePointerInfo SrcPtrInfo) { 7022 // Emit a library call. 7023 TargetLowering::ArgListTy Args; 7024 TargetLowering::ArgListEntry Entry; 7025 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7026 Entry.Node = Dst; 7027 Args.push_back(Entry); 7028 7029 Entry.Node = Src; 7030 Args.push_back(Entry); 7031 7032 Entry.Ty = SizeTy; 7033 Entry.Node = Size; 7034 Args.push_back(Entry); 7035 7036 RTLIB::Libcall LibraryCall = 7037 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7038 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7039 report_fatal_error("Unsupported element size"); 7040 7041 TargetLowering::CallLoweringInfo CLI(*this); 7042 CLI.setDebugLoc(dl) 7043 .setChain(Chain) 7044 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7045 Type::getVoidTy(*getContext()), 7046 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7047 TLI->getPointerTy(getDataLayout())), 7048 std::move(Args)) 7049 .setDiscardResult() 7050 .setTailCall(isTailCall); 7051 7052 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7053 return CallResult.second; 7054 } 7055 7056 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7057 SDValue Src, SDValue Size, Align Alignment, 7058 bool isVol, bool isTailCall, 7059 MachinePointerInfo DstPtrInfo, 7060 MachinePointerInfo SrcPtrInfo, 7061 const AAMDNodes &AAInfo) { 7062 // Check to see if we should lower the memmove to loads and stores first. 7063 // For cases within the target-specified limits, this is the best choice. 7064 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7065 if (ConstantSize) { 7066 // Memmove with size zero? Just return the original chain. 7067 if (ConstantSize->isZero()) 7068 return Chain; 7069 7070 SDValue Result = getMemmoveLoadsAndStores( 7071 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7072 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7073 if (Result.getNode()) 7074 return Result; 7075 } 7076 7077 // Then check to see if we should lower the memmove with target-specific 7078 // code. If the target chooses to do this, this is the next best. 7079 if (TSI) { 7080 SDValue Result = 7081 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7082 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7083 if (Result.getNode()) 7084 return Result; 7085 } 7086 7087 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7088 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7089 7090 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7091 // not be safe. See memcpy above for more details. 7092 7093 // Emit a library call. 7094 TargetLowering::ArgListTy Args; 7095 TargetLowering::ArgListEntry Entry; 7096 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7097 Entry.Node = Dst; Args.push_back(Entry); 7098 Entry.Node = Src; Args.push_back(Entry); 7099 7100 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7101 Entry.Node = Size; Args.push_back(Entry); 7102 // FIXME: pass in SDLoc 7103 TargetLowering::CallLoweringInfo CLI(*this); 7104 CLI.setDebugLoc(dl) 7105 .setChain(Chain) 7106 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7107 Dst.getValueType().getTypeForEVT(*getContext()), 7108 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7109 TLI->getPointerTy(getDataLayout())), 7110 std::move(Args)) 7111 .setDiscardResult() 7112 .setTailCall(isTailCall); 7113 7114 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7115 return CallResult.second; 7116 } 7117 7118 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7119 SDValue Dst, unsigned DstAlign, 7120 SDValue Src, unsigned SrcAlign, 7121 SDValue Size, Type *SizeTy, 7122 unsigned ElemSz, bool isTailCall, 7123 MachinePointerInfo DstPtrInfo, 7124 MachinePointerInfo SrcPtrInfo) { 7125 // Emit a library call. 7126 TargetLowering::ArgListTy Args; 7127 TargetLowering::ArgListEntry Entry; 7128 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7129 Entry.Node = Dst; 7130 Args.push_back(Entry); 7131 7132 Entry.Node = Src; 7133 Args.push_back(Entry); 7134 7135 Entry.Ty = SizeTy; 7136 Entry.Node = Size; 7137 Args.push_back(Entry); 7138 7139 RTLIB::Libcall LibraryCall = 7140 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7141 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7142 report_fatal_error("Unsupported element size"); 7143 7144 TargetLowering::CallLoweringInfo CLI(*this); 7145 CLI.setDebugLoc(dl) 7146 .setChain(Chain) 7147 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7148 Type::getVoidTy(*getContext()), 7149 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7150 TLI->getPointerTy(getDataLayout())), 7151 std::move(Args)) 7152 .setDiscardResult() 7153 .setTailCall(isTailCall); 7154 7155 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7156 return CallResult.second; 7157 } 7158 7159 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7160 SDValue Src, SDValue Size, Align Alignment, 7161 bool isVol, bool isTailCall, 7162 MachinePointerInfo DstPtrInfo, 7163 const AAMDNodes &AAInfo) { 7164 // Check to see if we should lower the memset to stores first. 7165 // For cases within the target-specified limits, this is the best choice. 7166 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7167 if (ConstantSize) { 7168 // Memset with size zero? Just return the original chain. 7169 if (ConstantSize->isZero()) 7170 return Chain; 7171 7172 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7173 ConstantSize->getZExtValue(), Alignment, 7174 isVol, DstPtrInfo, AAInfo); 7175 7176 if (Result.getNode()) 7177 return Result; 7178 } 7179 7180 // Then check to see if we should lower the memset with target-specific 7181 // code. If the target chooses to do this, this is the next best. 7182 if (TSI) { 7183 SDValue Result = TSI->EmitTargetCodeForMemset( 7184 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7185 if (Result.getNode()) 7186 return Result; 7187 } 7188 7189 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7190 7191 // Emit a library call. 7192 TargetLowering::ArgListTy Args; 7193 TargetLowering::ArgListEntry Entry; 7194 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7195 Args.push_back(Entry); 7196 Entry.Node = Src; 7197 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7198 Args.push_back(Entry); 7199 Entry.Node = Size; 7200 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7201 Args.push_back(Entry); 7202 7203 // FIXME: pass in SDLoc 7204 TargetLowering::CallLoweringInfo CLI(*this); 7205 CLI.setDebugLoc(dl) 7206 .setChain(Chain) 7207 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7208 Dst.getValueType().getTypeForEVT(*getContext()), 7209 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7210 TLI->getPointerTy(getDataLayout())), 7211 std::move(Args)) 7212 .setDiscardResult() 7213 .setTailCall(isTailCall); 7214 7215 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7216 return CallResult.second; 7217 } 7218 7219 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7220 SDValue Dst, unsigned DstAlign, 7221 SDValue Value, SDValue Size, Type *SizeTy, 7222 unsigned ElemSz, bool isTailCall, 7223 MachinePointerInfo DstPtrInfo) { 7224 // Emit a library call. 7225 TargetLowering::ArgListTy Args; 7226 TargetLowering::ArgListEntry Entry; 7227 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7228 Entry.Node = Dst; 7229 Args.push_back(Entry); 7230 7231 Entry.Ty = Type::getInt8Ty(*getContext()); 7232 Entry.Node = Value; 7233 Args.push_back(Entry); 7234 7235 Entry.Ty = SizeTy; 7236 Entry.Node = Size; 7237 Args.push_back(Entry); 7238 7239 RTLIB::Libcall LibraryCall = 7240 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7241 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7242 report_fatal_error("Unsupported element size"); 7243 7244 TargetLowering::CallLoweringInfo CLI(*this); 7245 CLI.setDebugLoc(dl) 7246 .setChain(Chain) 7247 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7248 Type::getVoidTy(*getContext()), 7249 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7250 TLI->getPointerTy(getDataLayout())), 7251 std::move(Args)) 7252 .setDiscardResult() 7253 .setTailCall(isTailCall); 7254 7255 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7256 return CallResult.second; 7257 } 7258 7259 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7260 SDVTList VTList, ArrayRef<SDValue> Ops, 7261 MachineMemOperand *MMO) { 7262 FoldingSetNodeID ID; 7263 ID.AddInteger(MemVT.getRawBits()); 7264 AddNodeIDNode(ID, Opcode, VTList, Ops); 7265 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7266 void* IP = nullptr; 7267 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7268 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7269 return SDValue(E, 0); 7270 } 7271 7272 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7273 VTList, MemVT, MMO); 7274 createOperands(N, Ops); 7275 7276 CSEMap.InsertNode(N, IP); 7277 InsertNode(N); 7278 return SDValue(N, 0); 7279 } 7280 7281 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7282 EVT MemVT, SDVTList VTs, SDValue Chain, 7283 SDValue Ptr, SDValue Cmp, SDValue Swp, 7284 MachineMemOperand *MMO) { 7285 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7286 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7287 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7288 7289 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7290 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7291 } 7292 7293 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7294 SDValue Chain, SDValue Ptr, SDValue Val, 7295 MachineMemOperand *MMO) { 7296 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7297 Opcode == ISD::ATOMIC_LOAD_SUB || 7298 Opcode == ISD::ATOMIC_LOAD_AND || 7299 Opcode == ISD::ATOMIC_LOAD_CLR || 7300 Opcode == ISD::ATOMIC_LOAD_OR || 7301 Opcode == ISD::ATOMIC_LOAD_XOR || 7302 Opcode == ISD::ATOMIC_LOAD_NAND || 7303 Opcode == ISD::ATOMIC_LOAD_MIN || 7304 Opcode == ISD::ATOMIC_LOAD_MAX || 7305 Opcode == ISD::ATOMIC_LOAD_UMIN || 7306 Opcode == ISD::ATOMIC_LOAD_UMAX || 7307 Opcode == ISD::ATOMIC_LOAD_FADD || 7308 Opcode == ISD::ATOMIC_LOAD_FSUB || 7309 Opcode == ISD::ATOMIC_SWAP || 7310 Opcode == ISD::ATOMIC_STORE) && 7311 "Invalid Atomic Op"); 7312 7313 EVT VT = Val.getValueType(); 7314 7315 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7316 getVTList(VT, MVT::Other); 7317 SDValue Ops[] = {Chain, Ptr, Val}; 7318 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7319 } 7320 7321 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7322 EVT VT, SDValue Chain, SDValue Ptr, 7323 MachineMemOperand *MMO) { 7324 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7325 7326 SDVTList VTs = getVTList(VT, MVT::Other); 7327 SDValue Ops[] = {Chain, Ptr}; 7328 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7329 } 7330 7331 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7332 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7333 if (Ops.size() == 1) 7334 return Ops[0]; 7335 7336 SmallVector<EVT, 4> VTs; 7337 VTs.reserve(Ops.size()); 7338 for (const SDValue &Op : Ops) 7339 VTs.push_back(Op.getValueType()); 7340 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7341 } 7342 7343 SDValue SelectionDAG::getMemIntrinsicNode( 7344 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7345 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7346 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7347 if (!Size && MemVT.isScalableVector()) 7348 Size = MemoryLocation::UnknownSize; 7349 else if (!Size) 7350 Size = MemVT.getStoreSize(); 7351 7352 MachineFunction &MF = getMachineFunction(); 7353 MachineMemOperand *MMO = 7354 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7355 7356 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7357 } 7358 7359 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7360 SDVTList VTList, 7361 ArrayRef<SDValue> Ops, EVT MemVT, 7362 MachineMemOperand *MMO) { 7363 assert((Opcode == ISD::INTRINSIC_VOID || 7364 Opcode == ISD::INTRINSIC_W_CHAIN || 7365 Opcode == ISD::PREFETCH || 7366 ((int)Opcode <= std::numeric_limits<int>::max() && 7367 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7368 "Opcode is not a memory-accessing opcode!"); 7369 7370 // Memoize the node unless it returns a flag. 7371 MemIntrinsicSDNode *N; 7372 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7373 FoldingSetNodeID ID; 7374 AddNodeIDNode(ID, Opcode, VTList, Ops); 7375 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7376 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7377 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7378 void *IP = nullptr; 7379 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7380 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7381 return SDValue(E, 0); 7382 } 7383 7384 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7385 VTList, MemVT, MMO); 7386 createOperands(N, Ops); 7387 7388 CSEMap.InsertNode(N, IP); 7389 } else { 7390 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7391 VTList, MemVT, MMO); 7392 createOperands(N, Ops); 7393 } 7394 InsertNode(N); 7395 SDValue V(N, 0); 7396 NewSDValueDbgMsg(V, "Creating new node: ", this); 7397 return V; 7398 } 7399 7400 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7401 SDValue Chain, int FrameIndex, 7402 int64_t Size, int64_t Offset) { 7403 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7404 const auto VTs = getVTList(MVT::Other); 7405 SDValue Ops[2] = { 7406 Chain, 7407 getFrameIndex(FrameIndex, 7408 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7409 true)}; 7410 7411 FoldingSetNodeID ID; 7412 AddNodeIDNode(ID, Opcode, VTs, Ops); 7413 ID.AddInteger(FrameIndex); 7414 ID.AddInteger(Size); 7415 ID.AddInteger(Offset); 7416 void *IP = nullptr; 7417 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7418 return SDValue(E, 0); 7419 7420 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7421 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7422 createOperands(N, Ops); 7423 CSEMap.InsertNode(N, IP); 7424 InsertNode(N); 7425 SDValue V(N, 0); 7426 NewSDValueDbgMsg(V, "Creating new node: ", this); 7427 return V; 7428 } 7429 7430 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7431 uint64_t Guid, uint64_t Index, 7432 uint32_t Attr) { 7433 const unsigned Opcode = ISD::PSEUDO_PROBE; 7434 const auto VTs = getVTList(MVT::Other); 7435 SDValue Ops[] = {Chain}; 7436 FoldingSetNodeID ID; 7437 AddNodeIDNode(ID, Opcode, VTs, Ops); 7438 ID.AddInteger(Guid); 7439 ID.AddInteger(Index); 7440 void *IP = nullptr; 7441 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7442 return SDValue(E, 0); 7443 7444 auto *N = newSDNode<PseudoProbeSDNode>( 7445 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7446 createOperands(N, Ops); 7447 CSEMap.InsertNode(N, IP); 7448 InsertNode(N); 7449 SDValue V(N, 0); 7450 NewSDValueDbgMsg(V, "Creating new node: ", this); 7451 return V; 7452 } 7453 7454 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7455 /// MachinePointerInfo record from it. This is particularly useful because the 7456 /// code generator has many cases where it doesn't bother passing in a 7457 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7458 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7459 SelectionDAG &DAG, SDValue Ptr, 7460 int64_t Offset = 0) { 7461 // If this is FI+Offset, we can model it. 7462 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7463 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7464 FI->getIndex(), Offset); 7465 7466 // If this is (FI+Offset1)+Offset2, we can model it. 7467 if (Ptr.getOpcode() != ISD::ADD || 7468 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7469 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7470 return Info; 7471 7472 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7473 return MachinePointerInfo::getFixedStack( 7474 DAG.getMachineFunction(), FI, 7475 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7476 } 7477 7478 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7479 /// MachinePointerInfo record from it. This is particularly useful because the 7480 /// code generator has many cases where it doesn't bother passing in a 7481 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7482 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7483 SelectionDAG &DAG, SDValue Ptr, 7484 SDValue OffsetOp) { 7485 // If the 'Offset' value isn't a constant, we can't handle this. 7486 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7487 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7488 if (OffsetOp.isUndef()) 7489 return InferPointerInfo(Info, DAG, Ptr); 7490 return Info; 7491 } 7492 7493 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7494 EVT VT, const SDLoc &dl, SDValue Chain, 7495 SDValue Ptr, SDValue Offset, 7496 MachinePointerInfo PtrInfo, EVT MemVT, 7497 Align Alignment, 7498 MachineMemOperand::Flags MMOFlags, 7499 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7500 assert(Chain.getValueType() == MVT::Other && 7501 "Invalid chain type"); 7502 7503 MMOFlags |= MachineMemOperand::MOLoad; 7504 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7505 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7506 // clients. 7507 if (PtrInfo.V.isNull()) 7508 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7509 7510 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7511 MachineFunction &MF = getMachineFunction(); 7512 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7513 Alignment, AAInfo, Ranges); 7514 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7515 } 7516 7517 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7518 EVT VT, const SDLoc &dl, SDValue Chain, 7519 SDValue Ptr, SDValue Offset, EVT MemVT, 7520 MachineMemOperand *MMO) { 7521 if (VT == MemVT) { 7522 ExtType = ISD::NON_EXTLOAD; 7523 } else if (ExtType == ISD::NON_EXTLOAD) { 7524 assert(VT == MemVT && "Non-extending load from different memory type!"); 7525 } else { 7526 // Extending load. 7527 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7528 "Should only be an extending load, not truncating!"); 7529 assert(VT.isInteger() == MemVT.isInteger() && 7530 "Cannot convert from FP to Int or Int -> FP!"); 7531 assert(VT.isVector() == MemVT.isVector() && 7532 "Cannot use an ext load to convert to or from a vector!"); 7533 assert((!VT.isVector() || 7534 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7535 "Cannot use an ext load to change the number of vector elements!"); 7536 } 7537 7538 bool Indexed = AM != ISD::UNINDEXED; 7539 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7540 7541 SDVTList VTs = Indexed ? 7542 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7543 SDValue Ops[] = { Chain, Ptr, Offset }; 7544 FoldingSetNodeID ID; 7545 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7546 ID.AddInteger(MemVT.getRawBits()); 7547 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7548 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7549 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7550 void *IP = nullptr; 7551 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7552 cast<LoadSDNode>(E)->refineAlignment(MMO); 7553 return SDValue(E, 0); 7554 } 7555 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7556 ExtType, MemVT, MMO); 7557 createOperands(N, Ops); 7558 7559 CSEMap.InsertNode(N, IP); 7560 InsertNode(N); 7561 SDValue V(N, 0); 7562 NewSDValueDbgMsg(V, "Creating new node: ", this); 7563 return V; 7564 } 7565 7566 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7567 SDValue Ptr, MachinePointerInfo PtrInfo, 7568 MaybeAlign Alignment, 7569 MachineMemOperand::Flags MMOFlags, 7570 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7571 SDValue Undef = getUNDEF(Ptr.getValueType()); 7572 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7573 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7574 } 7575 7576 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7577 SDValue Ptr, MachineMemOperand *MMO) { 7578 SDValue Undef = getUNDEF(Ptr.getValueType()); 7579 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7580 VT, MMO); 7581 } 7582 7583 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7584 EVT VT, SDValue Chain, SDValue Ptr, 7585 MachinePointerInfo PtrInfo, EVT MemVT, 7586 MaybeAlign Alignment, 7587 MachineMemOperand::Flags MMOFlags, 7588 const AAMDNodes &AAInfo) { 7589 SDValue Undef = getUNDEF(Ptr.getValueType()); 7590 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7591 MemVT, Alignment, MMOFlags, AAInfo); 7592 } 7593 7594 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7595 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7596 MachineMemOperand *MMO) { 7597 SDValue Undef = getUNDEF(Ptr.getValueType()); 7598 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7599 MemVT, MMO); 7600 } 7601 7602 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7603 SDValue Base, SDValue Offset, 7604 ISD::MemIndexedMode AM) { 7605 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7606 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7607 // Don't propagate the invariant or dereferenceable flags. 7608 auto MMOFlags = 7609 LD->getMemOperand()->getFlags() & 7610 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7611 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7612 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7613 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7614 } 7615 7616 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7617 SDValue Ptr, MachinePointerInfo PtrInfo, 7618 Align Alignment, 7619 MachineMemOperand::Flags MMOFlags, 7620 const AAMDNodes &AAInfo) { 7621 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7622 7623 MMOFlags |= MachineMemOperand::MOStore; 7624 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7625 7626 if (PtrInfo.V.isNull()) 7627 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7628 7629 MachineFunction &MF = getMachineFunction(); 7630 uint64_t Size = 7631 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7632 MachineMemOperand *MMO = 7633 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7634 return getStore(Chain, dl, Val, Ptr, MMO); 7635 } 7636 7637 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7638 SDValue Ptr, MachineMemOperand *MMO) { 7639 assert(Chain.getValueType() == MVT::Other && 7640 "Invalid chain type"); 7641 EVT VT = Val.getValueType(); 7642 SDVTList VTs = getVTList(MVT::Other); 7643 SDValue Undef = getUNDEF(Ptr.getValueType()); 7644 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7645 FoldingSetNodeID ID; 7646 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7647 ID.AddInteger(VT.getRawBits()); 7648 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7649 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7650 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7651 void *IP = nullptr; 7652 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7653 cast<StoreSDNode>(E)->refineAlignment(MMO); 7654 return SDValue(E, 0); 7655 } 7656 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7657 ISD::UNINDEXED, false, VT, MMO); 7658 createOperands(N, Ops); 7659 7660 CSEMap.InsertNode(N, IP); 7661 InsertNode(N); 7662 SDValue V(N, 0); 7663 NewSDValueDbgMsg(V, "Creating new node: ", this); 7664 return V; 7665 } 7666 7667 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7668 SDValue Ptr, MachinePointerInfo PtrInfo, 7669 EVT SVT, Align Alignment, 7670 MachineMemOperand::Flags MMOFlags, 7671 const AAMDNodes &AAInfo) { 7672 assert(Chain.getValueType() == MVT::Other && 7673 "Invalid chain type"); 7674 7675 MMOFlags |= MachineMemOperand::MOStore; 7676 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7677 7678 if (PtrInfo.V.isNull()) 7679 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7680 7681 MachineFunction &MF = getMachineFunction(); 7682 MachineMemOperand *MMO = MF.getMachineMemOperand( 7683 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7684 Alignment, AAInfo); 7685 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7686 } 7687 7688 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7689 SDValue Ptr, EVT SVT, 7690 MachineMemOperand *MMO) { 7691 EVT VT = Val.getValueType(); 7692 7693 assert(Chain.getValueType() == MVT::Other && 7694 "Invalid chain type"); 7695 if (VT == SVT) 7696 return getStore(Chain, dl, Val, Ptr, MMO); 7697 7698 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7699 "Should only be a truncating store, not extending!"); 7700 assert(VT.isInteger() == SVT.isInteger() && 7701 "Can't do FP-INT conversion!"); 7702 assert(VT.isVector() == SVT.isVector() && 7703 "Cannot use trunc store to convert to or from a vector!"); 7704 assert((!VT.isVector() || 7705 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7706 "Cannot use trunc store to change the number of vector elements!"); 7707 7708 SDVTList VTs = getVTList(MVT::Other); 7709 SDValue Undef = getUNDEF(Ptr.getValueType()); 7710 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7711 FoldingSetNodeID ID; 7712 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7713 ID.AddInteger(SVT.getRawBits()); 7714 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7715 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7716 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7717 void *IP = nullptr; 7718 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7719 cast<StoreSDNode>(E)->refineAlignment(MMO); 7720 return SDValue(E, 0); 7721 } 7722 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7723 ISD::UNINDEXED, true, SVT, MMO); 7724 createOperands(N, Ops); 7725 7726 CSEMap.InsertNode(N, IP); 7727 InsertNode(N); 7728 SDValue V(N, 0); 7729 NewSDValueDbgMsg(V, "Creating new node: ", this); 7730 return V; 7731 } 7732 7733 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7734 SDValue Base, SDValue Offset, 7735 ISD::MemIndexedMode AM) { 7736 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7737 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7738 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7739 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7740 FoldingSetNodeID ID; 7741 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7742 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7743 ID.AddInteger(ST->getRawSubclassData()); 7744 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7745 void *IP = nullptr; 7746 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7747 return SDValue(E, 0); 7748 7749 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7750 ST->isTruncatingStore(), ST->getMemoryVT(), 7751 ST->getMemOperand()); 7752 createOperands(N, Ops); 7753 7754 CSEMap.InsertNode(N, IP); 7755 InsertNode(N); 7756 SDValue V(N, 0); 7757 NewSDValueDbgMsg(V, "Creating new node: ", this); 7758 return V; 7759 } 7760 7761 SDValue SelectionDAG::getLoadVP( 7762 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7763 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7764 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7765 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7766 const MDNode *Ranges, bool IsExpanding) { 7767 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7768 7769 MMOFlags |= MachineMemOperand::MOLoad; 7770 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7771 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7772 // clients. 7773 if (PtrInfo.V.isNull()) 7774 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7775 7776 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7777 MachineFunction &MF = getMachineFunction(); 7778 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7779 Alignment, AAInfo, Ranges); 7780 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7781 MMO, IsExpanding); 7782 } 7783 7784 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7785 ISD::LoadExtType ExtType, EVT VT, 7786 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7787 SDValue Offset, SDValue Mask, SDValue EVL, 7788 EVT MemVT, MachineMemOperand *MMO, 7789 bool IsExpanding) { 7790 bool Indexed = AM != ISD::UNINDEXED; 7791 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7792 7793 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7794 : getVTList(VT, MVT::Other); 7795 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7796 FoldingSetNodeID ID; 7797 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7798 ID.AddInteger(VT.getRawBits()); 7799 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7800 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7801 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7802 void *IP = nullptr; 7803 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7804 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7805 return SDValue(E, 0); 7806 } 7807 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7808 ExtType, IsExpanding, MemVT, MMO); 7809 createOperands(N, Ops); 7810 7811 CSEMap.InsertNode(N, IP); 7812 InsertNode(N); 7813 SDValue V(N, 0); 7814 NewSDValueDbgMsg(V, "Creating new node: ", this); 7815 return V; 7816 } 7817 7818 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7819 SDValue Ptr, SDValue Mask, SDValue EVL, 7820 MachinePointerInfo PtrInfo, 7821 MaybeAlign Alignment, 7822 MachineMemOperand::Flags MMOFlags, 7823 const AAMDNodes &AAInfo, const MDNode *Ranges, 7824 bool IsExpanding) { 7825 SDValue Undef = getUNDEF(Ptr.getValueType()); 7826 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7827 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7828 IsExpanding); 7829 } 7830 7831 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7832 SDValue Ptr, SDValue Mask, SDValue EVL, 7833 MachineMemOperand *MMO, bool IsExpanding) { 7834 SDValue Undef = getUNDEF(Ptr.getValueType()); 7835 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7836 Mask, EVL, VT, MMO, IsExpanding); 7837 } 7838 7839 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7840 EVT VT, SDValue Chain, SDValue Ptr, 7841 SDValue Mask, SDValue EVL, 7842 MachinePointerInfo PtrInfo, EVT MemVT, 7843 MaybeAlign Alignment, 7844 MachineMemOperand::Flags MMOFlags, 7845 const AAMDNodes &AAInfo, bool IsExpanding) { 7846 SDValue Undef = getUNDEF(Ptr.getValueType()); 7847 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7848 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7849 IsExpanding); 7850 } 7851 7852 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7853 EVT VT, SDValue Chain, SDValue Ptr, 7854 SDValue Mask, SDValue EVL, EVT MemVT, 7855 MachineMemOperand *MMO, bool IsExpanding) { 7856 SDValue Undef = getUNDEF(Ptr.getValueType()); 7857 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7858 EVL, MemVT, MMO, IsExpanding); 7859 } 7860 7861 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7862 SDValue Base, SDValue Offset, 7863 ISD::MemIndexedMode AM) { 7864 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7865 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7866 // Don't propagate the invariant or dereferenceable flags. 7867 auto MMOFlags = 7868 LD->getMemOperand()->getFlags() & 7869 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7870 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7871 LD->getChain(), Base, Offset, LD->getMask(), 7872 LD->getVectorLength(), LD->getPointerInfo(), 7873 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7874 nullptr, LD->isExpandingLoad()); 7875 } 7876 7877 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7878 SDValue Ptr, SDValue Offset, SDValue Mask, 7879 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 7880 ISD::MemIndexedMode AM, bool IsTruncating, 7881 bool IsCompressing) { 7882 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7883 bool Indexed = AM != ISD::UNINDEXED; 7884 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 7885 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 7886 : getVTList(MVT::Other); 7887 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 7888 FoldingSetNodeID ID; 7889 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7890 ID.AddInteger(MemVT.getRawBits()); 7891 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7892 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7893 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7894 void *IP = nullptr; 7895 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7896 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7897 return SDValue(E, 0); 7898 } 7899 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7900 IsTruncating, IsCompressing, MemVT, MMO); 7901 createOperands(N, Ops); 7902 7903 CSEMap.InsertNode(N, IP); 7904 InsertNode(N); 7905 SDValue V(N, 0); 7906 NewSDValueDbgMsg(V, "Creating new node: ", this); 7907 return V; 7908 } 7909 7910 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7911 SDValue Val, SDValue Ptr, SDValue Mask, 7912 SDValue EVL, MachinePointerInfo PtrInfo, 7913 EVT SVT, Align Alignment, 7914 MachineMemOperand::Flags MMOFlags, 7915 const AAMDNodes &AAInfo, 7916 bool IsCompressing) { 7917 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7918 7919 MMOFlags |= MachineMemOperand::MOStore; 7920 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7921 7922 if (PtrInfo.V.isNull()) 7923 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7924 7925 MachineFunction &MF = getMachineFunction(); 7926 MachineMemOperand *MMO = MF.getMachineMemOperand( 7927 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7928 Alignment, AAInfo); 7929 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 7930 IsCompressing); 7931 } 7932 7933 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7934 SDValue Val, SDValue Ptr, SDValue Mask, 7935 SDValue EVL, EVT SVT, 7936 MachineMemOperand *MMO, 7937 bool IsCompressing) { 7938 EVT VT = Val.getValueType(); 7939 7940 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7941 if (VT == SVT) 7942 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 7943 EVL, VT, MMO, ISD::UNINDEXED, 7944 /*IsTruncating*/ false, IsCompressing); 7945 7946 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7947 "Should only be a truncating store, not extending!"); 7948 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 7949 assert(VT.isVector() == SVT.isVector() && 7950 "Cannot use trunc store to convert to or from a vector!"); 7951 assert((!VT.isVector() || 7952 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7953 "Cannot use trunc store to change the number of vector elements!"); 7954 7955 SDVTList VTs = getVTList(MVT::Other); 7956 SDValue Undef = getUNDEF(Ptr.getValueType()); 7957 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 7958 FoldingSetNodeID ID; 7959 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7960 ID.AddInteger(SVT.getRawBits()); 7961 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7962 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 7963 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7964 void *IP = nullptr; 7965 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7966 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7967 return SDValue(E, 0); 7968 } 7969 auto *N = 7970 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7971 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 7972 createOperands(N, Ops); 7973 7974 CSEMap.InsertNode(N, IP); 7975 InsertNode(N); 7976 SDValue V(N, 0); 7977 NewSDValueDbgMsg(V, "Creating new node: ", this); 7978 return V; 7979 } 7980 7981 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 7982 SDValue Base, SDValue Offset, 7983 ISD::MemIndexedMode AM) { 7984 auto *ST = cast<VPStoreSDNode>(OrigStore); 7985 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 7986 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7987 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 7988 Offset, ST->getMask(), ST->getVectorLength()}; 7989 FoldingSetNodeID ID; 7990 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7991 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7992 ID.AddInteger(ST->getRawSubclassData()); 7993 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7994 void *IP = nullptr; 7995 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7996 return SDValue(E, 0); 7997 7998 auto *N = newSDNode<VPStoreSDNode>( 7999 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8000 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8001 createOperands(N, Ops); 8002 8003 CSEMap.InsertNode(N, IP); 8004 InsertNode(N); 8005 SDValue V(N, 0); 8006 NewSDValueDbgMsg(V, "Creating new node: ", this); 8007 return V; 8008 } 8009 8010 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8011 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8012 ISD::MemIndexType IndexType) { 8013 assert(Ops.size() == 6 && "Incompatible number of operands"); 8014 8015 FoldingSetNodeID ID; 8016 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8017 ID.AddInteger(VT.getRawBits()); 8018 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8019 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8020 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8021 void *IP = nullptr; 8022 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8023 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8024 return SDValue(E, 0); 8025 } 8026 8027 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8028 VT, MMO, IndexType); 8029 createOperands(N, Ops); 8030 8031 assert(N->getMask().getValueType().getVectorElementCount() == 8032 N->getValueType(0).getVectorElementCount() && 8033 "Vector width mismatch between mask and data"); 8034 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8035 N->getValueType(0).getVectorElementCount().isScalable() && 8036 "Scalable flags of index and data do not match"); 8037 assert(ElementCount::isKnownGE( 8038 N->getIndex().getValueType().getVectorElementCount(), 8039 N->getValueType(0).getVectorElementCount()) && 8040 "Vector width mismatch between index and data"); 8041 assert(isa<ConstantSDNode>(N->getScale()) && 8042 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8043 "Scale should be a constant power of 2"); 8044 8045 CSEMap.InsertNode(N, IP); 8046 InsertNode(N); 8047 SDValue V(N, 0); 8048 NewSDValueDbgMsg(V, "Creating new node: ", this); 8049 return V; 8050 } 8051 8052 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8053 ArrayRef<SDValue> Ops, 8054 MachineMemOperand *MMO, 8055 ISD::MemIndexType IndexType) { 8056 assert(Ops.size() == 7 && "Incompatible number of operands"); 8057 8058 FoldingSetNodeID ID; 8059 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8060 ID.AddInteger(VT.getRawBits()); 8061 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8062 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8063 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8064 void *IP = nullptr; 8065 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8066 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8067 return SDValue(E, 0); 8068 } 8069 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8070 VT, MMO, IndexType); 8071 createOperands(N, Ops); 8072 8073 assert(N->getMask().getValueType().getVectorElementCount() == 8074 N->getValue().getValueType().getVectorElementCount() && 8075 "Vector width mismatch between mask and data"); 8076 assert( 8077 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8078 N->getValue().getValueType().getVectorElementCount().isScalable() && 8079 "Scalable flags of index and data do not match"); 8080 assert(ElementCount::isKnownGE( 8081 N->getIndex().getValueType().getVectorElementCount(), 8082 N->getValue().getValueType().getVectorElementCount()) && 8083 "Vector width mismatch between index and data"); 8084 assert(isa<ConstantSDNode>(N->getScale()) && 8085 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8086 "Scale should be a constant power of 2"); 8087 8088 CSEMap.InsertNode(N, IP); 8089 InsertNode(N); 8090 SDValue V(N, 0); 8091 NewSDValueDbgMsg(V, "Creating new node: ", this); 8092 return V; 8093 } 8094 8095 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8096 SDValue Base, SDValue Offset, SDValue Mask, 8097 SDValue PassThru, EVT MemVT, 8098 MachineMemOperand *MMO, 8099 ISD::MemIndexedMode AM, 8100 ISD::LoadExtType ExtTy, bool isExpanding) { 8101 bool Indexed = AM != ISD::UNINDEXED; 8102 assert((Indexed || Offset.isUndef()) && 8103 "Unindexed masked load with an offset!"); 8104 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8105 : getVTList(VT, MVT::Other); 8106 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8107 FoldingSetNodeID ID; 8108 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8109 ID.AddInteger(MemVT.getRawBits()); 8110 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8111 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8112 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8113 void *IP = nullptr; 8114 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8115 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8116 return SDValue(E, 0); 8117 } 8118 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8119 AM, ExtTy, isExpanding, MemVT, MMO); 8120 createOperands(N, Ops); 8121 8122 CSEMap.InsertNode(N, IP); 8123 InsertNode(N); 8124 SDValue V(N, 0); 8125 NewSDValueDbgMsg(V, "Creating new node: ", this); 8126 return V; 8127 } 8128 8129 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8130 SDValue Base, SDValue Offset, 8131 ISD::MemIndexedMode AM) { 8132 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8133 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8134 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8135 Offset, LD->getMask(), LD->getPassThru(), 8136 LD->getMemoryVT(), LD->getMemOperand(), AM, 8137 LD->getExtensionType(), LD->isExpandingLoad()); 8138 } 8139 8140 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8141 SDValue Val, SDValue Base, SDValue Offset, 8142 SDValue Mask, EVT MemVT, 8143 MachineMemOperand *MMO, 8144 ISD::MemIndexedMode AM, bool IsTruncating, 8145 bool IsCompressing) { 8146 assert(Chain.getValueType() == MVT::Other && 8147 "Invalid chain type"); 8148 bool Indexed = AM != ISD::UNINDEXED; 8149 assert((Indexed || Offset.isUndef()) && 8150 "Unindexed masked store with an offset!"); 8151 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8152 : getVTList(MVT::Other); 8153 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8154 FoldingSetNodeID ID; 8155 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8156 ID.AddInteger(MemVT.getRawBits()); 8157 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8158 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8159 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8160 void *IP = nullptr; 8161 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8162 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8163 return SDValue(E, 0); 8164 } 8165 auto *N = 8166 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8167 IsTruncating, IsCompressing, MemVT, MMO); 8168 createOperands(N, Ops); 8169 8170 CSEMap.InsertNode(N, IP); 8171 InsertNode(N); 8172 SDValue V(N, 0); 8173 NewSDValueDbgMsg(V, "Creating new node: ", this); 8174 return V; 8175 } 8176 8177 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8178 SDValue Base, SDValue Offset, 8179 ISD::MemIndexedMode AM) { 8180 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8181 assert(ST->getOffset().isUndef() && 8182 "Masked store is already a indexed store!"); 8183 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8184 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8185 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8186 } 8187 8188 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8189 ArrayRef<SDValue> Ops, 8190 MachineMemOperand *MMO, 8191 ISD::MemIndexType IndexType, 8192 ISD::LoadExtType ExtTy) { 8193 assert(Ops.size() == 6 && "Incompatible number of operands"); 8194 8195 FoldingSetNodeID ID; 8196 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8197 ID.AddInteger(MemVT.getRawBits()); 8198 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8199 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8200 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8201 void *IP = nullptr; 8202 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8203 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8204 return SDValue(E, 0); 8205 } 8206 8207 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8208 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8209 VTs, MemVT, MMO, IndexType, ExtTy); 8210 createOperands(N, Ops); 8211 8212 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8213 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8214 assert(N->getMask().getValueType().getVectorElementCount() == 8215 N->getValueType(0).getVectorElementCount() && 8216 "Vector width mismatch between mask and data"); 8217 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8218 N->getValueType(0).getVectorElementCount().isScalable() && 8219 "Scalable flags of index and data do not match"); 8220 assert(ElementCount::isKnownGE( 8221 N->getIndex().getValueType().getVectorElementCount(), 8222 N->getValueType(0).getVectorElementCount()) && 8223 "Vector width mismatch between index and data"); 8224 assert(isa<ConstantSDNode>(N->getScale()) && 8225 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8226 "Scale should be a constant power of 2"); 8227 8228 CSEMap.InsertNode(N, IP); 8229 InsertNode(N); 8230 SDValue V(N, 0); 8231 NewSDValueDbgMsg(V, "Creating new node: ", this); 8232 return V; 8233 } 8234 8235 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8236 ArrayRef<SDValue> Ops, 8237 MachineMemOperand *MMO, 8238 ISD::MemIndexType IndexType, 8239 bool IsTrunc) { 8240 assert(Ops.size() == 6 && "Incompatible number of operands"); 8241 8242 FoldingSetNodeID ID; 8243 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8244 ID.AddInteger(MemVT.getRawBits()); 8245 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8246 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8247 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8248 void *IP = nullptr; 8249 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8250 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8251 return SDValue(E, 0); 8252 } 8253 8254 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8255 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8256 VTs, MemVT, MMO, IndexType, IsTrunc); 8257 createOperands(N, Ops); 8258 8259 assert(N->getMask().getValueType().getVectorElementCount() == 8260 N->getValue().getValueType().getVectorElementCount() && 8261 "Vector width mismatch between mask and data"); 8262 assert( 8263 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8264 N->getValue().getValueType().getVectorElementCount().isScalable() && 8265 "Scalable flags of index and data do not match"); 8266 assert(ElementCount::isKnownGE( 8267 N->getIndex().getValueType().getVectorElementCount(), 8268 N->getValue().getValueType().getVectorElementCount()) && 8269 "Vector width mismatch between index and data"); 8270 assert(isa<ConstantSDNode>(N->getScale()) && 8271 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8272 "Scale should be a constant power of 2"); 8273 8274 CSEMap.InsertNode(N, IP); 8275 InsertNode(N); 8276 SDValue V(N, 0); 8277 NewSDValueDbgMsg(V, "Creating new node: ", this); 8278 return V; 8279 } 8280 8281 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8282 // select undef, T, F --> T (if T is a constant), otherwise F 8283 // select, ?, undef, F --> F 8284 // select, ?, T, undef --> T 8285 if (Cond.isUndef()) 8286 return isConstantValueOfAnyType(T) ? T : F; 8287 if (T.isUndef()) 8288 return F; 8289 if (F.isUndef()) 8290 return T; 8291 8292 // select true, T, F --> T 8293 // select false, T, F --> F 8294 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8295 return CondC->isZero() ? F : T; 8296 8297 // TODO: This should simplify VSELECT with constant condition using something 8298 // like this (but check boolean contents to be complete?): 8299 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8300 // return T; 8301 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8302 // return F; 8303 8304 // select ?, T, T --> T 8305 if (T == F) 8306 return T; 8307 8308 return SDValue(); 8309 } 8310 8311 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8312 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8313 if (X.isUndef()) 8314 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8315 // shift X, undef --> undef (because it may shift by the bitwidth) 8316 if (Y.isUndef()) 8317 return getUNDEF(X.getValueType()); 8318 8319 // shift 0, Y --> 0 8320 // shift X, 0 --> X 8321 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8322 return X; 8323 8324 // shift X, C >= bitwidth(X) --> undef 8325 // All vector elements must be too big (or undef) to avoid partial undefs. 8326 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8327 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8328 }; 8329 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8330 return getUNDEF(X.getValueType()); 8331 8332 return SDValue(); 8333 } 8334 8335 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8336 SDNodeFlags Flags) { 8337 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8338 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8339 // operation is poison. That result can be relaxed to undef. 8340 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8341 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8342 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8343 (YC && YC->getValueAPF().isNaN()); 8344 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8345 (YC && YC->getValueAPF().isInfinity()); 8346 8347 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8348 return getUNDEF(X.getValueType()); 8349 8350 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8351 return getUNDEF(X.getValueType()); 8352 8353 if (!YC) 8354 return SDValue(); 8355 8356 // X + -0.0 --> X 8357 if (Opcode == ISD::FADD) 8358 if (YC->getValueAPF().isNegZero()) 8359 return X; 8360 8361 // X - +0.0 --> X 8362 if (Opcode == ISD::FSUB) 8363 if (YC->getValueAPF().isPosZero()) 8364 return X; 8365 8366 // X * 1.0 --> X 8367 // X / 1.0 --> X 8368 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8369 if (YC->getValueAPF().isExactlyValue(1.0)) 8370 return X; 8371 8372 // X * 0.0 --> 0.0 8373 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8374 if (YC->getValueAPF().isZero()) 8375 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8376 8377 return SDValue(); 8378 } 8379 8380 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8381 SDValue Ptr, SDValue SV, unsigned Align) { 8382 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8383 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8384 } 8385 8386 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8387 ArrayRef<SDUse> Ops) { 8388 switch (Ops.size()) { 8389 case 0: return getNode(Opcode, DL, VT); 8390 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8391 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8392 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8393 default: break; 8394 } 8395 8396 // Copy from an SDUse array into an SDValue array for use with 8397 // the regular getNode logic. 8398 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8399 return getNode(Opcode, DL, VT, NewOps); 8400 } 8401 8402 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8403 ArrayRef<SDValue> Ops) { 8404 SDNodeFlags Flags; 8405 if (Inserter) 8406 Flags = Inserter->getFlags(); 8407 return getNode(Opcode, DL, VT, Ops, Flags); 8408 } 8409 8410 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8411 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8412 unsigned NumOps = Ops.size(); 8413 switch (NumOps) { 8414 case 0: return getNode(Opcode, DL, VT); 8415 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8416 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8417 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8418 default: break; 8419 } 8420 8421 #ifndef NDEBUG 8422 for (auto &Op : Ops) 8423 assert(Op.getOpcode() != ISD::DELETED_NODE && 8424 "Operand is DELETED_NODE!"); 8425 #endif 8426 8427 switch (Opcode) { 8428 default: break; 8429 case ISD::BUILD_VECTOR: 8430 // Attempt to simplify BUILD_VECTOR. 8431 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8432 return V; 8433 break; 8434 case ISD::CONCAT_VECTORS: 8435 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8436 return V; 8437 break; 8438 case ISD::SELECT_CC: 8439 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8440 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8441 "LHS and RHS of condition must have same type!"); 8442 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8443 "True and False arms of SelectCC must have same type!"); 8444 assert(Ops[2].getValueType() == VT && 8445 "select_cc node must be of same type as true and false value!"); 8446 break; 8447 case ISD::BR_CC: 8448 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8449 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8450 "LHS/RHS of comparison should match types!"); 8451 break; 8452 } 8453 8454 // Memoize nodes. 8455 SDNode *N; 8456 SDVTList VTs = getVTList(VT); 8457 8458 if (VT != MVT::Glue) { 8459 FoldingSetNodeID ID; 8460 AddNodeIDNode(ID, Opcode, VTs, Ops); 8461 void *IP = nullptr; 8462 8463 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8464 return SDValue(E, 0); 8465 8466 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8467 createOperands(N, Ops); 8468 8469 CSEMap.InsertNode(N, IP); 8470 } else { 8471 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8472 createOperands(N, Ops); 8473 } 8474 8475 N->setFlags(Flags); 8476 InsertNode(N); 8477 SDValue V(N, 0); 8478 NewSDValueDbgMsg(V, "Creating new node: ", this); 8479 return V; 8480 } 8481 8482 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8483 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8484 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8485 } 8486 8487 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8488 ArrayRef<SDValue> Ops) { 8489 SDNodeFlags Flags; 8490 if (Inserter) 8491 Flags = Inserter->getFlags(); 8492 return getNode(Opcode, DL, VTList, Ops, Flags); 8493 } 8494 8495 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8496 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8497 if (VTList.NumVTs == 1) 8498 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8499 8500 #ifndef NDEBUG 8501 for (auto &Op : Ops) 8502 assert(Op.getOpcode() != ISD::DELETED_NODE && 8503 "Operand is DELETED_NODE!"); 8504 #endif 8505 8506 switch (Opcode) { 8507 case ISD::STRICT_FP_EXTEND: 8508 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8509 "Invalid STRICT_FP_EXTEND!"); 8510 assert(VTList.VTs[0].isFloatingPoint() && 8511 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8512 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8513 "STRICT_FP_EXTEND result type should be vector iff the operand " 8514 "type is vector!"); 8515 assert((!VTList.VTs[0].isVector() || 8516 VTList.VTs[0].getVectorNumElements() == 8517 Ops[1].getValueType().getVectorNumElements()) && 8518 "Vector element count mismatch!"); 8519 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8520 "Invalid fpext node, dst <= src!"); 8521 break; 8522 case ISD::STRICT_FP_ROUND: 8523 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8524 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8525 "STRICT_FP_ROUND result type should be vector iff the operand " 8526 "type is vector!"); 8527 assert((!VTList.VTs[0].isVector() || 8528 VTList.VTs[0].getVectorNumElements() == 8529 Ops[1].getValueType().getVectorNumElements()) && 8530 "Vector element count mismatch!"); 8531 assert(VTList.VTs[0].isFloatingPoint() && 8532 Ops[1].getValueType().isFloatingPoint() && 8533 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8534 isa<ConstantSDNode>(Ops[2]) && 8535 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8536 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8537 "Invalid STRICT_FP_ROUND!"); 8538 break; 8539 #if 0 8540 // FIXME: figure out how to safely handle things like 8541 // int foo(int x) { return 1 << (x & 255); } 8542 // int bar() { return foo(256); } 8543 case ISD::SRA_PARTS: 8544 case ISD::SRL_PARTS: 8545 case ISD::SHL_PARTS: 8546 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8547 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8548 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8549 else if (N3.getOpcode() == ISD::AND) 8550 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8551 // If the and is only masking out bits that cannot effect the shift, 8552 // eliminate the and. 8553 unsigned NumBits = VT.getScalarSizeInBits()*2; 8554 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8555 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8556 } 8557 break; 8558 #endif 8559 } 8560 8561 // Memoize the node unless it returns a flag. 8562 SDNode *N; 8563 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8564 FoldingSetNodeID ID; 8565 AddNodeIDNode(ID, Opcode, VTList, Ops); 8566 void *IP = nullptr; 8567 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8568 return SDValue(E, 0); 8569 8570 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8571 createOperands(N, Ops); 8572 CSEMap.InsertNode(N, IP); 8573 } else { 8574 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8575 createOperands(N, Ops); 8576 } 8577 8578 N->setFlags(Flags); 8579 InsertNode(N); 8580 SDValue V(N, 0); 8581 NewSDValueDbgMsg(V, "Creating new node: ", this); 8582 return V; 8583 } 8584 8585 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8586 SDVTList VTList) { 8587 return getNode(Opcode, DL, VTList, None); 8588 } 8589 8590 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8591 SDValue N1) { 8592 SDValue Ops[] = { N1 }; 8593 return getNode(Opcode, DL, VTList, Ops); 8594 } 8595 8596 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8597 SDValue N1, SDValue N2) { 8598 SDValue Ops[] = { N1, N2 }; 8599 return getNode(Opcode, DL, VTList, Ops); 8600 } 8601 8602 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8603 SDValue N1, SDValue N2, SDValue N3) { 8604 SDValue Ops[] = { N1, N2, N3 }; 8605 return getNode(Opcode, DL, VTList, Ops); 8606 } 8607 8608 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8609 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8610 SDValue Ops[] = { N1, N2, N3, N4 }; 8611 return getNode(Opcode, DL, VTList, Ops); 8612 } 8613 8614 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8615 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8616 SDValue N5) { 8617 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8618 return getNode(Opcode, DL, VTList, Ops); 8619 } 8620 8621 SDVTList SelectionDAG::getVTList(EVT VT) { 8622 return makeVTList(SDNode::getValueTypeList(VT), 1); 8623 } 8624 8625 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8626 FoldingSetNodeID ID; 8627 ID.AddInteger(2U); 8628 ID.AddInteger(VT1.getRawBits()); 8629 ID.AddInteger(VT2.getRawBits()); 8630 8631 void *IP = nullptr; 8632 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8633 if (!Result) { 8634 EVT *Array = Allocator.Allocate<EVT>(2); 8635 Array[0] = VT1; 8636 Array[1] = VT2; 8637 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8638 VTListMap.InsertNode(Result, IP); 8639 } 8640 return Result->getSDVTList(); 8641 } 8642 8643 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 8644 FoldingSetNodeID ID; 8645 ID.AddInteger(3U); 8646 ID.AddInteger(VT1.getRawBits()); 8647 ID.AddInteger(VT2.getRawBits()); 8648 ID.AddInteger(VT3.getRawBits()); 8649 8650 void *IP = nullptr; 8651 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8652 if (!Result) { 8653 EVT *Array = Allocator.Allocate<EVT>(3); 8654 Array[0] = VT1; 8655 Array[1] = VT2; 8656 Array[2] = VT3; 8657 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 8658 VTListMap.InsertNode(Result, IP); 8659 } 8660 return Result->getSDVTList(); 8661 } 8662 8663 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 8664 FoldingSetNodeID ID; 8665 ID.AddInteger(4U); 8666 ID.AddInteger(VT1.getRawBits()); 8667 ID.AddInteger(VT2.getRawBits()); 8668 ID.AddInteger(VT3.getRawBits()); 8669 ID.AddInteger(VT4.getRawBits()); 8670 8671 void *IP = nullptr; 8672 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8673 if (!Result) { 8674 EVT *Array = Allocator.Allocate<EVT>(4); 8675 Array[0] = VT1; 8676 Array[1] = VT2; 8677 Array[2] = VT3; 8678 Array[3] = VT4; 8679 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 8680 VTListMap.InsertNode(Result, IP); 8681 } 8682 return Result->getSDVTList(); 8683 } 8684 8685 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 8686 unsigned NumVTs = VTs.size(); 8687 FoldingSetNodeID ID; 8688 ID.AddInteger(NumVTs); 8689 for (unsigned index = 0; index < NumVTs; index++) { 8690 ID.AddInteger(VTs[index].getRawBits()); 8691 } 8692 8693 void *IP = nullptr; 8694 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8695 if (!Result) { 8696 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 8697 llvm::copy(VTs, Array); 8698 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 8699 VTListMap.InsertNode(Result, IP); 8700 } 8701 return Result->getSDVTList(); 8702 } 8703 8704 8705 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 8706 /// specified operands. If the resultant node already exists in the DAG, 8707 /// this does not modify the specified node, instead it returns the node that 8708 /// already exists. If the resultant node does not exist in the DAG, the 8709 /// input node is returned. As a degenerate case, if you specify the same 8710 /// input operands as the node already has, the input node is returned. 8711 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 8712 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 8713 8714 // Check to see if there is no change. 8715 if (Op == N->getOperand(0)) return N; 8716 8717 // See if the modified node already exists. 8718 void *InsertPos = nullptr; 8719 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 8720 return Existing; 8721 8722 // Nope it doesn't. Remove the node from its current place in the maps. 8723 if (InsertPos) 8724 if (!RemoveNodeFromCSEMaps(N)) 8725 InsertPos = nullptr; 8726 8727 // Now we update the operands. 8728 N->OperandList[0].set(Op); 8729 8730 updateDivergence(N); 8731 // If this gets put into a CSE map, add it. 8732 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8733 return N; 8734 } 8735 8736 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 8737 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 8738 8739 // Check to see if there is no change. 8740 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 8741 return N; // No operands changed, just return the input node. 8742 8743 // See if the modified node already exists. 8744 void *InsertPos = nullptr; 8745 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 8746 return Existing; 8747 8748 // Nope it doesn't. Remove the node from its current place in the maps. 8749 if (InsertPos) 8750 if (!RemoveNodeFromCSEMaps(N)) 8751 InsertPos = nullptr; 8752 8753 // Now we update the operands. 8754 if (N->OperandList[0] != Op1) 8755 N->OperandList[0].set(Op1); 8756 if (N->OperandList[1] != Op2) 8757 N->OperandList[1].set(Op2); 8758 8759 updateDivergence(N); 8760 // If this gets put into a CSE map, add it. 8761 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8762 return N; 8763 } 8764 8765 SDNode *SelectionDAG:: 8766 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 8767 SDValue Ops[] = { Op1, Op2, Op3 }; 8768 return UpdateNodeOperands(N, Ops); 8769 } 8770 8771 SDNode *SelectionDAG:: 8772 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8773 SDValue Op3, SDValue Op4) { 8774 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 8775 return UpdateNodeOperands(N, Ops); 8776 } 8777 8778 SDNode *SelectionDAG:: 8779 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8780 SDValue Op3, SDValue Op4, SDValue Op5) { 8781 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 8782 return UpdateNodeOperands(N, Ops); 8783 } 8784 8785 SDNode *SelectionDAG:: 8786 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 8787 unsigned NumOps = Ops.size(); 8788 assert(N->getNumOperands() == NumOps && 8789 "Update with wrong number of operands"); 8790 8791 // If no operands changed just return the input node. 8792 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 8793 return N; 8794 8795 // See if the modified node already exists. 8796 void *InsertPos = nullptr; 8797 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8798 return Existing; 8799 8800 // Nope it doesn't. Remove the node from its current place in the maps. 8801 if (InsertPos) 8802 if (!RemoveNodeFromCSEMaps(N)) 8803 InsertPos = nullptr; 8804 8805 // Now we update the operands. 8806 for (unsigned i = 0; i != NumOps; ++i) 8807 if (N->OperandList[i] != Ops[i]) 8808 N->OperandList[i].set(Ops[i]); 8809 8810 updateDivergence(N); 8811 // If this gets put into a CSE map, add it. 8812 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8813 return N; 8814 } 8815 8816 /// DropOperands - Release the operands and set this node to have 8817 /// zero operands. 8818 void SDNode::DropOperands() { 8819 // Unlike the code in MorphNodeTo that does this, we don't need to 8820 // watch for dead nodes here. 8821 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8822 SDUse &Use = *I++; 8823 Use.set(SDValue()); 8824 } 8825 } 8826 8827 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8828 ArrayRef<MachineMemOperand *> NewMemRefs) { 8829 if (NewMemRefs.empty()) { 8830 N->clearMemRefs(); 8831 return; 8832 } 8833 8834 // Check if we can avoid allocating by storing a single reference directly. 8835 if (NewMemRefs.size() == 1) { 8836 N->MemRefs = NewMemRefs[0]; 8837 N->NumMemRefs = 1; 8838 return; 8839 } 8840 8841 MachineMemOperand **MemRefsBuffer = 8842 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8843 llvm::copy(NewMemRefs, MemRefsBuffer); 8844 N->MemRefs = MemRefsBuffer; 8845 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8846 } 8847 8848 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8849 /// machine opcode. 8850 /// 8851 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8852 EVT VT) { 8853 SDVTList VTs = getVTList(VT); 8854 return SelectNodeTo(N, MachineOpc, VTs, None); 8855 } 8856 8857 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8858 EVT VT, SDValue Op1) { 8859 SDVTList VTs = getVTList(VT); 8860 SDValue Ops[] = { Op1 }; 8861 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8862 } 8863 8864 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8865 EVT VT, SDValue Op1, 8866 SDValue Op2) { 8867 SDVTList VTs = getVTList(VT); 8868 SDValue Ops[] = { Op1, Op2 }; 8869 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8870 } 8871 8872 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8873 EVT VT, SDValue Op1, 8874 SDValue Op2, SDValue Op3) { 8875 SDVTList VTs = getVTList(VT); 8876 SDValue Ops[] = { Op1, Op2, Op3 }; 8877 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8878 } 8879 8880 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8881 EVT VT, ArrayRef<SDValue> Ops) { 8882 SDVTList VTs = getVTList(VT); 8883 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8884 } 8885 8886 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8887 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8888 SDVTList VTs = getVTList(VT1, VT2); 8889 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8890 } 8891 8892 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8893 EVT VT1, EVT VT2) { 8894 SDVTList VTs = getVTList(VT1, VT2); 8895 return SelectNodeTo(N, MachineOpc, VTs, None); 8896 } 8897 8898 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8899 EVT VT1, EVT VT2, EVT VT3, 8900 ArrayRef<SDValue> Ops) { 8901 SDVTList VTs = getVTList(VT1, VT2, VT3); 8902 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8903 } 8904 8905 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8906 EVT VT1, EVT VT2, 8907 SDValue Op1, SDValue Op2) { 8908 SDVTList VTs = getVTList(VT1, VT2); 8909 SDValue Ops[] = { Op1, Op2 }; 8910 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8911 } 8912 8913 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8914 SDVTList VTs,ArrayRef<SDValue> Ops) { 8915 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8916 // Reset the NodeID to -1. 8917 New->setNodeId(-1); 8918 if (New != N) { 8919 ReplaceAllUsesWith(N, New); 8920 RemoveDeadNode(N); 8921 } 8922 return New; 8923 } 8924 8925 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8926 /// the line number information on the merged node since it is not possible to 8927 /// preserve the information that operation is associated with multiple lines. 8928 /// This will make the debugger working better at -O0, were there is a higher 8929 /// probability having other instructions associated with that line. 8930 /// 8931 /// For IROrder, we keep the smaller of the two 8932 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8933 DebugLoc NLoc = N->getDebugLoc(); 8934 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8935 N->setDebugLoc(DebugLoc()); 8936 } 8937 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8938 N->setIROrder(Order); 8939 return N; 8940 } 8941 8942 /// MorphNodeTo - This *mutates* the specified node to have the specified 8943 /// return type, opcode, and operands. 8944 /// 8945 /// Note that MorphNodeTo returns the resultant node. If there is already a 8946 /// node of the specified opcode and operands, it returns that node instead of 8947 /// the current one. Note that the SDLoc need not be the same. 8948 /// 8949 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8950 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8951 /// node, and because it doesn't require CSE recalculation for any of 8952 /// the node's users. 8953 /// 8954 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8955 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8956 /// the legalizer which maintain worklists that would need to be updated when 8957 /// deleting things. 8958 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8959 SDVTList VTs, ArrayRef<SDValue> Ops) { 8960 // If an identical node already exists, use it. 8961 void *IP = nullptr; 8962 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8963 FoldingSetNodeID ID; 8964 AddNodeIDNode(ID, Opc, VTs, Ops); 8965 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8966 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8967 } 8968 8969 if (!RemoveNodeFromCSEMaps(N)) 8970 IP = nullptr; 8971 8972 // Start the morphing. 8973 N->NodeType = Opc; 8974 N->ValueList = VTs.VTs; 8975 N->NumValues = VTs.NumVTs; 8976 8977 // Clear the operands list, updating used nodes to remove this from their 8978 // use list. Keep track of any operands that become dead as a result. 8979 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8980 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8981 SDUse &Use = *I++; 8982 SDNode *Used = Use.getNode(); 8983 Use.set(SDValue()); 8984 if (Used->use_empty()) 8985 DeadNodeSet.insert(Used); 8986 } 8987 8988 // For MachineNode, initialize the memory references information. 8989 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8990 MN->clearMemRefs(); 8991 8992 // Swap for an appropriately sized array from the recycler. 8993 removeOperands(N); 8994 createOperands(N, Ops); 8995 8996 // Delete any nodes that are still dead after adding the uses for the 8997 // new operands. 8998 if (!DeadNodeSet.empty()) { 8999 SmallVector<SDNode *, 16> DeadNodes; 9000 for (SDNode *N : DeadNodeSet) 9001 if (N->use_empty()) 9002 DeadNodes.push_back(N); 9003 RemoveDeadNodes(DeadNodes); 9004 } 9005 9006 if (IP) 9007 CSEMap.InsertNode(N, IP); // Memoize the new node. 9008 return N; 9009 } 9010 9011 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9012 unsigned OrigOpc = Node->getOpcode(); 9013 unsigned NewOpc; 9014 switch (OrigOpc) { 9015 default: 9016 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9017 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9018 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9019 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9020 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9021 #include "llvm/IR/ConstrainedOps.def" 9022 } 9023 9024 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9025 9026 // We're taking this node out of the chain, so we need to re-link things. 9027 SDValue InputChain = Node->getOperand(0); 9028 SDValue OutputChain = SDValue(Node, 1); 9029 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9030 9031 SmallVector<SDValue, 3> Ops; 9032 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9033 Ops.push_back(Node->getOperand(i)); 9034 9035 SDVTList VTs = getVTList(Node->getValueType(0)); 9036 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9037 9038 // MorphNodeTo can operate in two ways: if an existing node with the 9039 // specified operands exists, it can just return it. Otherwise, it 9040 // updates the node in place to have the requested operands. 9041 if (Res == Node) { 9042 // If we updated the node in place, reset the node ID. To the isel, 9043 // this should be just like a newly allocated machine node. 9044 Res->setNodeId(-1); 9045 } else { 9046 ReplaceAllUsesWith(Node, Res); 9047 RemoveDeadNode(Node); 9048 } 9049 9050 return Res; 9051 } 9052 9053 /// getMachineNode - These are used for target selectors to create a new node 9054 /// with specified return type(s), MachineInstr opcode, and operands. 9055 /// 9056 /// Note that getMachineNode returns the resultant node. If there is already a 9057 /// node of the specified opcode and operands, it returns that node instead of 9058 /// the current one. 9059 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9060 EVT VT) { 9061 SDVTList VTs = getVTList(VT); 9062 return getMachineNode(Opcode, dl, VTs, None); 9063 } 9064 9065 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9066 EVT VT, SDValue Op1) { 9067 SDVTList VTs = getVTList(VT); 9068 SDValue Ops[] = { Op1 }; 9069 return getMachineNode(Opcode, dl, VTs, Ops); 9070 } 9071 9072 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9073 EVT VT, SDValue Op1, SDValue Op2) { 9074 SDVTList VTs = getVTList(VT); 9075 SDValue Ops[] = { Op1, Op2 }; 9076 return getMachineNode(Opcode, dl, VTs, Ops); 9077 } 9078 9079 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9080 EVT VT, SDValue Op1, SDValue Op2, 9081 SDValue Op3) { 9082 SDVTList VTs = getVTList(VT); 9083 SDValue Ops[] = { Op1, Op2, Op3 }; 9084 return getMachineNode(Opcode, dl, VTs, Ops); 9085 } 9086 9087 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9088 EVT VT, ArrayRef<SDValue> Ops) { 9089 SDVTList VTs = getVTList(VT); 9090 return getMachineNode(Opcode, dl, VTs, Ops); 9091 } 9092 9093 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9094 EVT VT1, EVT VT2, SDValue Op1, 9095 SDValue Op2) { 9096 SDVTList VTs = getVTList(VT1, VT2); 9097 SDValue Ops[] = { Op1, Op2 }; 9098 return getMachineNode(Opcode, dl, VTs, Ops); 9099 } 9100 9101 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9102 EVT VT1, EVT VT2, SDValue Op1, 9103 SDValue Op2, SDValue Op3) { 9104 SDVTList VTs = getVTList(VT1, VT2); 9105 SDValue Ops[] = { Op1, Op2, Op3 }; 9106 return getMachineNode(Opcode, dl, VTs, Ops); 9107 } 9108 9109 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9110 EVT VT1, EVT VT2, 9111 ArrayRef<SDValue> Ops) { 9112 SDVTList VTs = getVTList(VT1, VT2); 9113 return getMachineNode(Opcode, dl, VTs, Ops); 9114 } 9115 9116 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9117 EVT VT1, EVT VT2, EVT VT3, 9118 SDValue Op1, SDValue Op2) { 9119 SDVTList VTs = getVTList(VT1, VT2, VT3); 9120 SDValue Ops[] = { Op1, Op2 }; 9121 return getMachineNode(Opcode, dl, VTs, Ops); 9122 } 9123 9124 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9125 EVT VT1, EVT VT2, EVT VT3, 9126 SDValue Op1, SDValue Op2, 9127 SDValue Op3) { 9128 SDVTList VTs = getVTList(VT1, VT2, VT3); 9129 SDValue Ops[] = { Op1, Op2, Op3 }; 9130 return getMachineNode(Opcode, dl, VTs, Ops); 9131 } 9132 9133 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9134 EVT VT1, EVT VT2, EVT VT3, 9135 ArrayRef<SDValue> Ops) { 9136 SDVTList VTs = getVTList(VT1, VT2, VT3); 9137 return getMachineNode(Opcode, dl, VTs, Ops); 9138 } 9139 9140 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9141 ArrayRef<EVT> ResultTys, 9142 ArrayRef<SDValue> Ops) { 9143 SDVTList VTs = getVTList(ResultTys); 9144 return getMachineNode(Opcode, dl, VTs, Ops); 9145 } 9146 9147 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9148 SDVTList VTs, 9149 ArrayRef<SDValue> Ops) { 9150 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9151 MachineSDNode *N; 9152 void *IP = nullptr; 9153 9154 if (DoCSE) { 9155 FoldingSetNodeID ID; 9156 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9157 IP = nullptr; 9158 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9159 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9160 } 9161 } 9162 9163 // Allocate a new MachineSDNode. 9164 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9165 createOperands(N, Ops); 9166 9167 if (DoCSE) 9168 CSEMap.InsertNode(N, IP); 9169 9170 InsertNode(N); 9171 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9172 return N; 9173 } 9174 9175 /// getTargetExtractSubreg - A convenience function for creating 9176 /// TargetOpcode::EXTRACT_SUBREG nodes. 9177 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9178 SDValue Operand) { 9179 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9180 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9181 VT, Operand, SRIdxVal); 9182 return SDValue(Subreg, 0); 9183 } 9184 9185 /// getTargetInsertSubreg - A convenience function for creating 9186 /// TargetOpcode::INSERT_SUBREG nodes. 9187 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9188 SDValue Operand, SDValue Subreg) { 9189 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9190 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9191 VT, Operand, Subreg, SRIdxVal); 9192 return SDValue(Result, 0); 9193 } 9194 9195 /// getNodeIfExists - Get the specified node if it's already available, or 9196 /// else return NULL. 9197 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9198 ArrayRef<SDValue> Ops) { 9199 SDNodeFlags Flags; 9200 if (Inserter) 9201 Flags = Inserter->getFlags(); 9202 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9203 } 9204 9205 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9206 ArrayRef<SDValue> Ops, 9207 const SDNodeFlags Flags) { 9208 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9209 FoldingSetNodeID ID; 9210 AddNodeIDNode(ID, Opcode, VTList, Ops); 9211 void *IP = nullptr; 9212 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9213 E->intersectFlagsWith(Flags); 9214 return E; 9215 } 9216 } 9217 return nullptr; 9218 } 9219 9220 /// doesNodeExist - Check if a node exists without modifying its flags. 9221 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9222 ArrayRef<SDValue> Ops) { 9223 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9224 FoldingSetNodeID ID; 9225 AddNodeIDNode(ID, Opcode, VTList, Ops); 9226 void *IP = nullptr; 9227 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9228 return true; 9229 } 9230 return false; 9231 } 9232 9233 /// getDbgValue - Creates a SDDbgValue node. 9234 /// 9235 /// SDNode 9236 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9237 SDNode *N, unsigned R, bool IsIndirect, 9238 const DebugLoc &DL, unsigned O) { 9239 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9240 "Expected inlined-at fields to agree"); 9241 return new (DbgInfo->getAlloc()) 9242 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9243 {}, IsIndirect, DL, O, 9244 /*IsVariadic=*/false); 9245 } 9246 9247 /// Constant 9248 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9249 DIExpression *Expr, 9250 const Value *C, 9251 const DebugLoc &DL, unsigned O) { 9252 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9253 "Expected inlined-at fields to agree"); 9254 return new (DbgInfo->getAlloc()) 9255 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9256 /*IsIndirect=*/false, DL, O, 9257 /*IsVariadic=*/false); 9258 } 9259 9260 /// FrameIndex 9261 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9262 DIExpression *Expr, unsigned FI, 9263 bool IsIndirect, 9264 const DebugLoc &DL, 9265 unsigned O) { 9266 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9267 "Expected inlined-at fields to agree"); 9268 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9269 } 9270 9271 /// FrameIndex with dependencies 9272 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9273 DIExpression *Expr, unsigned FI, 9274 ArrayRef<SDNode *> Dependencies, 9275 bool IsIndirect, 9276 const DebugLoc &DL, 9277 unsigned O) { 9278 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9279 "Expected inlined-at fields to agree"); 9280 return new (DbgInfo->getAlloc()) 9281 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9282 Dependencies, IsIndirect, DL, O, 9283 /*IsVariadic=*/false); 9284 } 9285 9286 /// VReg 9287 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9288 unsigned VReg, bool IsIndirect, 9289 const DebugLoc &DL, unsigned O) { 9290 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9291 "Expected inlined-at fields to agree"); 9292 return new (DbgInfo->getAlloc()) 9293 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9294 {}, IsIndirect, DL, O, 9295 /*IsVariadic=*/false); 9296 } 9297 9298 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9299 ArrayRef<SDDbgOperand> Locs, 9300 ArrayRef<SDNode *> Dependencies, 9301 bool IsIndirect, const DebugLoc &DL, 9302 unsigned O, bool IsVariadic) { 9303 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9304 "Expected inlined-at fields to agree"); 9305 return new (DbgInfo->getAlloc()) 9306 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9307 DL, O, IsVariadic); 9308 } 9309 9310 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9311 unsigned OffsetInBits, unsigned SizeInBits, 9312 bool InvalidateDbg) { 9313 SDNode *FromNode = From.getNode(); 9314 SDNode *ToNode = To.getNode(); 9315 assert(FromNode && ToNode && "Can't modify dbg values"); 9316 9317 // PR35338 9318 // TODO: assert(From != To && "Redundant dbg value transfer"); 9319 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9320 if (From == To || FromNode == ToNode) 9321 return; 9322 9323 if (!FromNode->getHasDebugValue()) 9324 return; 9325 9326 SDDbgOperand FromLocOp = 9327 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9328 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9329 9330 SmallVector<SDDbgValue *, 2> ClonedDVs; 9331 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9332 if (Dbg->isInvalidated()) 9333 continue; 9334 9335 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9336 9337 // Create a new location ops vector that is equal to the old vector, but 9338 // with each instance of FromLocOp replaced with ToLocOp. 9339 bool Changed = false; 9340 auto NewLocOps = Dbg->copyLocationOps(); 9341 std::replace_if( 9342 NewLocOps.begin(), NewLocOps.end(), 9343 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9344 bool Match = Op == FromLocOp; 9345 Changed |= Match; 9346 return Match; 9347 }, 9348 ToLocOp); 9349 // Ignore this SDDbgValue if we didn't find a matching location. 9350 if (!Changed) 9351 continue; 9352 9353 DIVariable *Var = Dbg->getVariable(); 9354 auto *Expr = Dbg->getExpression(); 9355 // If a fragment is requested, update the expression. 9356 if (SizeInBits) { 9357 // When splitting a larger (e.g., sign-extended) value whose 9358 // lower bits are described with an SDDbgValue, do not attempt 9359 // to transfer the SDDbgValue to the upper bits. 9360 if (auto FI = Expr->getFragmentInfo()) 9361 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9362 continue; 9363 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9364 SizeInBits); 9365 if (!Fragment) 9366 continue; 9367 Expr = *Fragment; 9368 } 9369 9370 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9371 // Clone the SDDbgValue and move it to To. 9372 SDDbgValue *Clone = getDbgValueList( 9373 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9374 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9375 Dbg->isVariadic()); 9376 ClonedDVs.push_back(Clone); 9377 9378 if (InvalidateDbg) { 9379 // Invalidate value and indicate the SDDbgValue should not be emitted. 9380 Dbg->setIsInvalidated(); 9381 Dbg->setIsEmitted(); 9382 } 9383 } 9384 9385 for (SDDbgValue *Dbg : ClonedDVs) { 9386 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9387 "Transferred DbgValues should depend on the new SDNode"); 9388 AddDbgValue(Dbg, false); 9389 } 9390 } 9391 9392 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9393 if (!N.getHasDebugValue()) 9394 return; 9395 9396 SmallVector<SDDbgValue *, 2> ClonedDVs; 9397 for (auto DV : GetDbgValues(&N)) { 9398 if (DV->isInvalidated()) 9399 continue; 9400 switch (N.getOpcode()) { 9401 default: 9402 break; 9403 case ISD::ADD: 9404 SDValue N0 = N.getOperand(0); 9405 SDValue N1 = N.getOperand(1); 9406 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9407 isConstantIntBuildVectorOrConstantInt(N1)) { 9408 uint64_t Offset = N.getConstantOperandVal(1); 9409 9410 // Rewrite an ADD constant node into a DIExpression. Since we are 9411 // performing arithmetic to compute the variable's *value* in the 9412 // DIExpression, we need to mark the expression with a 9413 // DW_OP_stack_value. 9414 auto *DIExpr = DV->getExpression(); 9415 auto NewLocOps = DV->copyLocationOps(); 9416 bool Changed = false; 9417 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9418 // We're not given a ResNo to compare against because the whole 9419 // node is going away. We know that any ISD::ADD only has one 9420 // result, so we can assume any node match is using the result. 9421 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9422 NewLocOps[i].getSDNode() != &N) 9423 continue; 9424 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9425 SmallVector<uint64_t, 3> ExprOps; 9426 DIExpression::appendOffset(ExprOps, Offset); 9427 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9428 Changed = true; 9429 } 9430 (void)Changed; 9431 assert(Changed && "Salvage target doesn't use N"); 9432 9433 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9434 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9435 NewLocOps, AdditionalDependencies, 9436 DV->isIndirect(), DV->getDebugLoc(), 9437 DV->getOrder(), DV->isVariadic()); 9438 ClonedDVs.push_back(Clone); 9439 DV->setIsInvalidated(); 9440 DV->setIsEmitted(); 9441 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9442 N0.getNode()->dumprFull(this); 9443 dbgs() << " into " << *DIExpr << '\n'); 9444 } 9445 } 9446 } 9447 9448 for (SDDbgValue *Dbg : ClonedDVs) { 9449 assert(!Dbg->getSDNodes().empty() && 9450 "Salvaged DbgValue should depend on a new SDNode"); 9451 AddDbgValue(Dbg, false); 9452 } 9453 } 9454 9455 /// Creates a SDDbgLabel node. 9456 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9457 const DebugLoc &DL, unsigned O) { 9458 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9459 "Expected inlined-at fields to agree"); 9460 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9461 } 9462 9463 namespace { 9464 9465 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9466 /// pointed to by a use iterator is deleted, increment the use iterator 9467 /// so that it doesn't dangle. 9468 /// 9469 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9470 SDNode::use_iterator &UI; 9471 SDNode::use_iterator &UE; 9472 9473 void NodeDeleted(SDNode *N, SDNode *E) override { 9474 // Increment the iterator as needed. 9475 while (UI != UE && N == *UI) 9476 ++UI; 9477 } 9478 9479 public: 9480 RAUWUpdateListener(SelectionDAG &d, 9481 SDNode::use_iterator &ui, 9482 SDNode::use_iterator &ue) 9483 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9484 }; 9485 9486 } // end anonymous namespace 9487 9488 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9489 /// This can cause recursive merging of nodes in the DAG. 9490 /// 9491 /// This version assumes From has a single result value. 9492 /// 9493 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9494 SDNode *From = FromN.getNode(); 9495 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9496 "Cannot replace with this method!"); 9497 assert(From != To.getNode() && "Cannot replace uses of with self"); 9498 9499 // Preserve Debug Values 9500 transferDbgValues(FromN, To); 9501 9502 // Iterate over all the existing uses of From. New uses will be added 9503 // to the beginning of the use list, which we avoid visiting. 9504 // This specifically avoids visiting uses of From that arise while the 9505 // replacement is happening, because any such uses would be the result 9506 // of CSE: If an existing node looks like From after one of its operands 9507 // is replaced by To, we don't want to replace of all its users with To 9508 // too. See PR3018 for more info. 9509 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9510 RAUWUpdateListener Listener(*this, UI, UE); 9511 while (UI != UE) { 9512 SDNode *User = *UI; 9513 9514 // This node is about to morph, remove its old self from the CSE maps. 9515 RemoveNodeFromCSEMaps(User); 9516 9517 // A user can appear in a use list multiple times, and when this 9518 // happens the uses are usually next to each other in the list. 9519 // To help reduce the number of CSE recomputations, process all 9520 // the uses of this user that we can find this way. 9521 do { 9522 SDUse &Use = UI.getUse(); 9523 ++UI; 9524 Use.set(To); 9525 if (To->isDivergent() != From->isDivergent()) 9526 updateDivergence(User); 9527 } while (UI != UE && *UI == User); 9528 // Now that we have modified User, add it back to the CSE maps. If it 9529 // already exists there, recursively merge the results together. 9530 AddModifiedNodeToCSEMaps(User); 9531 } 9532 9533 // If we just RAUW'd the root, take note. 9534 if (FromN == getRoot()) 9535 setRoot(To); 9536 } 9537 9538 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9539 /// This can cause recursive merging of nodes in the DAG. 9540 /// 9541 /// This version assumes that for each value of From, there is a 9542 /// corresponding value in To in the same position with the same type. 9543 /// 9544 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9545 #ifndef NDEBUG 9546 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9547 assert((!From->hasAnyUseOfValue(i) || 9548 From->getValueType(i) == To->getValueType(i)) && 9549 "Cannot use this version of ReplaceAllUsesWith!"); 9550 #endif 9551 9552 // Handle the trivial case. 9553 if (From == To) 9554 return; 9555 9556 // Preserve Debug Info. Only do this if there's a use. 9557 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9558 if (From->hasAnyUseOfValue(i)) { 9559 assert((i < To->getNumValues()) && "Invalid To location"); 9560 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9561 } 9562 9563 // Iterate over just the existing users of From. See the comments in 9564 // the ReplaceAllUsesWith above. 9565 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9566 RAUWUpdateListener Listener(*this, UI, UE); 9567 while (UI != UE) { 9568 SDNode *User = *UI; 9569 9570 // This node is about to morph, remove its old self from the CSE maps. 9571 RemoveNodeFromCSEMaps(User); 9572 9573 // A user can appear in a use list multiple times, and when this 9574 // happens the uses are usually next to each other in the list. 9575 // To help reduce the number of CSE recomputations, process all 9576 // the uses of this user that we can find this way. 9577 do { 9578 SDUse &Use = UI.getUse(); 9579 ++UI; 9580 Use.setNode(To); 9581 if (To->isDivergent() != From->isDivergent()) 9582 updateDivergence(User); 9583 } while (UI != UE && *UI == User); 9584 9585 // Now that we have modified User, add it back to the CSE maps. If it 9586 // already exists there, recursively merge the results together. 9587 AddModifiedNodeToCSEMaps(User); 9588 } 9589 9590 // If we just RAUW'd the root, take note. 9591 if (From == getRoot().getNode()) 9592 setRoot(SDValue(To, getRoot().getResNo())); 9593 } 9594 9595 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9596 /// This can cause recursive merging of nodes in the DAG. 9597 /// 9598 /// This version can replace From with any result values. To must match the 9599 /// number and types of values returned by From. 9600 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9601 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9602 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9603 9604 // Preserve Debug Info. 9605 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9606 transferDbgValues(SDValue(From, i), To[i]); 9607 9608 // Iterate over just the existing users of From. See the comments in 9609 // the ReplaceAllUsesWith above. 9610 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9611 RAUWUpdateListener Listener(*this, UI, UE); 9612 while (UI != UE) { 9613 SDNode *User = *UI; 9614 9615 // This node is about to morph, remove its old self from the CSE maps. 9616 RemoveNodeFromCSEMaps(User); 9617 9618 // A user can appear in a use list multiple times, and when this happens the 9619 // uses are usually next to each other in the list. To help reduce the 9620 // number of CSE and divergence recomputations, process all the uses of this 9621 // user that we can find this way. 9622 bool To_IsDivergent = false; 9623 do { 9624 SDUse &Use = UI.getUse(); 9625 const SDValue &ToOp = To[Use.getResNo()]; 9626 ++UI; 9627 Use.set(ToOp); 9628 To_IsDivergent |= ToOp->isDivergent(); 9629 } while (UI != UE && *UI == User); 9630 9631 if (To_IsDivergent != From->isDivergent()) 9632 updateDivergence(User); 9633 9634 // Now that we have modified User, add it back to the CSE maps. If it 9635 // already exists there, recursively merge the results together. 9636 AddModifiedNodeToCSEMaps(User); 9637 } 9638 9639 // If we just RAUW'd the root, take note. 9640 if (From == getRoot().getNode()) 9641 setRoot(SDValue(To[getRoot().getResNo()])); 9642 } 9643 9644 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 9645 /// uses of other values produced by From.getNode() alone. The Deleted 9646 /// vector is handled the same way as for ReplaceAllUsesWith. 9647 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 9648 // Handle the really simple, really trivial case efficiently. 9649 if (From == To) return; 9650 9651 // Handle the simple, trivial, case efficiently. 9652 if (From.getNode()->getNumValues() == 1) { 9653 ReplaceAllUsesWith(From, To); 9654 return; 9655 } 9656 9657 // Preserve Debug Info. 9658 transferDbgValues(From, To); 9659 9660 // Iterate over just the existing users of From. See the comments in 9661 // the ReplaceAllUsesWith above. 9662 SDNode::use_iterator UI = From.getNode()->use_begin(), 9663 UE = From.getNode()->use_end(); 9664 RAUWUpdateListener Listener(*this, UI, UE); 9665 while (UI != UE) { 9666 SDNode *User = *UI; 9667 bool UserRemovedFromCSEMaps = false; 9668 9669 // A user can appear in a use list multiple times, and when this 9670 // happens the uses are usually next to each other in the list. 9671 // To help reduce the number of CSE recomputations, process all 9672 // the uses of this user that we can find this way. 9673 do { 9674 SDUse &Use = UI.getUse(); 9675 9676 // Skip uses of different values from the same node. 9677 if (Use.getResNo() != From.getResNo()) { 9678 ++UI; 9679 continue; 9680 } 9681 9682 // If this node hasn't been modified yet, it's still in the CSE maps, 9683 // so remove its old self from the CSE maps. 9684 if (!UserRemovedFromCSEMaps) { 9685 RemoveNodeFromCSEMaps(User); 9686 UserRemovedFromCSEMaps = true; 9687 } 9688 9689 ++UI; 9690 Use.set(To); 9691 if (To->isDivergent() != From->isDivergent()) 9692 updateDivergence(User); 9693 } while (UI != UE && *UI == User); 9694 // We are iterating over all uses of the From node, so if a use 9695 // doesn't use the specific value, no changes are made. 9696 if (!UserRemovedFromCSEMaps) 9697 continue; 9698 9699 // Now that we have modified User, add it back to the CSE maps. If it 9700 // already exists there, recursively merge the results together. 9701 AddModifiedNodeToCSEMaps(User); 9702 } 9703 9704 // If we just RAUW'd the root, take note. 9705 if (From == getRoot()) 9706 setRoot(To); 9707 } 9708 9709 namespace { 9710 9711 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 9712 /// to record information about a use. 9713 struct UseMemo { 9714 SDNode *User; 9715 unsigned Index; 9716 SDUse *Use; 9717 }; 9718 9719 /// operator< - Sort Memos by User. 9720 bool operator<(const UseMemo &L, const UseMemo &R) { 9721 return (intptr_t)L.User < (intptr_t)R.User; 9722 } 9723 9724 } // end anonymous namespace 9725 9726 bool SelectionDAG::calculateDivergence(SDNode *N) { 9727 if (TLI->isSDNodeAlwaysUniform(N)) { 9728 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 9729 "Conflicting divergence information!"); 9730 return false; 9731 } 9732 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 9733 return true; 9734 for (auto &Op : N->ops()) { 9735 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 9736 return true; 9737 } 9738 return false; 9739 } 9740 9741 void SelectionDAG::updateDivergence(SDNode *N) { 9742 SmallVector<SDNode *, 16> Worklist(1, N); 9743 do { 9744 N = Worklist.pop_back_val(); 9745 bool IsDivergent = calculateDivergence(N); 9746 if (N->SDNodeBits.IsDivergent != IsDivergent) { 9747 N->SDNodeBits.IsDivergent = IsDivergent; 9748 llvm::append_range(Worklist, N->uses()); 9749 } 9750 } while (!Worklist.empty()); 9751 } 9752 9753 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 9754 DenseMap<SDNode *, unsigned> Degree; 9755 Order.reserve(AllNodes.size()); 9756 for (auto &N : allnodes()) { 9757 unsigned NOps = N.getNumOperands(); 9758 Degree[&N] = NOps; 9759 if (0 == NOps) 9760 Order.push_back(&N); 9761 } 9762 for (size_t I = 0; I != Order.size(); ++I) { 9763 SDNode *N = Order[I]; 9764 for (auto U : N->uses()) { 9765 unsigned &UnsortedOps = Degree[U]; 9766 if (0 == --UnsortedOps) 9767 Order.push_back(U); 9768 } 9769 } 9770 } 9771 9772 #ifndef NDEBUG 9773 void SelectionDAG::VerifyDAGDivergence() { 9774 std::vector<SDNode *> TopoOrder; 9775 CreateTopologicalOrder(TopoOrder); 9776 for (auto *N : TopoOrder) { 9777 assert(calculateDivergence(N) == N->isDivergent() && 9778 "Divergence bit inconsistency detected"); 9779 } 9780 } 9781 #endif 9782 9783 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 9784 /// uses of other values produced by From.getNode() alone. The same value 9785 /// may appear in both the From and To list. The Deleted vector is 9786 /// handled the same way as for ReplaceAllUsesWith. 9787 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 9788 const SDValue *To, 9789 unsigned Num){ 9790 // Handle the simple, trivial case efficiently. 9791 if (Num == 1) 9792 return ReplaceAllUsesOfValueWith(*From, *To); 9793 9794 transferDbgValues(*From, *To); 9795 9796 // Read up all the uses and make records of them. This helps 9797 // processing new uses that are introduced during the 9798 // replacement process. 9799 SmallVector<UseMemo, 4> Uses; 9800 for (unsigned i = 0; i != Num; ++i) { 9801 unsigned FromResNo = From[i].getResNo(); 9802 SDNode *FromNode = From[i].getNode(); 9803 for (SDNode::use_iterator UI = FromNode->use_begin(), 9804 E = FromNode->use_end(); UI != E; ++UI) { 9805 SDUse &Use = UI.getUse(); 9806 if (Use.getResNo() == FromResNo) { 9807 UseMemo Memo = { *UI, i, &Use }; 9808 Uses.push_back(Memo); 9809 } 9810 } 9811 } 9812 9813 // Sort the uses, so that all the uses from a given User are together. 9814 llvm::sort(Uses); 9815 9816 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 9817 UseIndex != UseIndexEnd; ) { 9818 // We know that this user uses some value of From. If it is the right 9819 // value, update it. 9820 SDNode *User = Uses[UseIndex].User; 9821 9822 // This node is about to morph, remove its old self from the CSE maps. 9823 RemoveNodeFromCSEMaps(User); 9824 9825 // The Uses array is sorted, so all the uses for a given User 9826 // are next to each other in the list. 9827 // To help reduce the number of CSE recomputations, process all 9828 // the uses of this user that we can find this way. 9829 do { 9830 unsigned i = Uses[UseIndex].Index; 9831 SDUse &Use = *Uses[UseIndex].Use; 9832 ++UseIndex; 9833 9834 Use.set(To[i]); 9835 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 9836 9837 // Now that we have modified User, add it back to the CSE maps. If it 9838 // already exists there, recursively merge the results together. 9839 AddModifiedNodeToCSEMaps(User); 9840 } 9841 } 9842 9843 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 9844 /// based on their topological order. It returns the maximum id and a vector 9845 /// of the SDNodes* in assigned order by reference. 9846 unsigned SelectionDAG::AssignTopologicalOrder() { 9847 unsigned DAGSize = 0; 9848 9849 // SortedPos tracks the progress of the algorithm. Nodes before it are 9850 // sorted, nodes after it are unsorted. When the algorithm completes 9851 // it is at the end of the list. 9852 allnodes_iterator SortedPos = allnodes_begin(); 9853 9854 // Visit all the nodes. Move nodes with no operands to the front of 9855 // the list immediately. Annotate nodes that do have operands with their 9856 // operand count. Before we do this, the Node Id fields of the nodes 9857 // may contain arbitrary values. After, the Node Id fields for nodes 9858 // before SortedPos will contain the topological sort index, and the 9859 // Node Id fields for nodes At SortedPos and after will contain the 9860 // count of outstanding operands. 9861 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 9862 checkForCycles(&N, this); 9863 unsigned Degree = N.getNumOperands(); 9864 if (Degree == 0) { 9865 // A node with no uses, add it to the result array immediately. 9866 N.setNodeId(DAGSize++); 9867 allnodes_iterator Q(&N); 9868 if (Q != SortedPos) 9869 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 9870 assert(SortedPos != AllNodes.end() && "Overran node list"); 9871 ++SortedPos; 9872 } else { 9873 // Temporarily use the Node Id as scratch space for the degree count. 9874 N.setNodeId(Degree); 9875 } 9876 } 9877 9878 // Visit all the nodes. As we iterate, move nodes into sorted order, 9879 // such that by the time the end is reached all nodes will be sorted. 9880 for (SDNode &Node : allnodes()) { 9881 SDNode *N = &Node; 9882 checkForCycles(N, this); 9883 // N is in sorted position, so all its uses have one less operand 9884 // that needs to be sorted. 9885 for (SDNode *P : N->uses()) { 9886 unsigned Degree = P->getNodeId(); 9887 assert(Degree != 0 && "Invalid node degree"); 9888 --Degree; 9889 if (Degree == 0) { 9890 // All of P's operands are sorted, so P may sorted now. 9891 P->setNodeId(DAGSize++); 9892 if (P->getIterator() != SortedPos) 9893 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9894 assert(SortedPos != AllNodes.end() && "Overran node list"); 9895 ++SortedPos; 9896 } else { 9897 // Update P's outstanding operand count. 9898 P->setNodeId(Degree); 9899 } 9900 } 9901 if (Node.getIterator() == SortedPos) { 9902 #ifndef NDEBUG 9903 allnodes_iterator I(N); 9904 SDNode *S = &*++I; 9905 dbgs() << "Overran sorted position:\n"; 9906 S->dumprFull(this); dbgs() << "\n"; 9907 dbgs() << "Checking if this is due to cycles\n"; 9908 checkForCycles(this, true); 9909 #endif 9910 llvm_unreachable(nullptr); 9911 } 9912 } 9913 9914 assert(SortedPos == AllNodes.end() && 9915 "Topological sort incomplete!"); 9916 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9917 "First node in topological sort is not the entry token!"); 9918 assert(AllNodes.front().getNodeId() == 0 && 9919 "First node in topological sort has non-zero id!"); 9920 assert(AllNodes.front().getNumOperands() == 0 && 9921 "First node in topological sort has operands!"); 9922 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9923 "Last node in topologic sort has unexpected id!"); 9924 assert(AllNodes.back().use_empty() && 9925 "Last node in topologic sort has users!"); 9926 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9927 return DAGSize; 9928 } 9929 9930 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9931 /// value is produced by SD. 9932 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 9933 for (SDNode *SD : DB->getSDNodes()) { 9934 if (!SD) 9935 continue; 9936 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9937 SD->setHasDebugValue(true); 9938 } 9939 DbgInfo->add(DB, isParameter); 9940 } 9941 9942 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 9943 9944 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9945 SDValue NewMemOpChain) { 9946 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9947 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9948 // The new memory operation must have the same position as the old load in 9949 // terms of memory dependency. Create a TokenFactor for the old load and new 9950 // memory operation and update uses of the old load's output chain to use that 9951 // TokenFactor. 9952 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9953 return NewMemOpChain; 9954 9955 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9956 OldChain, NewMemOpChain); 9957 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9958 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9959 return TokenFactor; 9960 } 9961 9962 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9963 SDValue NewMemOp) { 9964 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9965 SDValue OldChain = SDValue(OldLoad, 1); 9966 SDValue NewMemOpChain = NewMemOp.getValue(1); 9967 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9968 } 9969 9970 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9971 Function **OutFunction) { 9972 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9973 9974 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9975 auto *Module = MF->getFunction().getParent(); 9976 auto *Function = Module->getFunction(Symbol); 9977 9978 if (OutFunction != nullptr) 9979 *OutFunction = Function; 9980 9981 if (Function != nullptr) { 9982 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9983 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9984 } 9985 9986 std::string ErrorStr; 9987 raw_string_ostream ErrorFormatter(ErrorStr); 9988 ErrorFormatter << "Undefined external symbol "; 9989 ErrorFormatter << '"' << Symbol << '"'; 9990 report_fatal_error(Twine(ErrorFormatter.str())); 9991 } 9992 9993 //===----------------------------------------------------------------------===// 9994 // SDNode Class 9995 //===----------------------------------------------------------------------===// 9996 9997 bool llvm::isNullConstant(SDValue V) { 9998 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9999 return Const != nullptr && Const->isZero(); 10000 } 10001 10002 bool llvm::isNullFPConstant(SDValue V) { 10003 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10004 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10005 } 10006 10007 bool llvm::isAllOnesConstant(SDValue V) { 10008 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10009 return Const != nullptr && Const->isAllOnes(); 10010 } 10011 10012 bool llvm::isOneConstant(SDValue V) { 10013 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10014 return Const != nullptr && Const->isOne(); 10015 } 10016 10017 SDValue llvm::peekThroughBitcasts(SDValue V) { 10018 while (V.getOpcode() == ISD::BITCAST) 10019 V = V.getOperand(0); 10020 return V; 10021 } 10022 10023 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10024 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10025 V = V.getOperand(0); 10026 return V; 10027 } 10028 10029 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10030 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10031 V = V.getOperand(0); 10032 return V; 10033 } 10034 10035 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10036 if (V.getOpcode() != ISD::XOR) 10037 return false; 10038 V = peekThroughBitcasts(V.getOperand(1)); 10039 unsigned NumBits = V.getScalarValueSizeInBits(); 10040 ConstantSDNode *C = 10041 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10042 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10043 } 10044 10045 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10046 bool AllowTruncation) { 10047 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10048 return CN; 10049 10050 // SplatVectors can truncate their operands. Ignore that case here unless 10051 // AllowTruncation is set. 10052 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10053 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10054 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10055 EVT CVT = CN->getValueType(0); 10056 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10057 if (AllowTruncation || CVT == VecEltVT) 10058 return CN; 10059 } 10060 } 10061 10062 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10063 BitVector UndefElements; 10064 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10065 10066 // BuildVectors can truncate their operands. Ignore that case here unless 10067 // AllowTruncation is set. 10068 if (CN && (UndefElements.none() || AllowUndefs)) { 10069 EVT CVT = CN->getValueType(0); 10070 EVT NSVT = N.getValueType().getScalarType(); 10071 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10072 if (AllowTruncation || (CVT == NSVT)) 10073 return CN; 10074 } 10075 } 10076 10077 return nullptr; 10078 } 10079 10080 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10081 bool AllowUndefs, 10082 bool AllowTruncation) { 10083 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10084 return CN; 10085 10086 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10087 BitVector UndefElements; 10088 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10089 10090 // BuildVectors can truncate their operands. Ignore that case here unless 10091 // AllowTruncation is set. 10092 if (CN && (UndefElements.none() || AllowUndefs)) { 10093 EVT CVT = CN->getValueType(0); 10094 EVT NSVT = N.getValueType().getScalarType(); 10095 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10096 if (AllowTruncation || (CVT == NSVT)) 10097 return CN; 10098 } 10099 } 10100 10101 return nullptr; 10102 } 10103 10104 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10105 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10106 return CN; 10107 10108 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10109 BitVector UndefElements; 10110 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10111 if (CN && (UndefElements.none() || AllowUndefs)) 10112 return CN; 10113 } 10114 10115 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10116 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10117 return CN; 10118 10119 return nullptr; 10120 } 10121 10122 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10123 const APInt &DemandedElts, 10124 bool AllowUndefs) { 10125 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10126 return CN; 10127 10128 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10129 BitVector UndefElements; 10130 ConstantFPSDNode *CN = 10131 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10132 if (CN && (UndefElements.none() || AllowUndefs)) 10133 return CN; 10134 } 10135 10136 return nullptr; 10137 } 10138 10139 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10140 // TODO: may want to use peekThroughBitcast() here. 10141 ConstantSDNode *C = 10142 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10143 return C && C->isZero(); 10144 } 10145 10146 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10147 // TODO: may want to use peekThroughBitcast() here. 10148 unsigned BitWidth = N.getScalarValueSizeInBits(); 10149 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10150 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10151 } 10152 10153 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10154 N = peekThroughBitcasts(N); 10155 unsigned BitWidth = N.getScalarValueSizeInBits(); 10156 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10157 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10158 } 10159 10160 HandleSDNode::~HandleSDNode() { 10161 DropOperands(); 10162 } 10163 10164 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10165 const DebugLoc &DL, 10166 const GlobalValue *GA, EVT VT, 10167 int64_t o, unsigned TF) 10168 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10169 TheGlobal = GA; 10170 } 10171 10172 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10173 EVT VT, unsigned SrcAS, 10174 unsigned DestAS) 10175 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10176 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10177 10178 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10179 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10180 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10181 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10182 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10183 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10184 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10185 10186 // We check here that the size of the memory operand fits within the size of 10187 // the MMO. This is because the MMO might indicate only a possible address 10188 // range instead of specifying the affected memory addresses precisely. 10189 // TODO: Make MachineMemOperands aware of scalable vectors. 10190 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10191 "Size mismatch!"); 10192 } 10193 10194 /// Profile - Gather unique data for the node. 10195 /// 10196 void SDNode::Profile(FoldingSetNodeID &ID) const { 10197 AddNodeIDNode(ID, this); 10198 } 10199 10200 namespace { 10201 10202 struct EVTArray { 10203 std::vector<EVT> VTs; 10204 10205 EVTArray() { 10206 VTs.reserve(MVT::VALUETYPE_SIZE); 10207 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10208 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10209 } 10210 }; 10211 10212 } // end anonymous namespace 10213 10214 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10215 static ManagedStatic<EVTArray> SimpleVTArray; 10216 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10217 10218 /// getValueTypeList - Return a pointer to the specified value type. 10219 /// 10220 const EVT *SDNode::getValueTypeList(EVT VT) { 10221 if (VT.isExtended()) { 10222 sys::SmartScopedLock<true> Lock(*VTMutex); 10223 return &(*EVTs->insert(VT).first); 10224 } 10225 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10226 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10227 } 10228 10229 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10230 /// indicated value. This method ignores uses of other values defined by this 10231 /// operation. 10232 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10233 assert(Value < getNumValues() && "Bad value!"); 10234 10235 // TODO: Only iterate over uses of a given value of the node 10236 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10237 if (UI.getUse().getResNo() == Value) { 10238 if (NUses == 0) 10239 return false; 10240 --NUses; 10241 } 10242 } 10243 10244 // Found exactly the right number of uses? 10245 return NUses == 0; 10246 } 10247 10248 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10249 /// value. This method ignores uses of other values defined by this operation. 10250 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10251 assert(Value < getNumValues() && "Bad value!"); 10252 10253 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10254 if (UI.getUse().getResNo() == Value) 10255 return true; 10256 10257 return false; 10258 } 10259 10260 /// isOnlyUserOf - Return true if this node is the only use of N. 10261 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10262 bool Seen = false; 10263 for (const SDNode *User : N->uses()) { 10264 if (User == this) 10265 Seen = true; 10266 else 10267 return false; 10268 } 10269 10270 return Seen; 10271 } 10272 10273 /// Return true if the only users of N are contained in Nodes. 10274 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10275 bool Seen = false; 10276 for (const SDNode *User : N->uses()) { 10277 if (llvm::is_contained(Nodes, User)) 10278 Seen = true; 10279 else 10280 return false; 10281 } 10282 10283 return Seen; 10284 } 10285 10286 /// isOperand - Return true if this node is an operand of N. 10287 bool SDValue::isOperandOf(const SDNode *N) const { 10288 return is_contained(N->op_values(), *this); 10289 } 10290 10291 bool SDNode::isOperandOf(const SDNode *N) const { 10292 return any_of(N->op_values(), 10293 [this](SDValue Op) { return this == Op.getNode(); }); 10294 } 10295 10296 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10297 /// be a chain) reaches the specified operand without crossing any 10298 /// side-effecting instructions on any chain path. In practice, this looks 10299 /// through token factors and non-volatile loads. In order to remain efficient, 10300 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10301 /// 10302 /// Note that we only need to examine chains when we're searching for 10303 /// side-effects; SelectionDAG requires that all side-effects are represented 10304 /// by chains, even if another operand would force a specific ordering. This 10305 /// constraint is necessary to allow transformations like splitting loads. 10306 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10307 unsigned Depth) const { 10308 if (*this == Dest) return true; 10309 10310 // Don't search too deeply, we just want to be able to see through 10311 // TokenFactor's etc. 10312 if (Depth == 0) return false; 10313 10314 // If this is a token factor, all inputs to the TF happen in parallel. 10315 if (getOpcode() == ISD::TokenFactor) { 10316 // First, try a shallow search. 10317 if (is_contained((*this)->ops(), Dest)) { 10318 // We found the chain we want as an operand of this TokenFactor. 10319 // Essentially, we reach the chain without side-effects if we could 10320 // serialize the TokenFactor into a simple chain of operations with 10321 // Dest as the last operation. This is automatically true if the 10322 // chain has one use: there are no other ordering constraints. 10323 // If the chain has more than one use, we give up: some other 10324 // use of Dest might force a side-effect between Dest and the current 10325 // node. 10326 if (Dest.hasOneUse()) 10327 return true; 10328 } 10329 // Next, try a deep search: check whether every operand of the TokenFactor 10330 // reaches Dest. 10331 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10332 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10333 }); 10334 } 10335 10336 // Loads don't have side effects, look through them. 10337 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10338 if (Ld->isUnordered()) 10339 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10340 } 10341 return false; 10342 } 10343 10344 bool SDNode::hasPredecessor(const SDNode *N) const { 10345 SmallPtrSet<const SDNode *, 32> Visited; 10346 SmallVector<const SDNode *, 16> Worklist; 10347 Worklist.push_back(this); 10348 return hasPredecessorHelper(N, Visited, Worklist); 10349 } 10350 10351 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10352 this->Flags.intersectWith(Flags); 10353 } 10354 10355 SDValue 10356 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10357 ArrayRef<ISD::NodeType> CandidateBinOps, 10358 bool AllowPartials) { 10359 // The pattern must end in an extract from index 0. 10360 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10361 !isNullConstant(Extract->getOperand(1))) 10362 return SDValue(); 10363 10364 // Match against one of the candidate binary ops. 10365 SDValue Op = Extract->getOperand(0); 10366 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10367 return Op.getOpcode() == unsigned(BinOp); 10368 })) 10369 return SDValue(); 10370 10371 // Floating-point reductions may require relaxed constraints on the final step 10372 // of the reduction because they may reorder intermediate operations. 10373 unsigned CandidateBinOp = Op.getOpcode(); 10374 if (Op.getValueType().isFloatingPoint()) { 10375 SDNodeFlags Flags = Op->getFlags(); 10376 switch (CandidateBinOp) { 10377 case ISD::FADD: 10378 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10379 return SDValue(); 10380 break; 10381 default: 10382 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10383 } 10384 } 10385 10386 // Matching failed - attempt to see if we did enough stages that a partial 10387 // reduction from a subvector is possible. 10388 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10389 if (!AllowPartials || !Op) 10390 return SDValue(); 10391 EVT OpVT = Op.getValueType(); 10392 EVT OpSVT = OpVT.getScalarType(); 10393 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10394 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10395 return SDValue(); 10396 BinOp = (ISD::NodeType)CandidateBinOp; 10397 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10398 getVectorIdxConstant(0, SDLoc(Op))); 10399 }; 10400 10401 // At each stage, we're looking for something that looks like: 10402 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10403 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10404 // i32 undef, i32 undef, i32 undef, i32 undef> 10405 // %a = binop <8 x i32> %op, %s 10406 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10407 // we expect something like: 10408 // <4,5,6,7,u,u,u,u> 10409 // <2,3,u,u,u,u,u,u> 10410 // <1,u,u,u,u,u,u,u> 10411 // While a partial reduction match would be: 10412 // <2,3,u,u,u,u,u,u> 10413 // <1,u,u,u,u,u,u,u> 10414 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10415 SDValue PrevOp; 10416 for (unsigned i = 0; i < Stages; ++i) { 10417 unsigned MaskEnd = (1 << i); 10418 10419 if (Op.getOpcode() != CandidateBinOp) 10420 return PartialReduction(PrevOp, MaskEnd); 10421 10422 SDValue Op0 = Op.getOperand(0); 10423 SDValue Op1 = Op.getOperand(1); 10424 10425 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10426 if (Shuffle) { 10427 Op = Op1; 10428 } else { 10429 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10430 Op = Op0; 10431 } 10432 10433 // The first operand of the shuffle should be the same as the other operand 10434 // of the binop. 10435 if (!Shuffle || Shuffle->getOperand(0) != Op) 10436 return PartialReduction(PrevOp, MaskEnd); 10437 10438 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10439 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10440 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10441 return PartialReduction(PrevOp, MaskEnd); 10442 10443 PrevOp = Op; 10444 } 10445 10446 // Handle subvector reductions, which tend to appear after the shuffle 10447 // reduction stages. 10448 while (Op.getOpcode() == CandidateBinOp) { 10449 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10450 SDValue Op0 = Op.getOperand(0); 10451 SDValue Op1 = Op.getOperand(1); 10452 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10453 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10454 Op0.getOperand(0) != Op1.getOperand(0)) 10455 break; 10456 SDValue Src = Op0.getOperand(0); 10457 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10458 if (NumSrcElts != (2 * NumElts)) 10459 break; 10460 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10461 Op1.getConstantOperandAPInt(1) == NumElts) && 10462 !(Op1.getConstantOperandAPInt(1) == 0 && 10463 Op0.getConstantOperandAPInt(1) == NumElts)) 10464 break; 10465 Op = Src; 10466 } 10467 10468 BinOp = (ISD::NodeType)CandidateBinOp; 10469 return Op; 10470 } 10471 10472 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10473 assert(N->getNumValues() == 1 && 10474 "Can't unroll a vector with multiple results!"); 10475 10476 EVT VT = N->getValueType(0); 10477 unsigned NE = VT.getVectorNumElements(); 10478 EVT EltVT = VT.getVectorElementType(); 10479 SDLoc dl(N); 10480 10481 SmallVector<SDValue, 8> Scalars; 10482 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10483 10484 // If ResNE is 0, fully unroll the vector op. 10485 if (ResNE == 0) 10486 ResNE = NE; 10487 else if (NE > ResNE) 10488 NE = ResNE; 10489 10490 unsigned i; 10491 for (i= 0; i != NE; ++i) { 10492 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10493 SDValue Operand = N->getOperand(j); 10494 EVT OperandVT = Operand.getValueType(); 10495 if (OperandVT.isVector()) { 10496 // A vector operand; extract a single element. 10497 EVT OperandEltVT = OperandVT.getVectorElementType(); 10498 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10499 Operand, getVectorIdxConstant(i, dl)); 10500 } else { 10501 // A scalar operand; just use it as is. 10502 Operands[j] = Operand; 10503 } 10504 } 10505 10506 switch (N->getOpcode()) { 10507 default: { 10508 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10509 N->getFlags())); 10510 break; 10511 } 10512 case ISD::VSELECT: 10513 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10514 break; 10515 case ISD::SHL: 10516 case ISD::SRA: 10517 case ISD::SRL: 10518 case ISD::ROTL: 10519 case ISD::ROTR: 10520 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10521 getShiftAmountOperand(Operands[0].getValueType(), 10522 Operands[1]))); 10523 break; 10524 case ISD::SIGN_EXTEND_INREG: { 10525 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10526 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10527 Operands[0], 10528 getValueType(ExtVT))); 10529 } 10530 } 10531 } 10532 10533 for (; i < ResNE; ++i) 10534 Scalars.push_back(getUNDEF(EltVT)); 10535 10536 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10537 return getBuildVector(VecVT, dl, Scalars); 10538 } 10539 10540 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10541 SDNode *N, unsigned ResNE) { 10542 unsigned Opcode = N->getOpcode(); 10543 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10544 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10545 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10546 "Expected an overflow opcode"); 10547 10548 EVT ResVT = N->getValueType(0); 10549 EVT OvVT = N->getValueType(1); 10550 EVT ResEltVT = ResVT.getVectorElementType(); 10551 EVT OvEltVT = OvVT.getVectorElementType(); 10552 SDLoc dl(N); 10553 10554 // If ResNE is 0, fully unroll the vector op. 10555 unsigned NE = ResVT.getVectorNumElements(); 10556 if (ResNE == 0) 10557 ResNE = NE; 10558 else if (NE > ResNE) 10559 NE = ResNE; 10560 10561 SmallVector<SDValue, 8> LHSScalars; 10562 SmallVector<SDValue, 8> RHSScalars; 10563 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10564 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10565 10566 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10567 SDVTList VTs = getVTList(ResEltVT, SVT); 10568 SmallVector<SDValue, 8> ResScalars; 10569 SmallVector<SDValue, 8> OvScalars; 10570 for (unsigned i = 0; i < NE; ++i) { 10571 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10572 SDValue Ov = 10573 getSelect(dl, OvEltVT, Res.getValue(1), 10574 getBoolConstant(true, dl, OvEltVT, ResVT), 10575 getConstant(0, dl, OvEltVT)); 10576 10577 ResScalars.push_back(Res); 10578 OvScalars.push_back(Ov); 10579 } 10580 10581 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10582 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10583 10584 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10585 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10586 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10587 getBuildVector(NewOvVT, dl, OvScalars)); 10588 } 10589 10590 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10591 LoadSDNode *Base, 10592 unsigned Bytes, 10593 int Dist) const { 10594 if (LD->isVolatile() || Base->isVolatile()) 10595 return false; 10596 // TODO: probably too restrictive for atomics, revisit 10597 if (!LD->isSimple()) 10598 return false; 10599 if (LD->isIndexed() || Base->isIndexed()) 10600 return false; 10601 if (LD->getChain() != Base->getChain()) 10602 return false; 10603 EVT VT = LD->getValueType(0); 10604 if (VT.getSizeInBits() / 8 != Bytes) 10605 return false; 10606 10607 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10608 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10609 10610 int64_t Offset = 0; 10611 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 10612 return (Dist * Bytes == Offset); 10613 return false; 10614 } 10615 10616 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 10617 /// if it cannot be inferred. 10618 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 10619 // If this is a GlobalAddress + cst, return the alignment. 10620 const GlobalValue *GV = nullptr; 10621 int64_t GVOffset = 0; 10622 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 10623 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 10624 KnownBits Known(PtrWidth); 10625 llvm::computeKnownBits(GV, Known, getDataLayout()); 10626 unsigned AlignBits = Known.countMinTrailingZeros(); 10627 if (AlignBits) 10628 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 10629 } 10630 10631 // If this is a direct reference to a stack slot, use information about the 10632 // stack slot's alignment. 10633 int FrameIdx = INT_MIN; 10634 int64_t FrameOffset = 0; 10635 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 10636 FrameIdx = FI->getIndex(); 10637 } else if (isBaseWithConstantOffset(Ptr) && 10638 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 10639 // Handle FI+Cst 10640 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 10641 FrameOffset = Ptr.getConstantOperandVal(1); 10642 } 10643 10644 if (FrameIdx != INT_MIN) { 10645 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 10646 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 10647 } 10648 10649 return None; 10650 } 10651 10652 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 10653 /// which is split (or expanded) into two not necessarily identical pieces. 10654 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 10655 // Currently all types are split in half. 10656 EVT LoVT, HiVT; 10657 if (!VT.isVector()) 10658 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 10659 else 10660 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 10661 10662 return std::make_pair(LoVT, HiVT); 10663 } 10664 10665 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 10666 /// type, dependent on an enveloping VT that has been split into two identical 10667 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 10668 std::pair<EVT, EVT> 10669 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 10670 bool *HiIsEmpty) const { 10671 EVT EltTp = VT.getVectorElementType(); 10672 // Examples: 10673 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 10674 // custom VL=9 with enveloping VL=8/8 yields 8/1 10675 // custom VL=10 with enveloping VL=8/8 yields 8/2 10676 // etc. 10677 ElementCount VTNumElts = VT.getVectorElementCount(); 10678 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 10679 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 10680 "Mixing fixed width and scalable vectors when enveloping a type"); 10681 EVT LoVT, HiVT; 10682 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 10683 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 10684 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 10685 *HiIsEmpty = false; 10686 } else { 10687 // Flag that hi type has zero storage size, but return split envelop type 10688 // (this would be easier if vector types with zero elements were allowed). 10689 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 10690 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 10691 *HiIsEmpty = true; 10692 } 10693 return std::make_pair(LoVT, HiVT); 10694 } 10695 10696 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 10697 /// low/high part. 10698 std::pair<SDValue, SDValue> 10699 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 10700 const EVT &HiVT) { 10701 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 10702 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 10703 "Splitting vector with an invalid mixture of fixed and scalable " 10704 "vector types"); 10705 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 10706 N.getValueType().getVectorMinNumElements() && 10707 "More vector elements requested than available!"); 10708 SDValue Lo, Hi; 10709 Lo = 10710 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 10711 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 10712 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 10713 // IDX with the runtime scaling factor of the result vector type. For 10714 // fixed-width result vectors, that runtime scaling factor is 1. 10715 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 10716 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 10717 return std::make_pair(Lo, Hi); 10718 } 10719 10720 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 10721 const SDLoc &DL) { 10722 // Split the vector length parameter. 10723 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 10724 EVT VT = N.getValueType(); 10725 assert(VecVT.getVectorElementCount().isKnownEven() && 10726 "Expecting the mask to be an evenly-sized vector"); 10727 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 10728 SDValue HalfNumElts = 10729 VecVT.isFixedLengthVector() 10730 ? getConstant(HalfMinNumElts, DL, VT) 10731 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 10732 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 10733 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 10734 return std::make_pair(Lo, Hi); 10735 } 10736 10737 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 10738 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 10739 EVT VT = N.getValueType(); 10740 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 10741 NextPowerOf2(VT.getVectorNumElements())); 10742 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 10743 getVectorIdxConstant(0, DL)); 10744 } 10745 10746 void SelectionDAG::ExtractVectorElements(SDValue Op, 10747 SmallVectorImpl<SDValue> &Args, 10748 unsigned Start, unsigned Count, 10749 EVT EltVT) { 10750 EVT VT = Op.getValueType(); 10751 if (Count == 0) 10752 Count = VT.getVectorNumElements(); 10753 if (EltVT == EVT()) 10754 EltVT = VT.getVectorElementType(); 10755 SDLoc SL(Op); 10756 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 10757 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 10758 getVectorIdxConstant(i, SL))); 10759 } 10760 } 10761 10762 // getAddressSpace - Return the address space this GlobalAddress belongs to. 10763 unsigned GlobalAddressSDNode::getAddressSpace() const { 10764 return getGlobal()->getType()->getAddressSpace(); 10765 } 10766 10767 Type *ConstantPoolSDNode::getType() const { 10768 if (isMachineConstantPoolEntry()) 10769 return Val.MachineCPVal->getType(); 10770 return Val.ConstVal->getType(); 10771 } 10772 10773 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 10774 unsigned &SplatBitSize, 10775 bool &HasAnyUndefs, 10776 unsigned MinSplatBits, 10777 bool IsBigEndian) const { 10778 EVT VT = getValueType(0); 10779 assert(VT.isVector() && "Expected a vector type"); 10780 unsigned VecWidth = VT.getSizeInBits(); 10781 if (MinSplatBits > VecWidth) 10782 return false; 10783 10784 // FIXME: The widths are based on this node's type, but build vectors can 10785 // truncate their operands. 10786 SplatValue = APInt(VecWidth, 0); 10787 SplatUndef = APInt(VecWidth, 0); 10788 10789 // Get the bits. Bits with undefined values (when the corresponding element 10790 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 10791 // in SplatValue. If any of the values are not constant, give up and return 10792 // false. 10793 unsigned int NumOps = getNumOperands(); 10794 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 10795 unsigned EltWidth = VT.getScalarSizeInBits(); 10796 10797 for (unsigned j = 0; j < NumOps; ++j) { 10798 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 10799 SDValue OpVal = getOperand(i); 10800 unsigned BitPos = j * EltWidth; 10801 10802 if (OpVal.isUndef()) 10803 SplatUndef.setBits(BitPos, BitPos + EltWidth); 10804 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 10805 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 10806 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 10807 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 10808 else 10809 return false; 10810 } 10811 10812 // The build_vector is all constants or undefs. Find the smallest element 10813 // size that splats the vector. 10814 HasAnyUndefs = (SplatUndef != 0); 10815 10816 // FIXME: This does not work for vectors with elements less than 8 bits. 10817 while (VecWidth > 8) { 10818 unsigned HalfSize = VecWidth / 2; 10819 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 10820 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 10821 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 10822 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 10823 10824 // If the two halves do not match (ignoring undef bits), stop here. 10825 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 10826 MinSplatBits > HalfSize) 10827 break; 10828 10829 SplatValue = HighValue | LowValue; 10830 SplatUndef = HighUndef & LowUndef; 10831 10832 VecWidth = HalfSize; 10833 } 10834 10835 SplatBitSize = VecWidth; 10836 return true; 10837 } 10838 10839 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 10840 BitVector *UndefElements) const { 10841 unsigned NumOps = getNumOperands(); 10842 if (UndefElements) { 10843 UndefElements->clear(); 10844 UndefElements->resize(NumOps); 10845 } 10846 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10847 if (!DemandedElts) 10848 return SDValue(); 10849 SDValue Splatted; 10850 for (unsigned i = 0; i != NumOps; ++i) { 10851 if (!DemandedElts[i]) 10852 continue; 10853 SDValue Op = getOperand(i); 10854 if (Op.isUndef()) { 10855 if (UndefElements) 10856 (*UndefElements)[i] = true; 10857 } else if (!Splatted) { 10858 Splatted = Op; 10859 } else if (Splatted != Op) { 10860 return SDValue(); 10861 } 10862 } 10863 10864 if (!Splatted) { 10865 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 10866 assert(getOperand(FirstDemandedIdx).isUndef() && 10867 "Can only have a splat without a constant for all undefs."); 10868 return getOperand(FirstDemandedIdx); 10869 } 10870 10871 return Splatted; 10872 } 10873 10874 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 10875 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10876 return getSplatValue(DemandedElts, UndefElements); 10877 } 10878 10879 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 10880 SmallVectorImpl<SDValue> &Sequence, 10881 BitVector *UndefElements) const { 10882 unsigned NumOps = getNumOperands(); 10883 Sequence.clear(); 10884 if (UndefElements) { 10885 UndefElements->clear(); 10886 UndefElements->resize(NumOps); 10887 } 10888 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10889 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10890 return false; 10891 10892 // Set the undefs even if we don't find a sequence (like getSplatValue). 10893 if (UndefElements) 10894 for (unsigned I = 0; I != NumOps; ++I) 10895 if (DemandedElts[I] && getOperand(I).isUndef()) 10896 (*UndefElements)[I] = true; 10897 10898 // Iteratively widen the sequence length looking for repetitions. 10899 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10900 Sequence.append(SeqLen, SDValue()); 10901 for (unsigned I = 0; I != NumOps; ++I) { 10902 if (!DemandedElts[I]) 10903 continue; 10904 SDValue &SeqOp = Sequence[I % SeqLen]; 10905 SDValue Op = getOperand(I); 10906 if (Op.isUndef()) { 10907 if (!SeqOp) 10908 SeqOp = Op; 10909 continue; 10910 } 10911 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10912 Sequence.clear(); 10913 break; 10914 } 10915 SeqOp = Op; 10916 } 10917 if (!Sequence.empty()) 10918 return true; 10919 } 10920 10921 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10922 return false; 10923 } 10924 10925 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10926 BitVector *UndefElements) const { 10927 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10928 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10929 } 10930 10931 ConstantSDNode * 10932 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10933 BitVector *UndefElements) const { 10934 return dyn_cast_or_null<ConstantSDNode>( 10935 getSplatValue(DemandedElts, UndefElements)); 10936 } 10937 10938 ConstantSDNode * 10939 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10940 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10941 } 10942 10943 ConstantFPSDNode * 10944 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10945 BitVector *UndefElements) const { 10946 return dyn_cast_or_null<ConstantFPSDNode>( 10947 getSplatValue(DemandedElts, UndefElements)); 10948 } 10949 10950 ConstantFPSDNode * 10951 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10952 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10953 } 10954 10955 int32_t 10956 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10957 uint32_t BitWidth) const { 10958 if (ConstantFPSDNode *CN = 10959 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10960 bool IsExact; 10961 APSInt IntVal(BitWidth); 10962 const APFloat &APF = CN->getValueAPF(); 10963 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10964 APFloat::opOK || 10965 !IsExact) 10966 return -1; 10967 10968 return IntVal.exactLogBase2(); 10969 } 10970 return -1; 10971 } 10972 10973 bool BuildVectorSDNode::getConstantRawBits( 10974 bool IsLittleEndian, unsigned DstEltSizeInBits, 10975 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 10976 // Early-out if this contains anything but Undef/Constant/ConstantFP. 10977 if (!isConstant()) 10978 return false; 10979 10980 unsigned NumSrcOps = getNumOperands(); 10981 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 10982 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 10983 "Invalid bitcast scale"); 10984 10985 // Extract raw src bits. 10986 SmallVector<APInt> SrcBitElements(NumSrcOps, 10987 APInt::getNullValue(SrcEltSizeInBits)); 10988 BitVector SrcUndeElements(NumSrcOps, false); 10989 10990 for (unsigned I = 0; I != NumSrcOps; ++I) { 10991 SDValue Op = getOperand(I); 10992 if (Op.isUndef()) { 10993 SrcUndeElements.set(I); 10994 continue; 10995 } 10996 auto *CInt = dyn_cast<ConstantSDNode>(Op); 10997 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 10998 assert((CInt || CFP) && "Unknown constant"); 10999 SrcBitElements[I] = 11000 CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits) 11001 : CFP->getValueAPF().bitcastToAPInt(); 11002 } 11003 11004 // Recast to dst width. 11005 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11006 SrcBitElements, UndefElements, SrcUndeElements); 11007 return true; 11008 } 11009 11010 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11011 unsigned DstEltSizeInBits, 11012 SmallVectorImpl<APInt> &DstBitElements, 11013 ArrayRef<APInt> SrcBitElements, 11014 BitVector &DstUndefElements, 11015 const BitVector &SrcUndefElements) { 11016 unsigned NumSrcOps = SrcBitElements.size(); 11017 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11018 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11019 "Invalid bitcast scale"); 11020 assert(NumSrcOps == SrcUndefElements.size() && 11021 "Vector size mismatch"); 11022 11023 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11024 DstUndefElements.clear(); 11025 DstUndefElements.resize(NumDstOps, false); 11026 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11027 11028 // Concatenate src elements constant bits together into dst element. 11029 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11030 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11031 for (unsigned I = 0; I != NumDstOps; ++I) { 11032 DstUndefElements.set(I); 11033 APInt &DstBits = DstBitElements[I]; 11034 for (unsigned J = 0; J != Scale; ++J) { 11035 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11036 if (SrcUndefElements[Idx]) 11037 continue; 11038 DstUndefElements.reset(I); 11039 const APInt &SrcBits = SrcBitElements[Idx]; 11040 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11041 "Illegal constant bitwidths"); 11042 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11043 } 11044 } 11045 return; 11046 } 11047 11048 // Split src element constant bits into dst elements. 11049 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11050 for (unsigned I = 0; I != NumSrcOps; ++I) { 11051 if (SrcUndefElements[I]) { 11052 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11053 continue; 11054 } 11055 const APInt &SrcBits = SrcBitElements[I]; 11056 for (unsigned J = 0; J != Scale; ++J) { 11057 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11058 APInt &DstBits = DstBitElements[Idx]; 11059 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11060 } 11061 } 11062 } 11063 11064 bool BuildVectorSDNode::isConstant() const { 11065 for (const SDValue &Op : op_values()) { 11066 unsigned Opc = Op.getOpcode(); 11067 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11068 return false; 11069 } 11070 return true; 11071 } 11072 11073 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11074 // Find the first non-undef value in the shuffle mask. 11075 unsigned i, e; 11076 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11077 /* search */; 11078 11079 // If all elements are undefined, this shuffle can be considered a splat 11080 // (although it should eventually get simplified away completely). 11081 if (i == e) 11082 return true; 11083 11084 // Make sure all remaining elements are either undef or the same as the first 11085 // non-undef value. 11086 for (int Idx = Mask[i]; i != e; ++i) 11087 if (Mask[i] >= 0 && Mask[i] != Idx) 11088 return false; 11089 return true; 11090 } 11091 11092 // Returns the SDNode if it is a constant integer BuildVector 11093 // or constant integer. 11094 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11095 if (isa<ConstantSDNode>(N)) 11096 return N.getNode(); 11097 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11098 return N.getNode(); 11099 // Treat a GlobalAddress supporting constant offset folding as a 11100 // constant integer. 11101 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11102 if (GA->getOpcode() == ISD::GlobalAddress && 11103 TLI->isOffsetFoldingLegal(GA)) 11104 return GA; 11105 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11106 isa<ConstantSDNode>(N.getOperand(0))) 11107 return N.getNode(); 11108 return nullptr; 11109 } 11110 11111 // Returns the SDNode if it is a constant float BuildVector 11112 // or constant float. 11113 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11114 if (isa<ConstantFPSDNode>(N)) 11115 return N.getNode(); 11116 11117 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11118 return N.getNode(); 11119 11120 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11121 isa<ConstantFPSDNode>(N.getOperand(0))) 11122 return N.getNode(); 11123 11124 return nullptr; 11125 } 11126 11127 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11128 assert(!Node->OperandList && "Node already has operands"); 11129 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11130 "too many operands to fit into SDNode"); 11131 SDUse *Ops = OperandRecycler.allocate( 11132 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11133 11134 bool IsDivergent = false; 11135 for (unsigned I = 0; I != Vals.size(); ++I) { 11136 Ops[I].setUser(Node); 11137 Ops[I].setInitial(Vals[I]); 11138 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11139 IsDivergent |= Ops[I].getNode()->isDivergent(); 11140 } 11141 Node->NumOperands = Vals.size(); 11142 Node->OperandList = Ops; 11143 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11144 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11145 Node->SDNodeBits.IsDivergent = IsDivergent; 11146 } 11147 checkForCycles(Node); 11148 } 11149 11150 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11151 SmallVectorImpl<SDValue> &Vals) { 11152 size_t Limit = SDNode::getMaxNumOperands(); 11153 while (Vals.size() > Limit) { 11154 unsigned SliceIdx = Vals.size() - Limit; 11155 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11156 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11157 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11158 Vals.emplace_back(NewTF); 11159 } 11160 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11161 } 11162 11163 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11164 EVT VT, SDNodeFlags Flags) { 11165 switch (Opcode) { 11166 default: 11167 return SDValue(); 11168 case ISD::ADD: 11169 case ISD::OR: 11170 case ISD::XOR: 11171 case ISD::UMAX: 11172 return getConstant(0, DL, VT); 11173 case ISD::MUL: 11174 return getConstant(1, DL, VT); 11175 case ISD::AND: 11176 case ISD::UMIN: 11177 return getAllOnesConstant(DL, VT); 11178 case ISD::SMAX: 11179 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11180 case ISD::SMIN: 11181 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11182 case ISD::FADD: 11183 return getConstantFP(-0.0, DL, VT); 11184 case ISD::FMUL: 11185 return getConstantFP(1.0, DL, VT); 11186 case ISD::FMINNUM: 11187 case ISD::FMAXNUM: { 11188 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11189 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11190 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11191 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11192 APFloat::getLargest(Semantics); 11193 if (Opcode == ISD::FMAXNUM) 11194 NeutralAF.changeSign(); 11195 11196 return getConstantFP(NeutralAF, DL, VT); 11197 } 11198 } 11199 } 11200 11201 #ifndef NDEBUG 11202 static void checkForCyclesHelper(const SDNode *N, 11203 SmallPtrSetImpl<const SDNode*> &Visited, 11204 SmallPtrSetImpl<const SDNode*> &Checked, 11205 const llvm::SelectionDAG *DAG) { 11206 // If this node has already been checked, don't check it again. 11207 if (Checked.count(N)) 11208 return; 11209 11210 // If a node has already been visited on this depth-first walk, reject it as 11211 // a cycle. 11212 if (!Visited.insert(N).second) { 11213 errs() << "Detected cycle in SelectionDAG\n"; 11214 dbgs() << "Offending node:\n"; 11215 N->dumprFull(DAG); dbgs() << "\n"; 11216 abort(); 11217 } 11218 11219 for (const SDValue &Op : N->op_values()) 11220 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11221 11222 Checked.insert(N); 11223 Visited.erase(N); 11224 } 11225 #endif 11226 11227 void llvm::checkForCycles(const llvm::SDNode *N, 11228 const llvm::SelectionDAG *DAG, 11229 bool force) { 11230 #ifndef NDEBUG 11231 bool check = force; 11232 #ifdef EXPENSIVE_CHECKS 11233 check = true; 11234 #endif // EXPENSIVE_CHECKS 11235 if (check) { 11236 assert(N && "Checking nonexistent SDNode"); 11237 SmallPtrSet<const SDNode*, 32> visited; 11238 SmallPtrSet<const SDNode*, 32> checked; 11239 checkForCyclesHelper(N, visited, checked, DAG); 11240 } 11241 #endif // !NDEBUG 11242 } 11243 11244 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11245 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11246 } 11247