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/FunctionLoweringInfo.h" 32 #include "llvm/CodeGen/ISDOpcodes.h" 33 #include "llvm/CodeGen/MachineBasicBlock.h" 34 #include "llvm/CodeGen/MachineConstantPool.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineMemOperand.h" 38 #include "llvm/CodeGen/RuntimeLibcalls.h" 39 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 40 #include "llvm/CodeGen/SelectionDAGNodes.h" 41 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 42 #include "llvm/CodeGen/TargetFrameLowering.h" 43 #include "llvm/CodeGen/TargetLowering.h" 44 #include "llvm/CodeGen/TargetRegisterInfo.h" 45 #include "llvm/CodeGen/TargetSubtargetInfo.h" 46 #include "llvm/CodeGen/ValueTypes.h" 47 #include "llvm/IR/Constant.h" 48 #include "llvm/IR/Constants.h" 49 #include "llvm/IR/DataLayout.h" 50 #include "llvm/IR/DebugInfoMetadata.h" 51 #include "llvm/IR/DebugLoc.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/GlobalValue.h" 55 #include "llvm/IR/Metadata.h" 56 #include "llvm/IR/Type.h" 57 #include "llvm/IR/Value.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/CodeGen.h" 60 #include "llvm/Support/Compiler.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/KnownBits.h" 64 #include "llvm/Support/MachineValueType.h" 65 #include "llvm/Support/ManagedStatic.h" 66 #include "llvm/Support/MathExtras.h" 67 #include "llvm/Support/Mutex.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include "llvm/Target/TargetOptions.h" 71 #include "llvm/Transforms/Utils/SizeOpts.h" 72 #include <algorithm> 73 #include <cassert> 74 #include <cstdint> 75 #include <cstdlib> 76 #include <limits> 77 #include <set> 78 #include <string> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 /// makeVTList - Return an instance of the SDVTList struct initialized with the 85 /// specified members. 86 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 87 SDVTList Res = {VTs, NumVTs}; 88 return Res; 89 } 90 91 // Default null implementations of the callbacks. 92 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 93 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 94 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 95 96 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 97 98 #define DEBUG_TYPE "selectiondag" 99 100 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 101 cl::Hidden, cl::init(true), 102 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 103 104 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 105 cl::desc("Number limit for gluing ld/st of memcpy."), 106 cl::Hidden, cl::init(0)); 107 108 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 109 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 110 } 111 112 //===----------------------------------------------------------------------===// 113 // ConstantFPSDNode Class 114 //===----------------------------------------------------------------------===// 115 116 /// isExactlyValue - We don't rely on operator== working on double values, as 117 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 118 /// As such, this method can be used to do an exact bit-for-bit comparison of 119 /// two floating point values. 120 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 121 return getValueAPF().bitwiseIsEqual(V); 122 } 123 124 bool ConstantFPSDNode::isValueValidForType(EVT VT, 125 const APFloat& Val) { 126 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 127 128 // convert modifies in place, so make a copy. 129 APFloat Val2 = APFloat(Val); 130 bool losesInfo; 131 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 132 APFloat::rmNearestTiesToEven, 133 &losesInfo); 134 return !losesInfo; 135 } 136 137 //===----------------------------------------------------------------------===// 138 // ISD Namespace 139 //===----------------------------------------------------------------------===// 140 141 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 142 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 143 unsigned EltSize = 144 N->getValueType(0).getVectorElementType().getSizeInBits(); 145 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 146 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize); 147 return true; 148 } 149 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 150 SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize); 151 return true; 152 } 153 } 154 155 auto *BV = dyn_cast<BuildVectorSDNode>(N); 156 if (!BV) 157 return false; 158 159 APInt SplatUndef; 160 unsigned SplatBitSize; 161 bool HasUndefs; 162 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 163 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 164 EltSize) && 165 EltSize == SplatBitSize; 166 } 167 168 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 169 // specializations of the more general isConstantSplatVector()? 170 171 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 172 // Look through a bit convert. 173 while (N->getOpcode() == ISD::BITCAST) 174 N = N->getOperand(0).getNode(); 175 176 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 177 APInt SplatVal; 178 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 179 } 180 181 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 182 183 unsigned i = 0, e = N->getNumOperands(); 184 185 // Skip over all of the undef values. 186 while (i != e && N->getOperand(i).isUndef()) 187 ++i; 188 189 // Do not accept an all-undef vector. 190 if (i == e) return false; 191 192 // Do not accept build_vectors that aren't all constants or which have non-~0 193 // elements. We have to be a bit careful here, as the type of the constant 194 // may not be the same as the type of the vector elements due to type 195 // legalization (the elements are promoted to a legal type for the target and 196 // a vector of a type may be legal when the base element type is not). 197 // We only want to check enough bits to cover the vector elements, because 198 // we care if the resultant vector is all ones, not whether the individual 199 // constants are. 200 SDValue NotZero = N->getOperand(i); 201 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 202 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 203 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 204 return false; 205 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 206 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 207 return false; 208 } else 209 return false; 210 211 // Okay, we have at least one ~0 value, check to see if the rest match or are 212 // undefs. Even with the above element type twiddling, this should be OK, as 213 // the same type legalization should have applied to all the elements. 214 for (++i; i != e; ++i) 215 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 216 return false; 217 return true; 218 } 219 220 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 221 // Look through a bit convert. 222 while (N->getOpcode() == ISD::BITCAST) 223 N = N->getOperand(0).getNode(); 224 225 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 226 APInt SplatVal; 227 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 228 } 229 230 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 231 232 bool IsAllUndef = true; 233 for (const SDValue &Op : N->op_values()) { 234 if (Op.isUndef()) 235 continue; 236 IsAllUndef = false; 237 // Do not accept build_vectors that aren't all constants or which have non-0 238 // elements. We have to be a bit careful here, as the type of the constant 239 // may not be the same as the type of the vector elements due to type 240 // legalization (the elements are promoted to a legal type for the target 241 // and a vector of a type may be legal when the base element type is not). 242 // We only want to check enough bits to cover the vector elements, because 243 // we care if the resultant vector is all zeros, not whether the individual 244 // constants are. 245 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 246 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 247 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 248 return false; 249 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 250 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 251 return false; 252 } else 253 return false; 254 } 255 256 // Do not accept an all-undef vector. 257 if (IsAllUndef) 258 return false; 259 return true; 260 } 261 262 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 263 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 264 } 265 266 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 267 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 268 } 269 270 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 271 if (N->getOpcode() != ISD::BUILD_VECTOR) 272 return false; 273 274 for (const SDValue &Op : N->op_values()) { 275 if (Op.isUndef()) 276 continue; 277 if (!isa<ConstantSDNode>(Op)) 278 return false; 279 } 280 return true; 281 } 282 283 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 284 if (N->getOpcode() != ISD::BUILD_VECTOR) 285 return false; 286 287 for (const SDValue &Op : N->op_values()) { 288 if (Op.isUndef()) 289 continue; 290 if (!isa<ConstantFPSDNode>(Op)) 291 return false; 292 } 293 return true; 294 } 295 296 bool ISD::allOperandsUndef(const SDNode *N) { 297 // Return false if the node has no operands. 298 // This is "logically inconsistent" with the definition of "all" but 299 // is probably the desired behavior. 300 if (N->getNumOperands() == 0) 301 return false; 302 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 303 } 304 305 bool ISD::matchUnaryPredicate(SDValue Op, 306 std::function<bool(ConstantSDNode *)> Match, 307 bool AllowUndefs) { 308 // FIXME: Add support for scalar UNDEF cases? 309 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 310 return Match(Cst); 311 312 // FIXME: Add support for vector UNDEF cases? 313 if (ISD::BUILD_VECTOR != Op.getOpcode() && 314 ISD::SPLAT_VECTOR != Op.getOpcode()) 315 return false; 316 317 EVT SVT = Op.getValueType().getScalarType(); 318 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 319 if (AllowUndefs && Op.getOperand(i).isUndef()) { 320 if (!Match(nullptr)) 321 return false; 322 continue; 323 } 324 325 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 326 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 327 return false; 328 } 329 return true; 330 } 331 332 bool ISD::matchBinaryPredicate( 333 SDValue LHS, SDValue RHS, 334 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 335 bool AllowUndefs, bool AllowTypeMismatch) { 336 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 337 return false; 338 339 // TODO: Add support for scalar UNDEF cases? 340 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 341 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 342 return Match(LHSCst, RHSCst); 343 344 // TODO: Add support for vector UNDEF cases? 345 if (LHS.getOpcode() != RHS.getOpcode() || 346 (LHS.getOpcode() != ISD::BUILD_VECTOR && 347 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 348 return false; 349 350 EVT SVT = LHS.getValueType().getScalarType(); 351 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 352 SDValue LHSOp = LHS.getOperand(i); 353 SDValue RHSOp = RHS.getOperand(i); 354 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 355 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 356 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 357 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 358 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 359 return false; 360 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 361 LHSOp.getValueType() != RHSOp.getValueType())) 362 return false; 363 if (!Match(LHSCst, RHSCst)) 364 return false; 365 } 366 return true; 367 } 368 369 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 370 switch (VecReduceOpcode) { 371 default: 372 llvm_unreachable("Expected VECREDUCE opcode"); 373 case ISD::VECREDUCE_FADD: 374 case ISD::VECREDUCE_SEQ_FADD: 375 return ISD::FADD; 376 case ISD::VECREDUCE_FMUL: 377 case ISD::VECREDUCE_SEQ_FMUL: 378 return ISD::FMUL; 379 case ISD::VECREDUCE_ADD: 380 return ISD::ADD; 381 case ISD::VECREDUCE_MUL: 382 return ISD::MUL; 383 case ISD::VECREDUCE_AND: 384 return ISD::AND; 385 case ISD::VECREDUCE_OR: 386 return ISD::OR; 387 case ISD::VECREDUCE_XOR: 388 return ISD::XOR; 389 case ISD::VECREDUCE_SMAX: 390 return ISD::SMAX; 391 case ISD::VECREDUCE_SMIN: 392 return ISD::SMIN; 393 case ISD::VECREDUCE_UMAX: 394 return ISD::UMAX; 395 case ISD::VECREDUCE_UMIN: 396 return ISD::UMIN; 397 case ISD::VECREDUCE_FMAX: 398 return ISD::FMAXNUM; 399 case ISD::VECREDUCE_FMIN: 400 return ISD::FMINNUM; 401 } 402 } 403 404 bool ISD::isVPOpcode(unsigned Opcode) { 405 switch (Opcode) { 406 default: 407 return false; 408 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \ 409 case ISD::SDOPC: \ 410 return true; 411 #include "llvm/IR/VPIntrinsics.def" 412 } 413 } 414 415 bool ISD::isVPBinaryOp(unsigned Opcode) { 416 switch (Opcode) { 417 default: 418 return false; 419 #define PROPERTY_VP_BINARYOP_SDNODE(SDOPC) \ 420 case ISD::SDOPC: \ 421 return true; 422 #include "llvm/IR/VPIntrinsics.def" 423 } 424 } 425 426 bool ISD::isVPReduction(unsigned Opcode) { 427 switch (Opcode) { 428 default: 429 return false; 430 #define PROPERTY_VP_REDUCTION_SDNODE(SDOPC) \ 431 case ISD::SDOPC: \ 432 return true; 433 #include "llvm/IR/VPIntrinsics.def" 434 } 435 } 436 437 /// The operand position of the vector mask. 438 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 439 switch (Opcode) { 440 default: 441 return None; 442 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...) \ 443 case ISD::SDOPC: \ 444 return MASKPOS; 445 #include "llvm/IR/VPIntrinsics.def" 446 } 447 } 448 449 /// The operand position of the explicit vector length parameter. 450 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 451 switch (Opcode) { 452 default: 453 return None; 454 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 455 case ISD::SDOPC: \ 456 return EVLPOS; 457 #include "llvm/IR/VPIntrinsics.def" 458 } 459 } 460 461 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 462 switch (ExtType) { 463 case ISD::EXTLOAD: 464 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 465 case ISD::SEXTLOAD: 466 return ISD::SIGN_EXTEND; 467 case ISD::ZEXTLOAD: 468 return ISD::ZERO_EXTEND; 469 default: 470 break; 471 } 472 473 llvm_unreachable("Invalid LoadExtType"); 474 } 475 476 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 477 // To perform this operation, we just need to swap the L and G bits of the 478 // operation. 479 unsigned OldL = (Operation >> 2) & 1; 480 unsigned OldG = (Operation >> 1) & 1; 481 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 482 (OldL << 1) | // New G bit 483 (OldG << 2)); // New L bit. 484 } 485 486 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 487 unsigned Operation = Op; 488 if (isIntegerLike) 489 Operation ^= 7; // Flip L, G, E bits, but not U. 490 else 491 Operation ^= 15; // Flip all of the condition bits. 492 493 if (Operation > ISD::SETTRUE2) 494 Operation &= ~8; // Don't let N and U bits get set. 495 496 return ISD::CondCode(Operation); 497 } 498 499 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 500 return getSetCCInverseImpl(Op, Type.isInteger()); 501 } 502 503 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 504 bool isIntegerLike) { 505 return getSetCCInverseImpl(Op, isIntegerLike); 506 } 507 508 /// For an integer comparison, return 1 if the comparison is a signed operation 509 /// and 2 if the result is an unsigned comparison. Return zero if the operation 510 /// does not depend on the sign of the input (setne and seteq). 511 static int isSignedOp(ISD::CondCode Opcode) { 512 switch (Opcode) { 513 default: llvm_unreachable("Illegal integer setcc operation!"); 514 case ISD::SETEQ: 515 case ISD::SETNE: return 0; 516 case ISD::SETLT: 517 case ISD::SETLE: 518 case ISD::SETGT: 519 case ISD::SETGE: return 1; 520 case ISD::SETULT: 521 case ISD::SETULE: 522 case ISD::SETUGT: 523 case ISD::SETUGE: return 2; 524 } 525 } 526 527 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 528 EVT Type) { 529 bool IsInteger = Type.isInteger(); 530 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 531 // Cannot fold a signed integer setcc with an unsigned integer setcc. 532 return ISD::SETCC_INVALID; 533 534 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 535 536 // If the N and U bits get set, then the resultant comparison DOES suddenly 537 // care about orderedness, and it is true when ordered. 538 if (Op > ISD::SETTRUE2) 539 Op &= ~16; // Clear the U bit if the N bit is set. 540 541 // Canonicalize illegal integer setcc's. 542 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 543 Op = ISD::SETNE; 544 545 return ISD::CondCode(Op); 546 } 547 548 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 549 EVT Type) { 550 bool IsInteger = Type.isInteger(); 551 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 552 // Cannot fold a signed setcc with an unsigned setcc. 553 return ISD::SETCC_INVALID; 554 555 // Combine all of the condition bits. 556 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 557 558 // Canonicalize illegal integer setcc's. 559 if (IsInteger) { 560 switch (Result) { 561 default: break; 562 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 563 case ISD::SETOEQ: // SETEQ & SETU[LG]E 564 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 565 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 566 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 567 } 568 } 569 570 return Result; 571 } 572 573 //===----------------------------------------------------------------------===// 574 // SDNode Profile Support 575 //===----------------------------------------------------------------------===// 576 577 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 578 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 579 ID.AddInteger(OpC); 580 } 581 582 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 583 /// solely with their pointer. 584 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 585 ID.AddPointer(VTList.VTs); 586 } 587 588 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 589 static void AddNodeIDOperands(FoldingSetNodeID &ID, 590 ArrayRef<SDValue> Ops) { 591 for (auto& Op : Ops) { 592 ID.AddPointer(Op.getNode()); 593 ID.AddInteger(Op.getResNo()); 594 } 595 } 596 597 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 598 static void AddNodeIDOperands(FoldingSetNodeID &ID, 599 ArrayRef<SDUse> Ops) { 600 for (auto& Op : Ops) { 601 ID.AddPointer(Op.getNode()); 602 ID.AddInteger(Op.getResNo()); 603 } 604 } 605 606 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 607 SDVTList VTList, ArrayRef<SDValue> OpList) { 608 AddNodeIDOpcode(ID, OpC); 609 AddNodeIDValueTypes(ID, VTList); 610 AddNodeIDOperands(ID, OpList); 611 } 612 613 /// If this is an SDNode with special info, add this info to the NodeID data. 614 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 615 switch (N->getOpcode()) { 616 case ISD::TargetExternalSymbol: 617 case ISD::ExternalSymbol: 618 case ISD::MCSymbol: 619 llvm_unreachable("Should only be used on nodes with operands"); 620 default: break; // Normal nodes don't need extra info. 621 case ISD::TargetConstant: 622 case ISD::Constant: { 623 const ConstantSDNode *C = cast<ConstantSDNode>(N); 624 ID.AddPointer(C->getConstantIntValue()); 625 ID.AddBoolean(C->isOpaque()); 626 break; 627 } 628 case ISD::TargetConstantFP: 629 case ISD::ConstantFP: 630 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 631 break; 632 case ISD::TargetGlobalAddress: 633 case ISD::GlobalAddress: 634 case ISD::TargetGlobalTLSAddress: 635 case ISD::GlobalTLSAddress: { 636 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 637 ID.AddPointer(GA->getGlobal()); 638 ID.AddInteger(GA->getOffset()); 639 ID.AddInteger(GA->getTargetFlags()); 640 break; 641 } 642 case ISD::BasicBlock: 643 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 644 break; 645 case ISD::Register: 646 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 647 break; 648 case ISD::RegisterMask: 649 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 650 break; 651 case ISD::SRCVALUE: 652 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 653 break; 654 case ISD::FrameIndex: 655 case ISD::TargetFrameIndex: 656 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 657 break; 658 case ISD::LIFETIME_START: 659 case ISD::LIFETIME_END: 660 if (cast<LifetimeSDNode>(N)->hasOffset()) { 661 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 662 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 663 } 664 break; 665 case ISD::PSEUDO_PROBE: 666 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 667 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 668 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 669 break; 670 case ISD::JumpTable: 671 case ISD::TargetJumpTable: 672 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 673 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 674 break; 675 case ISD::ConstantPool: 676 case ISD::TargetConstantPool: { 677 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 678 ID.AddInteger(CP->getAlign().value()); 679 ID.AddInteger(CP->getOffset()); 680 if (CP->isMachineConstantPoolEntry()) 681 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 682 else 683 ID.AddPointer(CP->getConstVal()); 684 ID.AddInteger(CP->getTargetFlags()); 685 break; 686 } 687 case ISD::TargetIndex: { 688 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 689 ID.AddInteger(TI->getIndex()); 690 ID.AddInteger(TI->getOffset()); 691 ID.AddInteger(TI->getTargetFlags()); 692 break; 693 } 694 case ISD::LOAD: { 695 const LoadSDNode *LD = cast<LoadSDNode>(N); 696 ID.AddInteger(LD->getMemoryVT().getRawBits()); 697 ID.AddInteger(LD->getRawSubclassData()); 698 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 699 break; 700 } 701 case ISD::STORE: { 702 const StoreSDNode *ST = cast<StoreSDNode>(N); 703 ID.AddInteger(ST->getMemoryVT().getRawBits()); 704 ID.AddInteger(ST->getRawSubclassData()); 705 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 706 break; 707 } 708 case ISD::VP_LOAD: { 709 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 710 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 711 ID.AddInteger(ELD->getRawSubclassData()); 712 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 713 break; 714 } 715 case ISD::VP_STORE: { 716 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 717 ID.AddInteger(EST->getMemoryVT().getRawBits()); 718 ID.AddInteger(EST->getRawSubclassData()); 719 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 720 break; 721 } 722 case ISD::VP_GATHER: { 723 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 724 ID.AddInteger(EG->getMemoryVT().getRawBits()); 725 ID.AddInteger(EG->getRawSubclassData()); 726 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 727 break; 728 } 729 case ISD::VP_SCATTER: { 730 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 731 ID.AddInteger(ES->getMemoryVT().getRawBits()); 732 ID.AddInteger(ES->getRawSubclassData()); 733 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 734 break; 735 } 736 case ISD::MLOAD: { 737 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 738 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 739 ID.AddInteger(MLD->getRawSubclassData()); 740 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 741 break; 742 } 743 case ISD::MSTORE: { 744 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 745 ID.AddInteger(MST->getMemoryVT().getRawBits()); 746 ID.AddInteger(MST->getRawSubclassData()); 747 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 748 break; 749 } 750 case ISD::MGATHER: { 751 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 752 ID.AddInteger(MG->getMemoryVT().getRawBits()); 753 ID.AddInteger(MG->getRawSubclassData()); 754 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 755 break; 756 } 757 case ISD::MSCATTER: { 758 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 759 ID.AddInteger(MS->getMemoryVT().getRawBits()); 760 ID.AddInteger(MS->getRawSubclassData()); 761 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 762 break; 763 } 764 case ISD::ATOMIC_CMP_SWAP: 765 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 766 case ISD::ATOMIC_SWAP: 767 case ISD::ATOMIC_LOAD_ADD: 768 case ISD::ATOMIC_LOAD_SUB: 769 case ISD::ATOMIC_LOAD_AND: 770 case ISD::ATOMIC_LOAD_CLR: 771 case ISD::ATOMIC_LOAD_OR: 772 case ISD::ATOMIC_LOAD_XOR: 773 case ISD::ATOMIC_LOAD_NAND: 774 case ISD::ATOMIC_LOAD_MIN: 775 case ISD::ATOMIC_LOAD_MAX: 776 case ISD::ATOMIC_LOAD_UMIN: 777 case ISD::ATOMIC_LOAD_UMAX: 778 case ISD::ATOMIC_LOAD: 779 case ISD::ATOMIC_STORE: { 780 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 781 ID.AddInteger(AT->getMemoryVT().getRawBits()); 782 ID.AddInteger(AT->getRawSubclassData()); 783 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 784 break; 785 } 786 case ISD::PREFETCH: { 787 const MemSDNode *PF = cast<MemSDNode>(N); 788 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 789 break; 790 } 791 case ISD::VECTOR_SHUFFLE: { 792 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 793 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 794 i != e; ++i) 795 ID.AddInteger(SVN->getMaskElt(i)); 796 break; 797 } 798 case ISD::TargetBlockAddress: 799 case ISD::BlockAddress: { 800 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 801 ID.AddPointer(BA->getBlockAddress()); 802 ID.AddInteger(BA->getOffset()); 803 ID.AddInteger(BA->getTargetFlags()); 804 break; 805 } 806 } // end switch (N->getOpcode()) 807 808 // Target specific memory nodes could also have address spaces to check. 809 if (N->isTargetMemoryOpcode()) 810 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 811 } 812 813 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 814 /// data. 815 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 816 AddNodeIDOpcode(ID, N->getOpcode()); 817 // Add the return value info. 818 AddNodeIDValueTypes(ID, N->getVTList()); 819 // Add the operand info. 820 AddNodeIDOperands(ID, N->ops()); 821 822 // Handle SDNode leafs with special info. 823 AddNodeIDCustom(ID, N); 824 } 825 826 //===----------------------------------------------------------------------===// 827 // SelectionDAG Class 828 //===----------------------------------------------------------------------===// 829 830 /// doNotCSE - Return true if CSE should not be performed for this node. 831 static bool doNotCSE(SDNode *N) { 832 if (N->getValueType(0) == MVT::Glue) 833 return true; // Never CSE anything that produces a flag. 834 835 switch (N->getOpcode()) { 836 default: break; 837 case ISD::HANDLENODE: 838 case ISD::EH_LABEL: 839 return true; // Never CSE these nodes. 840 } 841 842 // Check that remaining values produced are not flags. 843 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 844 if (N->getValueType(i) == MVT::Glue) 845 return true; // Never CSE anything that produces a flag. 846 847 return false; 848 } 849 850 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 851 /// SelectionDAG. 852 void SelectionDAG::RemoveDeadNodes() { 853 // Create a dummy node (which is not added to allnodes), that adds a reference 854 // to the root node, preventing it from being deleted. 855 HandleSDNode Dummy(getRoot()); 856 857 SmallVector<SDNode*, 128> DeadNodes; 858 859 // Add all obviously-dead nodes to the DeadNodes worklist. 860 for (SDNode &Node : allnodes()) 861 if (Node.use_empty()) 862 DeadNodes.push_back(&Node); 863 864 RemoveDeadNodes(DeadNodes); 865 866 // If the root changed (e.g. it was a dead load, update the root). 867 setRoot(Dummy.getValue()); 868 } 869 870 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 871 /// given list, and any nodes that become unreachable as a result. 872 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 873 874 // Process the worklist, deleting the nodes and adding their uses to the 875 // worklist. 876 while (!DeadNodes.empty()) { 877 SDNode *N = DeadNodes.pop_back_val(); 878 // Skip to next node if we've already managed to delete the node. This could 879 // happen if replacing a node causes a node previously added to the node to 880 // be deleted. 881 if (N->getOpcode() == ISD::DELETED_NODE) 882 continue; 883 884 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 885 DUL->NodeDeleted(N, nullptr); 886 887 // Take the node out of the appropriate CSE map. 888 RemoveNodeFromCSEMaps(N); 889 890 // Next, brutally remove the operand list. This is safe to do, as there are 891 // no cycles in the graph. 892 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 893 SDUse &Use = *I++; 894 SDNode *Operand = Use.getNode(); 895 Use.set(SDValue()); 896 897 // Now that we removed this operand, see if there are no uses of it left. 898 if (Operand->use_empty()) 899 DeadNodes.push_back(Operand); 900 } 901 902 DeallocateNode(N); 903 } 904 } 905 906 void SelectionDAG::RemoveDeadNode(SDNode *N){ 907 SmallVector<SDNode*, 16> DeadNodes(1, N); 908 909 // Create a dummy node that adds a reference to the root node, preventing 910 // it from being deleted. (This matters if the root is an operand of the 911 // dead node.) 912 HandleSDNode Dummy(getRoot()); 913 914 RemoveDeadNodes(DeadNodes); 915 } 916 917 void SelectionDAG::DeleteNode(SDNode *N) { 918 // First take this out of the appropriate CSE map. 919 RemoveNodeFromCSEMaps(N); 920 921 // Finally, remove uses due to operands of this node, remove from the 922 // AllNodes list, and delete the node. 923 DeleteNodeNotInCSEMaps(N); 924 } 925 926 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 927 assert(N->getIterator() != AllNodes.begin() && 928 "Cannot delete the entry node!"); 929 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 930 931 // Drop all of the operands and decrement used node's use counts. 932 N->DropOperands(); 933 934 DeallocateNode(N); 935 } 936 937 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 938 assert(!(V->isVariadic() && isParameter)); 939 if (isParameter) 940 ByvalParmDbgValues.push_back(V); 941 else 942 DbgValues.push_back(V); 943 for (const SDNode *Node : V->getSDNodes()) 944 if (Node) 945 DbgValMap[Node].push_back(V); 946 } 947 948 void SDDbgInfo::erase(const SDNode *Node) { 949 DbgValMapType::iterator I = DbgValMap.find(Node); 950 if (I == DbgValMap.end()) 951 return; 952 for (auto &Val: I->second) 953 Val->setIsInvalidated(); 954 DbgValMap.erase(I); 955 } 956 957 void SelectionDAG::DeallocateNode(SDNode *N) { 958 // If we have operands, deallocate them. 959 removeOperands(N); 960 961 NodeAllocator.Deallocate(AllNodes.remove(N)); 962 963 // Set the opcode to DELETED_NODE to help catch bugs when node 964 // memory is reallocated. 965 // FIXME: There are places in SDag that have grown a dependency on the opcode 966 // value in the released node. 967 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 968 N->NodeType = ISD::DELETED_NODE; 969 970 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 971 // them and forget about that node. 972 DbgInfo->erase(N); 973 } 974 975 #ifndef NDEBUG 976 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 977 static void VerifySDNode(SDNode *N) { 978 switch (N->getOpcode()) { 979 default: 980 break; 981 case ISD::BUILD_PAIR: { 982 EVT VT = N->getValueType(0); 983 assert(N->getNumValues() == 1 && "Too many results!"); 984 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 985 "Wrong return type!"); 986 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 987 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 988 "Mismatched operand types!"); 989 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 990 "Wrong operand type!"); 991 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 992 "Wrong return type size"); 993 break; 994 } 995 case ISD::BUILD_VECTOR: { 996 assert(N->getNumValues() == 1 && "Too many results!"); 997 assert(N->getValueType(0).isVector() && "Wrong return type!"); 998 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 999 "Wrong number of operands!"); 1000 EVT EltVT = N->getValueType(0).getVectorElementType(); 1001 for (const SDUse &Op : N->ops()) { 1002 assert((Op.getValueType() == EltVT || 1003 (EltVT.isInteger() && Op.getValueType().isInteger() && 1004 EltVT.bitsLE(Op.getValueType()))) && 1005 "Wrong operand type!"); 1006 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1007 "Operands must all have the same type"); 1008 } 1009 break; 1010 } 1011 } 1012 } 1013 #endif // NDEBUG 1014 1015 /// Insert a newly allocated node into the DAG. 1016 /// 1017 /// Handles insertion into the all nodes list and CSE map, as well as 1018 /// verification and other common operations when a new node is allocated. 1019 void SelectionDAG::InsertNode(SDNode *N) { 1020 AllNodes.push_back(N); 1021 #ifndef NDEBUG 1022 N->PersistentId = NextPersistentId++; 1023 VerifySDNode(N); 1024 #endif 1025 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1026 DUL->NodeInserted(N); 1027 } 1028 1029 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1030 /// correspond to it. This is useful when we're about to delete or repurpose 1031 /// the node. We don't want future request for structurally identical nodes 1032 /// to return N anymore. 1033 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1034 bool Erased = false; 1035 switch (N->getOpcode()) { 1036 case ISD::HANDLENODE: return false; // noop. 1037 case ISD::CONDCODE: 1038 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1039 "Cond code doesn't exist!"); 1040 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1041 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1042 break; 1043 case ISD::ExternalSymbol: 1044 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1045 break; 1046 case ISD::TargetExternalSymbol: { 1047 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1048 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1049 ESN->getSymbol(), ESN->getTargetFlags())); 1050 break; 1051 } 1052 case ISD::MCSymbol: { 1053 auto *MCSN = cast<MCSymbolSDNode>(N); 1054 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1055 break; 1056 } 1057 case ISD::VALUETYPE: { 1058 EVT VT = cast<VTSDNode>(N)->getVT(); 1059 if (VT.isExtended()) { 1060 Erased = ExtendedValueTypeNodes.erase(VT); 1061 } else { 1062 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1063 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1064 } 1065 break; 1066 } 1067 default: 1068 // Remove it from the CSE Map. 1069 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1070 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1071 Erased = CSEMap.RemoveNode(N); 1072 break; 1073 } 1074 #ifndef NDEBUG 1075 // Verify that the node was actually in one of the CSE maps, unless it has a 1076 // flag result (which cannot be CSE'd) or is one of the special cases that are 1077 // not subject to CSE. 1078 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1079 !N->isMachineOpcode() && !doNotCSE(N)) { 1080 N->dump(this); 1081 dbgs() << "\n"; 1082 llvm_unreachable("Node is not in map!"); 1083 } 1084 #endif 1085 return Erased; 1086 } 1087 1088 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1089 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1090 /// node already exists, in which case transfer all its users to the existing 1091 /// node. This transfer can potentially trigger recursive merging. 1092 void 1093 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1094 // For node types that aren't CSE'd, just act as if no identical node 1095 // already exists. 1096 if (!doNotCSE(N)) { 1097 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1098 if (Existing != N) { 1099 // If there was already an existing matching node, use ReplaceAllUsesWith 1100 // to replace the dead one with the existing one. This can cause 1101 // recursive merging of other unrelated nodes down the line. 1102 ReplaceAllUsesWith(N, Existing); 1103 1104 // N is now dead. Inform the listeners and delete it. 1105 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1106 DUL->NodeDeleted(N, Existing); 1107 DeleteNodeNotInCSEMaps(N); 1108 return; 1109 } 1110 } 1111 1112 // If the node doesn't already exist, we updated it. Inform listeners. 1113 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1114 DUL->NodeUpdated(N); 1115 } 1116 1117 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1118 /// were replaced with those specified. If this node is never memoized, 1119 /// return null, otherwise return a pointer to the slot it would take. If a 1120 /// node already exists with these operands, the slot will be non-null. 1121 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1122 void *&InsertPos) { 1123 if (doNotCSE(N)) 1124 return nullptr; 1125 1126 SDValue Ops[] = { Op }; 1127 FoldingSetNodeID ID; 1128 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1129 AddNodeIDCustom(ID, N); 1130 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1131 if (Node) 1132 Node->intersectFlagsWith(N->getFlags()); 1133 return Node; 1134 } 1135 1136 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1137 /// were replaced with those specified. If this node is never memoized, 1138 /// return null, otherwise return a pointer to the slot it would take. If a 1139 /// node already exists with these operands, the slot will be non-null. 1140 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1141 SDValue Op1, SDValue Op2, 1142 void *&InsertPos) { 1143 if (doNotCSE(N)) 1144 return nullptr; 1145 1146 SDValue Ops[] = { Op1, Op2 }; 1147 FoldingSetNodeID ID; 1148 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1149 AddNodeIDCustom(ID, N); 1150 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1151 if (Node) 1152 Node->intersectFlagsWith(N->getFlags()); 1153 return Node; 1154 } 1155 1156 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1157 /// were replaced with those specified. If this node is never memoized, 1158 /// return null, otherwise return a pointer to the slot it would take. If a 1159 /// node already exists with these operands, the slot will be non-null. 1160 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1161 void *&InsertPos) { 1162 if (doNotCSE(N)) 1163 return nullptr; 1164 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 Align SelectionDAG::getEVTAlign(EVT VT) const { 1175 Type *Ty = VT == MVT::iPTR ? 1176 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1177 VT.getTypeForEVT(*getContext()); 1178 1179 return getDataLayout().getABITypeAlign(Ty); 1180 } 1181 1182 // EntryNode could meaningfully have debug info if we can find it... 1183 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1184 : TM(tm), OptLevel(OL), 1185 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1186 Root(getEntryNode()) { 1187 InsertNode(&EntryNode); 1188 DbgInfo = new SDDbgInfo(); 1189 } 1190 1191 void SelectionDAG::init(MachineFunction &NewMF, 1192 OptimizationRemarkEmitter &NewORE, 1193 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1194 LegacyDivergenceAnalysis * Divergence, 1195 ProfileSummaryInfo *PSIin, 1196 BlockFrequencyInfo *BFIin) { 1197 MF = &NewMF; 1198 SDAGISelPass = PassPtr; 1199 ORE = &NewORE; 1200 TLI = getSubtarget().getTargetLowering(); 1201 TSI = getSubtarget().getSelectionDAGInfo(); 1202 LibInfo = LibraryInfo; 1203 Context = &MF->getFunction().getContext(); 1204 DA = Divergence; 1205 PSI = PSIin; 1206 BFI = BFIin; 1207 } 1208 1209 SelectionDAG::~SelectionDAG() { 1210 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1211 allnodes_clear(); 1212 OperandRecycler.clear(OperandAllocator); 1213 delete DbgInfo; 1214 } 1215 1216 bool SelectionDAG::shouldOptForSize() const { 1217 return MF->getFunction().hasOptSize() || 1218 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1219 } 1220 1221 void SelectionDAG::allnodes_clear() { 1222 assert(&*AllNodes.begin() == &EntryNode); 1223 AllNodes.remove(AllNodes.begin()); 1224 while (!AllNodes.empty()) 1225 DeallocateNode(&AllNodes.front()); 1226 #ifndef NDEBUG 1227 NextPersistentId = 0; 1228 #endif 1229 } 1230 1231 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1232 void *&InsertPos) { 1233 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1234 if (N) { 1235 switch (N->getOpcode()) { 1236 default: break; 1237 case ISD::Constant: 1238 case ISD::ConstantFP: 1239 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1240 "debug location. Use another overload."); 1241 } 1242 } 1243 return N; 1244 } 1245 1246 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1247 const SDLoc &DL, void *&InsertPos) { 1248 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1249 if (N) { 1250 switch (N->getOpcode()) { 1251 case ISD::Constant: 1252 case ISD::ConstantFP: 1253 // Erase debug location from the node if the node is used at several 1254 // different places. Do not propagate one location to all uses as it 1255 // will cause a worse single stepping debugging experience. 1256 if (N->getDebugLoc() != DL.getDebugLoc()) 1257 N->setDebugLoc(DebugLoc()); 1258 break; 1259 default: 1260 // When the node's point of use is located earlier in the instruction 1261 // sequence than its prior point of use, update its debug info to the 1262 // earlier location. 1263 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1264 N->setDebugLoc(DL.getDebugLoc()); 1265 break; 1266 } 1267 } 1268 return N; 1269 } 1270 1271 void SelectionDAG::clear() { 1272 allnodes_clear(); 1273 OperandRecycler.clear(OperandAllocator); 1274 OperandAllocator.Reset(); 1275 CSEMap.clear(); 1276 1277 ExtendedValueTypeNodes.clear(); 1278 ExternalSymbols.clear(); 1279 TargetExternalSymbols.clear(); 1280 MCSymbols.clear(); 1281 SDCallSiteDbgInfo.clear(); 1282 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1283 static_cast<CondCodeSDNode*>(nullptr)); 1284 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1285 static_cast<SDNode*>(nullptr)); 1286 1287 EntryNode.UseList = nullptr; 1288 InsertNode(&EntryNode); 1289 Root = getEntryNode(); 1290 DbgInfo->clear(); 1291 } 1292 1293 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1294 return VT.bitsGT(Op.getValueType()) 1295 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1296 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1297 } 1298 1299 std::pair<SDValue, SDValue> 1300 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1301 const SDLoc &DL, EVT VT) { 1302 assert(!VT.bitsEq(Op.getValueType()) && 1303 "Strict no-op FP extend/round not allowed."); 1304 SDValue Res = 1305 VT.bitsGT(Op.getValueType()) 1306 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1307 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1308 {Chain, Op, getIntPtrConstant(0, DL)}); 1309 1310 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1311 } 1312 1313 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1314 return VT.bitsGT(Op.getValueType()) ? 1315 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1316 getNode(ISD::TRUNCATE, DL, VT, Op); 1317 } 1318 1319 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1320 return VT.bitsGT(Op.getValueType()) ? 1321 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1322 getNode(ISD::TRUNCATE, DL, VT, Op); 1323 } 1324 1325 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1326 return VT.bitsGT(Op.getValueType()) ? 1327 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1328 getNode(ISD::TRUNCATE, DL, VT, Op); 1329 } 1330 1331 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1332 EVT OpVT) { 1333 if (VT.bitsLE(Op.getValueType())) 1334 return getNode(ISD::TRUNCATE, SL, VT, Op); 1335 1336 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1337 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1338 } 1339 1340 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1341 EVT OpVT = Op.getValueType(); 1342 assert(VT.isInteger() && OpVT.isInteger() && 1343 "Cannot getZeroExtendInReg FP types"); 1344 assert(VT.isVector() == OpVT.isVector() && 1345 "getZeroExtendInReg type should be vector iff the operand " 1346 "type is vector!"); 1347 assert((!VT.isVector() || 1348 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1349 "Vector element counts must match in getZeroExtendInReg"); 1350 assert(VT.bitsLE(OpVT) && "Not extending!"); 1351 if (OpVT == VT) 1352 return Op; 1353 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1354 VT.getScalarSizeInBits()); 1355 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1356 } 1357 1358 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1359 // Only unsigned pointer semantics are supported right now. In the future this 1360 // might delegate to TLI to check pointer signedness. 1361 return getZExtOrTrunc(Op, DL, VT); 1362 } 1363 1364 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1365 // Only unsigned pointer semantics are supported right now. In the future this 1366 // might delegate to TLI to check pointer signedness. 1367 return getZeroExtendInReg(Op, DL, VT); 1368 } 1369 1370 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1371 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1372 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1373 } 1374 1375 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1376 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1377 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1378 } 1379 1380 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1381 EVT OpVT) { 1382 if (!V) 1383 return getConstant(0, DL, VT); 1384 1385 switch (TLI->getBooleanContents(OpVT)) { 1386 case TargetLowering::ZeroOrOneBooleanContent: 1387 case TargetLowering::UndefinedBooleanContent: 1388 return getConstant(1, DL, VT); 1389 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1390 return getAllOnesConstant(DL, VT); 1391 } 1392 llvm_unreachable("Unexpected boolean content enum!"); 1393 } 1394 1395 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1396 bool isT, bool isO) { 1397 EVT EltVT = VT.getScalarType(); 1398 assert((EltVT.getSizeInBits() >= 64 || 1399 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1400 "getConstant with a uint64_t value that doesn't fit in the type!"); 1401 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1402 } 1403 1404 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1405 bool isT, bool isO) { 1406 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1407 } 1408 1409 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1410 EVT VT, bool isT, bool isO) { 1411 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1412 1413 EVT EltVT = VT.getScalarType(); 1414 const ConstantInt *Elt = &Val; 1415 1416 // In some cases the vector type is legal but the element type is illegal and 1417 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1418 // inserted value (the type does not need to match the vector element type). 1419 // Any extra bits introduced will be truncated away. 1420 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1421 TargetLowering::TypePromoteInteger) { 1422 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1423 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1424 Elt = ConstantInt::get(*getContext(), NewVal); 1425 } 1426 // In other cases the element type is illegal and needs to be expanded, for 1427 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1428 // the value into n parts and use a vector type with n-times the elements. 1429 // Then bitcast to the type requested. 1430 // Legalizing constants too early makes the DAGCombiner's job harder so we 1431 // only legalize if the DAG tells us we must produce legal types. 1432 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1433 TLI->getTypeAction(*getContext(), EltVT) == 1434 TargetLowering::TypeExpandInteger) { 1435 const APInt &NewVal = Elt->getValue(); 1436 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1437 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1438 1439 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1440 if (VT.isScalableVector()) { 1441 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1442 "Can only handle an even split!"); 1443 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1444 1445 SmallVector<SDValue, 2> ScalarParts; 1446 for (unsigned i = 0; i != Parts; ++i) 1447 ScalarParts.push_back(getConstant( 1448 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1449 ViaEltVT, isT, isO)); 1450 1451 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1452 } 1453 1454 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1455 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1456 1457 // Check the temporary vector is the correct size. If this fails then 1458 // getTypeToTransformTo() probably returned a type whose size (in bits) 1459 // isn't a power-of-2 factor of the requested type size. 1460 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1461 1462 SmallVector<SDValue, 2> EltParts; 1463 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1464 EltParts.push_back(getConstant( 1465 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1466 ViaEltVT, isT, isO)); 1467 1468 // EltParts is currently in little endian order. If we actually want 1469 // big-endian order then reverse it now. 1470 if (getDataLayout().isBigEndian()) 1471 std::reverse(EltParts.begin(), EltParts.end()); 1472 1473 // The elements must be reversed when the element order is different 1474 // to the endianness of the elements (because the BITCAST is itself a 1475 // vector shuffle in this situation). However, we do not need any code to 1476 // perform this reversal because getConstant() is producing a vector 1477 // splat. 1478 // This situation occurs in MIPS MSA. 1479 1480 SmallVector<SDValue, 8> Ops; 1481 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1482 llvm::append_range(Ops, EltParts); 1483 1484 SDValue V = 1485 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1486 return V; 1487 } 1488 1489 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1490 "APInt size does not match type size!"); 1491 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1492 FoldingSetNodeID ID; 1493 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1494 ID.AddPointer(Elt); 1495 ID.AddBoolean(isO); 1496 void *IP = nullptr; 1497 SDNode *N = nullptr; 1498 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1499 if (!VT.isVector()) 1500 return SDValue(N, 0); 1501 1502 if (!N) { 1503 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1504 CSEMap.InsertNode(N, IP); 1505 InsertNode(N); 1506 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1507 } 1508 1509 SDValue Result(N, 0); 1510 if (VT.isScalableVector()) 1511 Result = getSplatVector(VT, DL, Result); 1512 else if (VT.isVector()) 1513 Result = getSplatBuildVector(VT, DL, Result); 1514 1515 return Result; 1516 } 1517 1518 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1519 bool isTarget) { 1520 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1521 } 1522 1523 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1524 const SDLoc &DL, bool LegalTypes) { 1525 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1526 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1527 return getConstant(Val, DL, ShiftVT); 1528 } 1529 1530 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1531 bool isTarget) { 1532 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1533 } 1534 1535 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1536 bool isTarget) { 1537 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1538 } 1539 1540 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1541 EVT VT, bool isTarget) { 1542 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1543 1544 EVT EltVT = VT.getScalarType(); 1545 1546 // Do the map lookup using the actual bit pattern for the floating point 1547 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1548 // we don't have issues with SNANs. 1549 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1550 FoldingSetNodeID ID; 1551 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1552 ID.AddPointer(&V); 1553 void *IP = nullptr; 1554 SDNode *N = nullptr; 1555 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1556 if (!VT.isVector()) 1557 return SDValue(N, 0); 1558 1559 if (!N) { 1560 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1561 CSEMap.InsertNode(N, IP); 1562 InsertNode(N); 1563 } 1564 1565 SDValue Result(N, 0); 1566 if (VT.isScalableVector()) 1567 Result = getSplatVector(VT, DL, Result); 1568 else if (VT.isVector()) 1569 Result = getSplatBuildVector(VT, DL, Result); 1570 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1571 return Result; 1572 } 1573 1574 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1575 bool isTarget) { 1576 EVT EltVT = VT.getScalarType(); 1577 if (EltVT == MVT::f32) 1578 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1579 if (EltVT == MVT::f64) 1580 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1581 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1582 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1583 bool Ignored; 1584 APFloat APF = APFloat(Val); 1585 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1586 &Ignored); 1587 return getConstantFP(APF, DL, VT, isTarget); 1588 } 1589 llvm_unreachable("Unsupported type in getConstantFP"); 1590 } 1591 1592 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1593 EVT VT, int64_t Offset, bool isTargetGA, 1594 unsigned TargetFlags) { 1595 assert((TargetFlags == 0 || isTargetGA) && 1596 "Cannot set target flags on target-independent globals"); 1597 1598 // Truncate (with sign-extension) the offset value to the pointer size. 1599 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1600 if (BitWidth < 64) 1601 Offset = SignExtend64(Offset, BitWidth); 1602 1603 unsigned Opc; 1604 if (GV->isThreadLocal()) 1605 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1606 else 1607 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1608 1609 FoldingSetNodeID ID; 1610 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1611 ID.AddPointer(GV); 1612 ID.AddInteger(Offset); 1613 ID.AddInteger(TargetFlags); 1614 void *IP = nullptr; 1615 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1616 return SDValue(E, 0); 1617 1618 auto *N = newSDNode<GlobalAddressSDNode>( 1619 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1620 CSEMap.InsertNode(N, IP); 1621 InsertNode(N); 1622 return SDValue(N, 0); 1623 } 1624 1625 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1626 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1627 FoldingSetNodeID ID; 1628 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1629 ID.AddInteger(FI); 1630 void *IP = nullptr; 1631 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1632 return SDValue(E, 0); 1633 1634 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1635 CSEMap.InsertNode(N, IP); 1636 InsertNode(N); 1637 return SDValue(N, 0); 1638 } 1639 1640 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1641 unsigned TargetFlags) { 1642 assert((TargetFlags == 0 || isTarget) && 1643 "Cannot set target flags on target-independent jump tables"); 1644 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1645 FoldingSetNodeID ID; 1646 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1647 ID.AddInteger(JTI); 1648 ID.AddInteger(TargetFlags); 1649 void *IP = nullptr; 1650 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1651 return SDValue(E, 0); 1652 1653 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1654 CSEMap.InsertNode(N, IP); 1655 InsertNode(N); 1656 return SDValue(N, 0); 1657 } 1658 1659 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1660 MaybeAlign Alignment, int Offset, 1661 bool isTarget, unsigned TargetFlags) { 1662 assert((TargetFlags == 0 || isTarget) && 1663 "Cannot set target flags on target-independent globals"); 1664 if (!Alignment) 1665 Alignment = shouldOptForSize() 1666 ? getDataLayout().getABITypeAlign(C->getType()) 1667 : getDataLayout().getPrefTypeAlign(C->getType()); 1668 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1669 FoldingSetNodeID ID; 1670 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1671 ID.AddInteger(Alignment->value()); 1672 ID.AddInteger(Offset); 1673 ID.AddPointer(C); 1674 ID.AddInteger(TargetFlags); 1675 void *IP = nullptr; 1676 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1677 return SDValue(E, 0); 1678 1679 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1680 TargetFlags); 1681 CSEMap.InsertNode(N, IP); 1682 InsertNode(N); 1683 SDValue V = SDValue(N, 0); 1684 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1685 return V; 1686 } 1687 1688 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1689 MaybeAlign Alignment, int Offset, 1690 bool isTarget, unsigned TargetFlags) { 1691 assert((TargetFlags == 0 || isTarget) && 1692 "Cannot set target flags on target-independent globals"); 1693 if (!Alignment) 1694 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1695 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1696 FoldingSetNodeID ID; 1697 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1698 ID.AddInteger(Alignment->value()); 1699 ID.AddInteger(Offset); 1700 C->addSelectionDAGCSEId(ID); 1701 ID.AddInteger(TargetFlags); 1702 void *IP = nullptr; 1703 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1704 return SDValue(E, 0); 1705 1706 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1707 TargetFlags); 1708 CSEMap.InsertNode(N, IP); 1709 InsertNode(N); 1710 return SDValue(N, 0); 1711 } 1712 1713 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1714 unsigned TargetFlags) { 1715 FoldingSetNodeID ID; 1716 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1717 ID.AddInteger(Index); 1718 ID.AddInteger(Offset); 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<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1725 CSEMap.InsertNode(N, IP); 1726 InsertNode(N); 1727 return SDValue(N, 0); 1728 } 1729 1730 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1731 FoldingSetNodeID ID; 1732 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1733 ID.AddPointer(MBB); 1734 void *IP = nullptr; 1735 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1736 return SDValue(E, 0); 1737 1738 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1739 CSEMap.InsertNode(N, IP); 1740 InsertNode(N); 1741 return SDValue(N, 0); 1742 } 1743 1744 SDValue SelectionDAG::getValueType(EVT VT) { 1745 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1746 ValueTypeNodes.size()) 1747 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1748 1749 SDNode *&N = VT.isExtended() ? 1750 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1751 1752 if (N) return SDValue(N, 0); 1753 N = newSDNode<VTSDNode>(VT); 1754 InsertNode(N); 1755 return SDValue(N, 0); 1756 } 1757 1758 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1759 SDNode *&N = ExternalSymbols[Sym]; 1760 if (N) return SDValue(N, 0); 1761 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1762 InsertNode(N); 1763 return SDValue(N, 0); 1764 } 1765 1766 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1767 SDNode *&N = MCSymbols[Sym]; 1768 if (N) 1769 return SDValue(N, 0); 1770 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1771 InsertNode(N); 1772 return SDValue(N, 0); 1773 } 1774 1775 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1776 unsigned TargetFlags) { 1777 SDNode *&N = 1778 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1779 if (N) return SDValue(N, 0); 1780 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1781 InsertNode(N); 1782 return SDValue(N, 0); 1783 } 1784 1785 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1786 if ((unsigned)Cond >= CondCodeNodes.size()) 1787 CondCodeNodes.resize(Cond+1); 1788 1789 if (!CondCodeNodes[Cond]) { 1790 auto *N = newSDNode<CondCodeSDNode>(Cond); 1791 CondCodeNodes[Cond] = N; 1792 InsertNode(N); 1793 } 1794 1795 return SDValue(CondCodeNodes[Cond], 0); 1796 } 1797 1798 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1799 APInt One(ResVT.getScalarSizeInBits(), 1); 1800 return getStepVector(DL, ResVT, One); 1801 } 1802 1803 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1804 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1805 if (ResVT.isScalableVector()) 1806 return getNode( 1807 ISD::STEP_VECTOR, DL, ResVT, 1808 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1809 1810 SmallVector<SDValue, 16> OpsStepConstants; 1811 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1812 OpsStepConstants.push_back( 1813 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1814 return getBuildVector(ResVT, DL, OpsStepConstants); 1815 } 1816 1817 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1818 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1819 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1820 std::swap(N1, N2); 1821 ShuffleVectorSDNode::commuteMask(M); 1822 } 1823 1824 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1825 SDValue N2, ArrayRef<int> Mask) { 1826 assert(VT.getVectorNumElements() == Mask.size() && 1827 "Must have the same number of vector elements as mask elements!"); 1828 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1829 "Invalid VECTOR_SHUFFLE"); 1830 1831 // Canonicalize shuffle undef, undef -> undef 1832 if (N1.isUndef() && N2.isUndef()) 1833 return getUNDEF(VT); 1834 1835 // Validate that all indices in Mask are within the range of the elements 1836 // input to the shuffle. 1837 int NElts = Mask.size(); 1838 assert(llvm::all_of(Mask, 1839 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1840 "Index out of range"); 1841 1842 // Copy the mask so we can do any needed cleanup. 1843 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1844 1845 // Canonicalize shuffle v, v -> v, undef 1846 if (N1 == N2) { 1847 N2 = getUNDEF(VT); 1848 for (int i = 0; i != NElts; ++i) 1849 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1850 } 1851 1852 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1853 if (N1.isUndef()) 1854 commuteShuffle(N1, N2, MaskVec); 1855 1856 if (TLI->hasVectorBlend()) { 1857 // If shuffling a splat, try to blend the splat instead. We do this here so 1858 // that even when this arises during lowering we don't have to re-handle it. 1859 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1860 BitVector UndefElements; 1861 SDValue Splat = BV->getSplatValue(&UndefElements); 1862 if (!Splat) 1863 return; 1864 1865 for (int i = 0; i < NElts; ++i) { 1866 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1867 continue; 1868 1869 // If this input comes from undef, mark it as such. 1870 if (UndefElements[MaskVec[i] - Offset]) { 1871 MaskVec[i] = -1; 1872 continue; 1873 } 1874 1875 // If we can blend a non-undef lane, use that instead. 1876 if (!UndefElements[i]) 1877 MaskVec[i] = i + Offset; 1878 } 1879 }; 1880 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1881 BlendSplat(N1BV, 0); 1882 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1883 BlendSplat(N2BV, NElts); 1884 } 1885 1886 // Canonicalize all index into lhs, -> shuffle lhs, undef 1887 // Canonicalize all index into rhs, -> shuffle rhs, undef 1888 bool AllLHS = true, AllRHS = true; 1889 bool N2Undef = N2.isUndef(); 1890 for (int i = 0; i != NElts; ++i) { 1891 if (MaskVec[i] >= NElts) { 1892 if (N2Undef) 1893 MaskVec[i] = -1; 1894 else 1895 AllLHS = false; 1896 } else if (MaskVec[i] >= 0) { 1897 AllRHS = false; 1898 } 1899 } 1900 if (AllLHS && AllRHS) 1901 return getUNDEF(VT); 1902 if (AllLHS && !N2Undef) 1903 N2 = getUNDEF(VT); 1904 if (AllRHS) { 1905 N1 = getUNDEF(VT); 1906 commuteShuffle(N1, N2, MaskVec); 1907 } 1908 // Reset our undef status after accounting for the mask. 1909 N2Undef = N2.isUndef(); 1910 // Re-check whether both sides ended up undef. 1911 if (N1.isUndef() && N2Undef) 1912 return getUNDEF(VT); 1913 1914 // If Identity shuffle return that node. 1915 bool Identity = true, AllSame = true; 1916 for (int i = 0; i != NElts; ++i) { 1917 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1918 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1919 } 1920 if (Identity && NElts) 1921 return N1; 1922 1923 // Shuffling a constant splat doesn't change the result. 1924 if (N2Undef) { 1925 SDValue V = N1; 1926 1927 // Look through any bitcasts. We check that these don't change the number 1928 // (and size) of elements and just changes their types. 1929 while (V.getOpcode() == ISD::BITCAST) 1930 V = V->getOperand(0); 1931 1932 // A splat should always show up as a build vector node. 1933 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1934 BitVector UndefElements; 1935 SDValue Splat = BV->getSplatValue(&UndefElements); 1936 // If this is a splat of an undef, shuffling it is also undef. 1937 if (Splat && Splat.isUndef()) 1938 return getUNDEF(VT); 1939 1940 bool SameNumElts = 1941 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1942 1943 // We only have a splat which can skip shuffles if there is a splatted 1944 // value and no undef lanes rearranged by the shuffle. 1945 if (Splat && UndefElements.none()) { 1946 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1947 // number of elements match or the value splatted is a zero constant. 1948 if (SameNumElts) 1949 return N1; 1950 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1951 if (C->isZero()) 1952 return N1; 1953 } 1954 1955 // If the shuffle itself creates a splat, build the vector directly. 1956 if (AllSame && SameNumElts) { 1957 EVT BuildVT = BV->getValueType(0); 1958 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1959 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1960 1961 // We may have jumped through bitcasts, so the type of the 1962 // BUILD_VECTOR may not match the type of the shuffle. 1963 if (BuildVT != VT) 1964 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1965 return NewBV; 1966 } 1967 } 1968 } 1969 1970 FoldingSetNodeID ID; 1971 SDValue Ops[2] = { N1, N2 }; 1972 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1973 for (int i = 0; i != NElts; ++i) 1974 ID.AddInteger(MaskVec[i]); 1975 1976 void* IP = nullptr; 1977 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1978 return SDValue(E, 0); 1979 1980 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1981 // SDNode doesn't have access to it. This memory will be "leaked" when 1982 // the node is deallocated, but recovered when the NodeAllocator is released. 1983 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1984 llvm::copy(MaskVec, MaskAlloc); 1985 1986 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 1987 dl.getDebugLoc(), MaskAlloc); 1988 createOperands(N, Ops); 1989 1990 CSEMap.InsertNode(N, IP); 1991 InsertNode(N); 1992 SDValue V = SDValue(N, 0); 1993 NewSDValueDbgMsg(V, "Creating new node: ", this); 1994 return V; 1995 } 1996 1997 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 1998 EVT VT = SV.getValueType(0); 1999 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2000 ShuffleVectorSDNode::commuteMask(MaskVec); 2001 2002 SDValue Op0 = SV.getOperand(0); 2003 SDValue Op1 = SV.getOperand(1); 2004 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2005 } 2006 2007 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2008 FoldingSetNodeID ID; 2009 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2010 ID.AddInteger(RegNo); 2011 void *IP = nullptr; 2012 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2013 return SDValue(E, 0); 2014 2015 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2016 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2017 CSEMap.InsertNode(N, IP); 2018 InsertNode(N); 2019 return SDValue(N, 0); 2020 } 2021 2022 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2023 FoldingSetNodeID ID; 2024 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2025 ID.AddPointer(RegMask); 2026 void *IP = nullptr; 2027 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2028 return SDValue(E, 0); 2029 2030 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2031 CSEMap.InsertNode(N, IP); 2032 InsertNode(N); 2033 return SDValue(N, 0); 2034 } 2035 2036 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2037 MCSymbol *Label) { 2038 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2039 } 2040 2041 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2042 SDValue Root, MCSymbol *Label) { 2043 FoldingSetNodeID ID; 2044 SDValue Ops[] = { Root }; 2045 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2046 ID.AddPointer(Label); 2047 void *IP = nullptr; 2048 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2049 return SDValue(E, 0); 2050 2051 auto *N = 2052 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2053 createOperands(N, Ops); 2054 2055 CSEMap.InsertNode(N, IP); 2056 InsertNode(N); 2057 return SDValue(N, 0); 2058 } 2059 2060 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2061 int64_t Offset, bool isTarget, 2062 unsigned TargetFlags) { 2063 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2064 2065 FoldingSetNodeID ID; 2066 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2067 ID.AddPointer(BA); 2068 ID.AddInteger(Offset); 2069 ID.AddInteger(TargetFlags); 2070 void *IP = nullptr; 2071 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2072 return SDValue(E, 0); 2073 2074 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2075 CSEMap.InsertNode(N, IP); 2076 InsertNode(N); 2077 return SDValue(N, 0); 2078 } 2079 2080 SDValue SelectionDAG::getSrcValue(const Value *V) { 2081 FoldingSetNodeID ID; 2082 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2083 ID.AddPointer(V); 2084 2085 void *IP = nullptr; 2086 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2087 return SDValue(E, 0); 2088 2089 auto *N = newSDNode<SrcValueSDNode>(V); 2090 CSEMap.InsertNode(N, IP); 2091 InsertNode(N); 2092 return SDValue(N, 0); 2093 } 2094 2095 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2096 FoldingSetNodeID ID; 2097 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2098 ID.AddPointer(MD); 2099 2100 void *IP = nullptr; 2101 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2102 return SDValue(E, 0); 2103 2104 auto *N = newSDNode<MDNodeSDNode>(MD); 2105 CSEMap.InsertNode(N, IP); 2106 InsertNode(N); 2107 return SDValue(N, 0); 2108 } 2109 2110 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2111 if (VT == V.getValueType()) 2112 return V; 2113 2114 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2115 } 2116 2117 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2118 unsigned SrcAS, unsigned DestAS) { 2119 SDValue Ops[] = {Ptr}; 2120 FoldingSetNodeID ID; 2121 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2122 ID.AddInteger(SrcAS); 2123 ID.AddInteger(DestAS); 2124 2125 void *IP = nullptr; 2126 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2127 return SDValue(E, 0); 2128 2129 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2130 VT, SrcAS, DestAS); 2131 createOperands(N, Ops); 2132 2133 CSEMap.InsertNode(N, IP); 2134 InsertNode(N); 2135 return SDValue(N, 0); 2136 } 2137 2138 SDValue SelectionDAG::getFreeze(SDValue V) { 2139 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2140 } 2141 2142 /// getShiftAmountOperand - Return the specified value casted to 2143 /// the target's desired shift amount type. 2144 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2145 EVT OpTy = Op.getValueType(); 2146 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2147 if (OpTy == ShTy || OpTy.isVector()) return Op; 2148 2149 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2150 } 2151 2152 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2153 SDLoc dl(Node); 2154 const TargetLowering &TLI = getTargetLoweringInfo(); 2155 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2156 EVT VT = Node->getValueType(0); 2157 SDValue Tmp1 = Node->getOperand(0); 2158 SDValue Tmp2 = Node->getOperand(1); 2159 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2160 2161 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2162 Tmp2, MachinePointerInfo(V)); 2163 SDValue VAList = VAListLoad; 2164 2165 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2166 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2167 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2168 2169 VAList = 2170 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2171 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2172 } 2173 2174 // Increment the pointer, VAList, to the next vaarg 2175 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2176 getConstant(getDataLayout().getTypeAllocSize( 2177 VT.getTypeForEVT(*getContext())), 2178 dl, VAList.getValueType())); 2179 // Store the incremented VAList to the legalized pointer 2180 Tmp1 = 2181 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2182 // Load the actual argument out of the pointer VAList 2183 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2184 } 2185 2186 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2187 SDLoc dl(Node); 2188 const TargetLowering &TLI = getTargetLoweringInfo(); 2189 // This defaults to loading a pointer from the input and storing it to the 2190 // output, returning the chain. 2191 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2192 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2193 SDValue Tmp1 = 2194 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2195 Node->getOperand(2), MachinePointerInfo(VS)); 2196 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2197 MachinePointerInfo(VD)); 2198 } 2199 2200 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2201 const DataLayout &DL = getDataLayout(); 2202 Type *Ty = VT.getTypeForEVT(*getContext()); 2203 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2204 2205 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2206 return RedAlign; 2207 2208 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2209 const Align StackAlign = TFI->getStackAlign(); 2210 2211 // See if we can choose a smaller ABI alignment in cases where it's an 2212 // illegal vector type that will get broken down. 2213 if (RedAlign > StackAlign) { 2214 EVT IntermediateVT; 2215 MVT RegisterVT; 2216 unsigned NumIntermediates; 2217 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2218 NumIntermediates, RegisterVT); 2219 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2220 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2221 if (RedAlign2 < RedAlign) 2222 RedAlign = RedAlign2; 2223 } 2224 2225 return RedAlign; 2226 } 2227 2228 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2229 MachineFrameInfo &MFI = MF->getFrameInfo(); 2230 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2231 int StackID = 0; 2232 if (Bytes.isScalable()) 2233 StackID = TFI->getStackIDForScalableVectors(); 2234 // The stack id gives an indication of whether the object is scalable or 2235 // not, so it's safe to pass in the minimum size here. 2236 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2237 false, nullptr, StackID); 2238 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2239 } 2240 2241 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2242 Type *Ty = VT.getTypeForEVT(*getContext()); 2243 Align StackAlign = 2244 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2245 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2246 } 2247 2248 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2249 TypeSize VT1Size = VT1.getStoreSize(); 2250 TypeSize VT2Size = VT2.getStoreSize(); 2251 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2252 "Don't know how to choose the maximum size when creating a stack " 2253 "temporary"); 2254 TypeSize Bytes = 2255 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2256 2257 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2258 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2259 const DataLayout &DL = getDataLayout(); 2260 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2261 return CreateStackTemporary(Bytes, Align); 2262 } 2263 2264 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2265 ISD::CondCode Cond, const SDLoc &dl) { 2266 EVT OpVT = N1.getValueType(); 2267 2268 // These setcc operations always fold. 2269 switch (Cond) { 2270 default: break; 2271 case ISD::SETFALSE: 2272 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2273 case ISD::SETTRUE: 2274 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2275 2276 case ISD::SETOEQ: 2277 case ISD::SETOGT: 2278 case ISD::SETOGE: 2279 case ISD::SETOLT: 2280 case ISD::SETOLE: 2281 case ISD::SETONE: 2282 case ISD::SETO: 2283 case ISD::SETUO: 2284 case ISD::SETUEQ: 2285 case ISD::SETUNE: 2286 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2287 break; 2288 } 2289 2290 if (OpVT.isInteger()) { 2291 // For EQ and NE, we can always pick a value for the undef to make the 2292 // predicate pass or fail, so we can return undef. 2293 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2294 // icmp eq/ne X, undef -> undef. 2295 if ((N1.isUndef() || N2.isUndef()) && 2296 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2297 return getUNDEF(VT); 2298 2299 // If both operands are undef, we can return undef for int comparison. 2300 // icmp undef, undef -> undef. 2301 if (N1.isUndef() && N2.isUndef()) 2302 return getUNDEF(VT); 2303 2304 // icmp X, X -> true/false 2305 // icmp X, undef -> true/false because undef could be X. 2306 if (N1 == N2) 2307 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2308 } 2309 2310 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2311 const APInt &C2 = N2C->getAPIntValue(); 2312 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2313 const APInt &C1 = N1C->getAPIntValue(); 2314 2315 switch (Cond) { 2316 default: llvm_unreachable("Unknown integer setcc!"); 2317 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT); 2318 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT); 2319 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT); 2320 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT); 2321 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT); 2322 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT); 2323 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT); 2324 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT); 2325 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT); 2326 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT); 2327 } 2328 } 2329 } 2330 2331 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2332 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2333 2334 if (N1CFP && N2CFP) { 2335 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2336 switch (Cond) { 2337 default: break; 2338 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2339 return getUNDEF(VT); 2340 LLVM_FALLTHROUGH; 2341 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2342 OpVT); 2343 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2344 return getUNDEF(VT); 2345 LLVM_FALLTHROUGH; 2346 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2347 R==APFloat::cmpLessThan, dl, VT, 2348 OpVT); 2349 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2350 return getUNDEF(VT); 2351 LLVM_FALLTHROUGH; 2352 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2353 OpVT); 2354 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2355 return getUNDEF(VT); 2356 LLVM_FALLTHROUGH; 2357 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2358 VT, OpVT); 2359 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2360 return getUNDEF(VT); 2361 LLVM_FALLTHROUGH; 2362 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2363 R==APFloat::cmpEqual, dl, VT, 2364 OpVT); 2365 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2366 return getUNDEF(VT); 2367 LLVM_FALLTHROUGH; 2368 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2369 R==APFloat::cmpEqual, dl, VT, OpVT); 2370 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2371 OpVT); 2372 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2373 OpVT); 2374 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2375 R==APFloat::cmpEqual, dl, VT, 2376 OpVT); 2377 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2378 OpVT); 2379 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2380 R==APFloat::cmpLessThan, dl, VT, 2381 OpVT); 2382 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2383 R==APFloat::cmpUnordered, dl, VT, 2384 OpVT); 2385 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2386 VT, OpVT); 2387 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2388 OpVT); 2389 } 2390 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2391 // Ensure that the constant occurs on the RHS. 2392 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2393 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2394 return SDValue(); 2395 return getSetCC(dl, VT, N2, N1, SwappedCond); 2396 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2397 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2398 // If an operand is known to be a nan (or undef that could be a nan), we can 2399 // fold it. 2400 // Choosing NaN for the undef will always make unordered comparison succeed 2401 // and ordered comparison fails. 2402 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2403 switch (ISD::getUnorderedFlavor(Cond)) { 2404 default: 2405 llvm_unreachable("Unknown flavor!"); 2406 case 0: // Known false. 2407 return getBoolConstant(false, dl, VT, OpVT); 2408 case 1: // Known true. 2409 return getBoolConstant(true, dl, VT, OpVT); 2410 case 2: // Undefined. 2411 return getUNDEF(VT); 2412 } 2413 } 2414 2415 // Could not fold it. 2416 return SDValue(); 2417 } 2418 2419 /// See if the specified operand can be simplified with the knowledge that only 2420 /// the bits specified by DemandedBits are used. 2421 /// TODO: really we should be making this into the DAG equivalent of 2422 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2423 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2424 EVT VT = V.getValueType(); 2425 2426 if (VT.isScalableVector()) 2427 return SDValue(); 2428 2429 APInt DemandedElts = VT.isVector() 2430 ? APInt::getAllOnes(VT.getVectorNumElements()) 2431 : APInt(1, 1); 2432 return GetDemandedBits(V, DemandedBits, DemandedElts); 2433 } 2434 2435 /// See if the specified operand can be simplified with the knowledge that only 2436 /// the bits specified by DemandedBits are used in the elements specified by 2437 /// DemandedElts. 2438 /// TODO: really we should be making this into the DAG equivalent of 2439 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2440 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2441 const APInt &DemandedElts) { 2442 switch (V.getOpcode()) { 2443 default: 2444 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2445 *this, 0); 2446 case ISD::Constant: { 2447 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2448 APInt NewVal = CVal & DemandedBits; 2449 if (NewVal != CVal) 2450 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2451 break; 2452 } 2453 case ISD::SRL: 2454 // Only look at single-use SRLs. 2455 if (!V.getNode()->hasOneUse()) 2456 break; 2457 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2458 // See if we can recursively simplify the LHS. 2459 unsigned Amt = RHSC->getZExtValue(); 2460 2461 // Watch out for shift count overflow though. 2462 if (Amt >= DemandedBits.getBitWidth()) 2463 break; 2464 APInt SrcDemandedBits = DemandedBits << Amt; 2465 if (SDValue SimplifyLHS = 2466 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2467 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2468 V.getOperand(1)); 2469 } 2470 break; 2471 } 2472 return SDValue(); 2473 } 2474 2475 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2476 /// use this predicate to simplify operations downstream. 2477 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2478 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2479 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2480 } 2481 2482 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2483 /// this predicate to simplify operations downstream. Mask is known to be zero 2484 /// for bits that V cannot have. 2485 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2486 unsigned Depth) const { 2487 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2488 } 2489 2490 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2491 /// DemandedElts. We use this predicate to simplify operations downstream. 2492 /// Mask is known to be zero for bits that V cannot have. 2493 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2494 const APInt &DemandedElts, 2495 unsigned Depth) const { 2496 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2497 } 2498 2499 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2500 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2501 unsigned Depth) const { 2502 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2503 } 2504 2505 /// isSplatValue - Return true if the vector V has the same value 2506 /// across all DemandedElts. For scalable vectors it does not make 2507 /// sense to specify which elements are demanded or undefined, therefore 2508 /// they are simply ignored. 2509 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2510 APInt &UndefElts, unsigned Depth) { 2511 EVT VT = V.getValueType(); 2512 assert(VT.isVector() && "Vector type expected"); 2513 2514 if (!VT.isScalableVector() && !DemandedElts) 2515 return false; // No demanded elts, better to assume we don't know anything. 2516 2517 if (Depth >= MaxRecursionDepth) 2518 return false; // Limit search depth. 2519 2520 // Deal with some common cases here that work for both fixed and scalable 2521 // vector types. 2522 switch (V.getOpcode()) { 2523 case ISD::SPLAT_VECTOR: 2524 UndefElts = V.getOperand(0).isUndef() 2525 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2526 : APInt(DemandedElts.getBitWidth(), 0); 2527 return true; 2528 case ISD::ADD: 2529 case ISD::SUB: 2530 case ISD::AND: 2531 case ISD::XOR: 2532 case ISD::OR: { 2533 APInt UndefLHS, UndefRHS; 2534 SDValue LHS = V.getOperand(0); 2535 SDValue RHS = V.getOperand(1); 2536 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2537 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2538 UndefElts = UndefLHS | UndefRHS; 2539 return true; 2540 } 2541 return false; 2542 } 2543 case ISD::ABS: 2544 case ISD::TRUNCATE: 2545 case ISD::SIGN_EXTEND: 2546 case ISD::ZERO_EXTEND: 2547 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2548 } 2549 2550 // We don't support other cases than those above for scalable vectors at 2551 // the moment. 2552 if (VT.isScalableVector()) 2553 return false; 2554 2555 unsigned NumElts = VT.getVectorNumElements(); 2556 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2557 UndefElts = APInt::getZero(NumElts); 2558 2559 switch (V.getOpcode()) { 2560 case ISD::BUILD_VECTOR: { 2561 SDValue Scl; 2562 for (unsigned i = 0; i != NumElts; ++i) { 2563 SDValue Op = V.getOperand(i); 2564 if (Op.isUndef()) { 2565 UndefElts.setBit(i); 2566 continue; 2567 } 2568 if (!DemandedElts[i]) 2569 continue; 2570 if (Scl && Scl != Op) 2571 return false; 2572 Scl = Op; 2573 } 2574 return true; 2575 } 2576 case ISD::VECTOR_SHUFFLE: { 2577 // Check if this is a shuffle node doing a splat. 2578 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2579 int SplatIndex = -1; 2580 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2581 for (int i = 0; i != (int)NumElts; ++i) { 2582 int M = Mask[i]; 2583 if (M < 0) { 2584 UndefElts.setBit(i); 2585 continue; 2586 } 2587 if (!DemandedElts[i]) 2588 continue; 2589 if (0 <= SplatIndex && SplatIndex != M) 2590 return false; 2591 SplatIndex = M; 2592 } 2593 return true; 2594 } 2595 case ISD::EXTRACT_SUBVECTOR: { 2596 // Offset the demanded elts by the subvector index. 2597 SDValue Src = V.getOperand(0); 2598 // We don't support scalable vectors at the moment. 2599 if (Src.getValueType().isScalableVector()) 2600 return false; 2601 uint64_t Idx = V.getConstantOperandVal(1); 2602 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2603 APInt UndefSrcElts; 2604 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2605 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2606 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2607 return true; 2608 } 2609 break; 2610 } 2611 } 2612 2613 return false; 2614 } 2615 2616 /// Helper wrapper to main isSplatValue function. 2617 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) { 2618 EVT VT = V.getValueType(); 2619 assert(VT.isVector() && "Vector type expected"); 2620 2621 APInt UndefElts; 2622 APInt DemandedElts; 2623 2624 // For now we don't support this with scalable vectors. 2625 if (!VT.isScalableVector()) 2626 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2627 return isSplatValue(V, DemandedElts, UndefElts) && 2628 (AllowUndefs || !UndefElts); 2629 } 2630 2631 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2632 V = peekThroughExtractSubvectors(V); 2633 2634 EVT VT = V.getValueType(); 2635 unsigned Opcode = V.getOpcode(); 2636 switch (Opcode) { 2637 default: { 2638 APInt UndefElts; 2639 APInt DemandedElts; 2640 2641 if (!VT.isScalableVector()) 2642 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2643 2644 if (isSplatValue(V, DemandedElts, UndefElts)) { 2645 if (VT.isScalableVector()) { 2646 // DemandedElts and UndefElts are ignored for scalable vectors, since 2647 // the only supported cases are SPLAT_VECTOR nodes. 2648 SplatIdx = 0; 2649 } else { 2650 // Handle case where all demanded elements are UNDEF. 2651 if (DemandedElts.isSubsetOf(UndefElts)) { 2652 SplatIdx = 0; 2653 return getUNDEF(VT); 2654 } 2655 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2656 } 2657 return V; 2658 } 2659 break; 2660 } 2661 case ISD::SPLAT_VECTOR: 2662 SplatIdx = 0; 2663 return V; 2664 case ISD::VECTOR_SHUFFLE: { 2665 if (VT.isScalableVector()) 2666 return SDValue(); 2667 2668 // Check if this is a shuffle node doing a splat. 2669 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2670 // getTargetVShiftNode currently struggles without the splat source. 2671 auto *SVN = cast<ShuffleVectorSDNode>(V); 2672 if (!SVN->isSplat()) 2673 break; 2674 int Idx = SVN->getSplatIndex(); 2675 int NumElts = V.getValueType().getVectorNumElements(); 2676 SplatIdx = Idx % NumElts; 2677 return V.getOperand(Idx / NumElts); 2678 } 2679 } 2680 2681 return SDValue(); 2682 } 2683 2684 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2685 int SplatIdx; 2686 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2687 EVT SVT = SrcVector.getValueType().getScalarType(); 2688 EVT LegalSVT = SVT; 2689 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2690 if (!SVT.isInteger()) 2691 return SDValue(); 2692 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2693 if (LegalSVT.bitsLT(SVT)) 2694 return SDValue(); 2695 } 2696 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2697 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2698 } 2699 return SDValue(); 2700 } 2701 2702 const APInt * 2703 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2704 const APInt &DemandedElts) const { 2705 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2706 V.getOpcode() == ISD::SRA) && 2707 "Unknown shift node"); 2708 unsigned BitWidth = V.getScalarValueSizeInBits(); 2709 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2710 // Shifting more than the bitwidth is not valid. 2711 const APInt &ShAmt = SA->getAPIntValue(); 2712 if (ShAmt.ult(BitWidth)) 2713 return &ShAmt; 2714 } 2715 return nullptr; 2716 } 2717 2718 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2719 SDValue V, const APInt &DemandedElts) const { 2720 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2721 V.getOpcode() == ISD::SRA) && 2722 "Unknown shift node"); 2723 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2724 return ValidAmt; 2725 unsigned BitWidth = V.getScalarValueSizeInBits(); 2726 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2727 if (!BV) 2728 return nullptr; 2729 const APInt *MinShAmt = nullptr; 2730 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2731 if (!DemandedElts[i]) 2732 continue; 2733 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2734 if (!SA) 2735 return nullptr; 2736 // Shifting more than the bitwidth is not valid. 2737 const APInt &ShAmt = SA->getAPIntValue(); 2738 if (ShAmt.uge(BitWidth)) 2739 return nullptr; 2740 if (MinShAmt && MinShAmt->ule(ShAmt)) 2741 continue; 2742 MinShAmt = &ShAmt; 2743 } 2744 return MinShAmt; 2745 } 2746 2747 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2748 SDValue V, const APInt &DemandedElts) const { 2749 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2750 V.getOpcode() == ISD::SRA) && 2751 "Unknown shift node"); 2752 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2753 return ValidAmt; 2754 unsigned BitWidth = V.getScalarValueSizeInBits(); 2755 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2756 if (!BV) 2757 return nullptr; 2758 const APInt *MaxShAmt = nullptr; 2759 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2760 if (!DemandedElts[i]) 2761 continue; 2762 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2763 if (!SA) 2764 return nullptr; 2765 // Shifting more than the bitwidth is not valid. 2766 const APInt &ShAmt = SA->getAPIntValue(); 2767 if (ShAmt.uge(BitWidth)) 2768 return nullptr; 2769 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2770 continue; 2771 MaxShAmt = &ShAmt; 2772 } 2773 return MaxShAmt; 2774 } 2775 2776 /// Determine which bits of Op are known to be either zero or one and return 2777 /// them in Known. For vectors, the known bits are those that are shared by 2778 /// every vector element. 2779 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2780 EVT VT = Op.getValueType(); 2781 2782 // TOOD: Until we have a plan for how to represent demanded elements for 2783 // scalable vectors, we can just bail out for now. 2784 if (Op.getValueType().isScalableVector()) { 2785 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2786 return KnownBits(BitWidth); 2787 } 2788 2789 APInt DemandedElts = VT.isVector() 2790 ? APInt::getAllOnes(VT.getVectorNumElements()) 2791 : APInt(1, 1); 2792 return computeKnownBits(Op, DemandedElts, Depth); 2793 } 2794 2795 /// Determine which bits of Op are known to be either zero or one and return 2796 /// them in Known. The DemandedElts argument allows us to only collect the known 2797 /// bits that are shared by the requested vector elements. 2798 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2799 unsigned Depth) const { 2800 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2801 2802 KnownBits Known(BitWidth); // Don't know anything. 2803 2804 // TOOD: Until we have a plan for how to represent demanded elements for 2805 // scalable vectors, we can just bail out for now. 2806 if (Op.getValueType().isScalableVector()) 2807 return Known; 2808 2809 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2810 // We know all of the bits for a constant! 2811 return KnownBits::makeConstant(C->getAPIntValue()); 2812 } 2813 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2814 // We know all of the bits for a constant fp! 2815 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2816 } 2817 2818 if (Depth >= MaxRecursionDepth) 2819 return Known; // Limit search depth. 2820 2821 KnownBits Known2; 2822 unsigned NumElts = DemandedElts.getBitWidth(); 2823 assert((!Op.getValueType().isVector() || 2824 NumElts == Op.getValueType().getVectorNumElements()) && 2825 "Unexpected vector size"); 2826 2827 if (!DemandedElts) 2828 return Known; // No demanded elts, better to assume we don't know anything. 2829 2830 unsigned Opcode = Op.getOpcode(); 2831 switch (Opcode) { 2832 case ISD::BUILD_VECTOR: 2833 // Collect the known bits that are shared by every demanded vector element. 2834 Known.Zero.setAllBits(); Known.One.setAllBits(); 2835 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2836 if (!DemandedElts[i]) 2837 continue; 2838 2839 SDValue SrcOp = Op.getOperand(i); 2840 Known2 = computeKnownBits(SrcOp, Depth + 1); 2841 2842 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2843 if (SrcOp.getValueSizeInBits() != BitWidth) { 2844 assert(SrcOp.getValueSizeInBits() > BitWidth && 2845 "Expected BUILD_VECTOR implicit truncation"); 2846 Known2 = Known2.trunc(BitWidth); 2847 } 2848 2849 // Known bits are the values that are shared by every demanded element. 2850 Known = KnownBits::commonBits(Known, Known2); 2851 2852 // If we don't know any bits, early out. 2853 if (Known.isUnknown()) 2854 break; 2855 } 2856 break; 2857 case ISD::VECTOR_SHUFFLE: { 2858 // Collect the known bits that are shared by every vector element referenced 2859 // by the shuffle. 2860 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2861 Known.Zero.setAllBits(); Known.One.setAllBits(); 2862 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2863 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2864 for (unsigned i = 0; i != NumElts; ++i) { 2865 if (!DemandedElts[i]) 2866 continue; 2867 2868 int M = SVN->getMaskElt(i); 2869 if (M < 0) { 2870 // For UNDEF elements, we don't know anything about the common state of 2871 // the shuffle result. 2872 Known.resetAll(); 2873 DemandedLHS.clearAllBits(); 2874 DemandedRHS.clearAllBits(); 2875 break; 2876 } 2877 2878 if ((unsigned)M < NumElts) 2879 DemandedLHS.setBit((unsigned)M % NumElts); 2880 else 2881 DemandedRHS.setBit((unsigned)M % NumElts); 2882 } 2883 // Known bits are the values that are shared by every demanded element. 2884 if (!!DemandedLHS) { 2885 SDValue LHS = Op.getOperand(0); 2886 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2887 Known = KnownBits::commonBits(Known, Known2); 2888 } 2889 // If we don't know any bits, early out. 2890 if (Known.isUnknown()) 2891 break; 2892 if (!!DemandedRHS) { 2893 SDValue RHS = Op.getOperand(1); 2894 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2895 Known = KnownBits::commonBits(Known, Known2); 2896 } 2897 break; 2898 } 2899 case ISD::CONCAT_VECTORS: { 2900 // Split DemandedElts and test each of the demanded subvectors. 2901 Known.Zero.setAllBits(); Known.One.setAllBits(); 2902 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2903 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2904 unsigned NumSubVectors = Op.getNumOperands(); 2905 for (unsigned i = 0; i != NumSubVectors; ++i) { 2906 APInt DemandedSub = 2907 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 2908 if (!!DemandedSub) { 2909 SDValue Sub = Op.getOperand(i); 2910 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2911 Known = KnownBits::commonBits(Known, Known2); 2912 } 2913 // If we don't know any bits, early out. 2914 if (Known.isUnknown()) 2915 break; 2916 } 2917 break; 2918 } 2919 case ISD::INSERT_SUBVECTOR: { 2920 // Demand any elements from the subvector and the remainder from the src its 2921 // inserted into. 2922 SDValue Src = Op.getOperand(0); 2923 SDValue Sub = Op.getOperand(1); 2924 uint64_t Idx = Op.getConstantOperandVal(2); 2925 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2926 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2927 APInt DemandedSrcElts = DemandedElts; 2928 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 2929 2930 Known.One.setAllBits(); 2931 Known.Zero.setAllBits(); 2932 if (!!DemandedSubElts) { 2933 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2934 if (Known.isUnknown()) 2935 break; // early-out. 2936 } 2937 if (!!DemandedSrcElts) { 2938 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2939 Known = KnownBits::commonBits(Known, Known2); 2940 } 2941 break; 2942 } 2943 case ISD::EXTRACT_SUBVECTOR: { 2944 // Offset the demanded elts by the subvector index. 2945 SDValue Src = Op.getOperand(0); 2946 // Bail until we can represent demanded elements for scalable vectors. 2947 if (Src.getValueType().isScalableVector()) 2948 break; 2949 uint64_t Idx = Op.getConstantOperandVal(1); 2950 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2951 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2952 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2953 break; 2954 } 2955 case ISD::SCALAR_TO_VECTOR: { 2956 // We know about scalar_to_vector as much as we know about it source, 2957 // which becomes the first element of otherwise unknown vector. 2958 if (DemandedElts != 1) 2959 break; 2960 2961 SDValue N0 = Op.getOperand(0); 2962 Known = computeKnownBits(N0, Depth + 1); 2963 if (N0.getValueSizeInBits() != BitWidth) 2964 Known = Known.trunc(BitWidth); 2965 2966 break; 2967 } 2968 case ISD::BITCAST: { 2969 SDValue N0 = Op.getOperand(0); 2970 EVT SubVT = N0.getValueType(); 2971 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 2972 2973 // Ignore bitcasts from unsupported types. 2974 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 2975 break; 2976 2977 // Fast handling of 'identity' bitcasts. 2978 if (BitWidth == SubBitWidth) { 2979 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 2980 break; 2981 } 2982 2983 bool IsLE = getDataLayout().isLittleEndian(); 2984 2985 // Bitcast 'small element' vector to 'large element' scalar/vector. 2986 if ((BitWidth % SubBitWidth) == 0) { 2987 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 2988 2989 // Collect known bits for the (larger) output by collecting the known 2990 // bits from each set of sub elements and shift these into place. 2991 // We need to separately call computeKnownBits for each set of 2992 // sub elements as the knownbits for each is likely to be different. 2993 unsigned SubScale = BitWidth / SubBitWidth; 2994 APInt SubDemandedElts(NumElts * SubScale, 0); 2995 for (unsigned i = 0; i != NumElts; ++i) 2996 if (DemandedElts[i]) 2997 SubDemandedElts.setBit(i * SubScale); 2998 2999 for (unsigned i = 0; i != SubScale; ++i) { 3000 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3001 Depth + 1); 3002 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3003 Known.insertBits(Known2, SubBitWidth * Shifts); 3004 } 3005 } 3006 3007 // Bitcast 'large element' scalar/vector to 'small element' vector. 3008 if ((SubBitWidth % BitWidth) == 0) { 3009 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3010 3011 // Collect known bits for the (smaller) output by collecting the known 3012 // bits from the overlapping larger input elements and extracting the 3013 // sub sections we actually care about. 3014 unsigned SubScale = SubBitWidth / BitWidth; 3015 APInt SubDemandedElts = 3016 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3017 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3018 3019 Known.Zero.setAllBits(); Known.One.setAllBits(); 3020 for (unsigned i = 0; i != NumElts; ++i) 3021 if (DemandedElts[i]) { 3022 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3023 unsigned Offset = (Shifts % SubScale) * BitWidth; 3024 Known = KnownBits::commonBits(Known, 3025 Known2.extractBits(BitWidth, Offset)); 3026 // If we don't know any bits, early out. 3027 if (Known.isUnknown()) 3028 break; 3029 } 3030 } 3031 break; 3032 } 3033 case ISD::AND: 3034 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3035 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3036 3037 Known &= Known2; 3038 break; 3039 case ISD::OR: 3040 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3041 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3042 3043 Known |= Known2; 3044 break; 3045 case ISD::XOR: 3046 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3047 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3048 3049 Known ^= Known2; 3050 break; 3051 case ISD::MUL: { 3052 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3053 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3054 Known = KnownBits::mul(Known, Known2); 3055 break; 3056 } 3057 case ISD::MULHU: { 3058 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3059 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3060 Known = KnownBits::mulhu(Known, Known2); 3061 break; 3062 } 3063 case ISD::MULHS: { 3064 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3065 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3066 Known = KnownBits::mulhs(Known, Known2); 3067 break; 3068 } 3069 case ISD::UMUL_LOHI: { 3070 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3071 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3072 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3073 if (Op.getResNo() == 0) 3074 Known = KnownBits::mul(Known, Known2); 3075 else 3076 Known = KnownBits::mulhu(Known, Known2); 3077 break; 3078 } 3079 case ISD::SMUL_LOHI: { 3080 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3081 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3082 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3083 if (Op.getResNo() == 0) 3084 Known = KnownBits::mul(Known, Known2); 3085 else 3086 Known = KnownBits::mulhs(Known, Known2); 3087 break; 3088 } 3089 case ISD::UDIV: { 3090 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3091 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3092 Known = KnownBits::udiv(Known, Known2); 3093 break; 3094 } 3095 case ISD::SELECT: 3096 case ISD::VSELECT: 3097 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3098 // If we don't know any bits, early out. 3099 if (Known.isUnknown()) 3100 break; 3101 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3102 3103 // Only known if known in both the LHS and RHS. 3104 Known = KnownBits::commonBits(Known, Known2); 3105 break; 3106 case ISD::SELECT_CC: 3107 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3108 // If we don't know any bits, early out. 3109 if (Known.isUnknown()) 3110 break; 3111 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3112 3113 // Only known if known in both the LHS and RHS. 3114 Known = KnownBits::commonBits(Known, Known2); 3115 break; 3116 case ISD::SMULO: 3117 case ISD::UMULO: 3118 if (Op.getResNo() != 1) 3119 break; 3120 // The boolean result conforms to getBooleanContents. 3121 // If we know the result of a setcc has the top bits zero, use this info. 3122 // We know that we have an integer-based boolean since these operations 3123 // are only available for integer. 3124 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3125 TargetLowering::ZeroOrOneBooleanContent && 3126 BitWidth > 1) 3127 Known.Zero.setBitsFrom(1); 3128 break; 3129 case ISD::SETCC: 3130 case ISD::STRICT_FSETCC: 3131 case ISD::STRICT_FSETCCS: { 3132 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3133 // If we know the result of a setcc has the top bits zero, use this info. 3134 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3135 TargetLowering::ZeroOrOneBooleanContent && 3136 BitWidth > 1) 3137 Known.Zero.setBitsFrom(1); 3138 break; 3139 } 3140 case ISD::SHL: 3141 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3142 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3143 Known = KnownBits::shl(Known, Known2); 3144 3145 // Minimum shift low bits are known zero. 3146 if (const APInt *ShMinAmt = 3147 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3148 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3149 break; 3150 case ISD::SRL: 3151 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3152 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3153 Known = KnownBits::lshr(Known, Known2); 3154 3155 // Minimum shift high bits are known zero. 3156 if (const APInt *ShMinAmt = 3157 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3158 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3159 break; 3160 case ISD::SRA: 3161 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3162 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3163 Known = KnownBits::ashr(Known, Known2); 3164 // TODO: Add minimum shift high known sign bits. 3165 break; 3166 case ISD::FSHL: 3167 case ISD::FSHR: 3168 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3169 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3170 3171 // For fshl, 0-shift returns the 1st arg. 3172 // For fshr, 0-shift returns the 2nd arg. 3173 if (Amt == 0) { 3174 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3175 DemandedElts, Depth + 1); 3176 break; 3177 } 3178 3179 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3180 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3181 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3182 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3183 if (Opcode == ISD::FSHL) { 3184 Known.One <<= Amt; 3185 Known.Zero <<= Amt; 3186 Known2.One.lshrInPlace(BitWidth - Amt); 3187 Known2.Zero.lshrInPlace(BitWidth - Amt); 3188 } else { 3189 Known.One <<= BitWidth - Amt; 3190 Known.Zero <<= BitWidth - Amt; 3191 Known2.One.lshrInPlace(Amt); 3192 Known2.Zero.lshrInPlace(Amt); 3193 } 3194 Known.One |= Known2.One; 3195 Known.Zero |= Known2.Zero; 3196 } 3197 break; 3198 case ISD::SIGN_EXTEND_INREG: { 3199 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3200 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3201 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3202 break; 3203 } 3204 case ISD::CTTZ: 3205 case ISD::CTTZ_ZERO_UNDEF: { 3206 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3207 // If we have a known 1, its position is our upper bound. 3208 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3209 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3210 Known.Zero.setBitsFrom(LowBits); 3211 break; 3212 } 3213 case ISD::CTLZ: 3214 case ISD::CTLZ_ZERO_UNDEF: { 3215 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3216 // If we have a known 1, its position is our upper bound. 3217 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3218 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3219 Known.Zero.setBitsFrom(LowBits); 3220 break; 3221 } 3222 case ISD::CTPOP: { 3223 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3224 // If we know some of the bits are zero, they can't be one. 3225 unsigned PossibleOnes = Known2.countMaxPopulation(); 3226 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3227 break; 3228 } 3229 case ISD::PARITY: { 3230 // Parity returns 0 everywhere but the LSB. 3231 Known.Zero.setBitsFrom(1); 3232 break; 3233 } 3234 case ISD::LOAD: { 3235 LoadSDNode *LD = cast<LoadSDNode>(Op); 3236 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3237 if (ISD::isNON_EXTLoad(LD) && Cst) { 3238 // Determine any common known bits from the loaded constant pool value. 3239 Type *CstTy = Cst->getType(); 3240 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3241 // If its a vector splat, then we can (quickly) reuse the scalar path. 3242 // NOTE: We assume all elements match and none are UNDEF. 3243 if (CstTy->isVectorTy()) { 3244 if (const Constant *Splat = Cst->getSplatValue()) { 3245 Cst = Splat; 3246 CstTy = Cst->getType(); 3247 } 3248 } 3249 // TODO - do we need to handle different bitwidths? 3250 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3251 // Iterate across all vector elements finding common known bits. 3252 Known.One.setAllBits(); 3253 Known.Zero.setAllBits(); 3254 for (unsigned i = 0; i != NumElts; ++i) { 3255 if (!DemandedElts[i]) 3256 continue; 3257 if (Constant *Elt = Cst->getAggregateElement(i)) { 3258 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3259 const APInt &Value = CInt->getValue(); 3260 Known.One &= Value; 3261 Known.Zero &= ~Value; 3262 continue; 3263 } 3264 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3265 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3266 Known.One &= Value; 3267 Known.Zero &= ~Value; 3268 continue; 3269 } 3270 } 3271 Known.One.clearAllBits(); 3272 Known.Zero.clearAllBits(); 3273 break; 3274 } 3275 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3276 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3277 Known = KnownBits::makeConstant(CInt->getValue()); 3278 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3279 Known = 3280 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3281 } 3282 } 3283 } 3284 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3285 // If this is a ZEXTLoad and we are looking at the loaded value. 3286 EVT VT = LD->getMemoryVT(); 3287 unsigned MemBits = VT.getScalarSizeInBits(); 3288 Known.Zero.setBitsFrom(MemBits); 3289 } else if (const MDNode *Ranges = LD->getRanges()) { 3290 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3291 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3292 } 3293 break; 3294 } 3295 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3296 EVT InVT = Op.getOperand(0).getValueType(); 3297 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3298 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3299 Known = Known.zext(BitWidth); 3300 break; 3301 } 3302 case ISD::ZERO_EXTEND: { 3303 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3304 Known = Known.zext(BitWidth); 3305 break; 3306 } 3307 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3308 EVT InVT = Op.getOperand(0).getValueType(); 3309 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3310 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3311 // If the sign bit is known to be zero or one, then sext will extend 3312 // it to the top bits, else it will just zext. 3313 Known = Known.sext(BitWidth); 3314 break; 3315 } 3316 case ISD::SIGN_EXTEND: { 3317 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3318 // If the sign bit is known to be zero or one, then sext will extend 3319 // it to the top bits, else it will just zext. 3320 Known = Known.sext(BitWidth); 3321 break; 3322 } 3323 case ISD::ANY_EXTEND_VECTOR_INREG: { 3324 EVT InVT = Op.getOperand(0).getValueType(); 3325 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3326 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3327 Known = Known.anyext(BitWidth); 3328 break; 3329 } 3330 case ISD::ANY_EXTEND: { 3331 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3332 Known = Known.anyext(BitWidth); 3333 break; 3334 } 3335 case ISD::TRUNCATE: { 3336 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3337 Known = Known.trunc(BitWidth); 3338 break; 3339 } 3340 case ISD::AssertZext: { 3341 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3342 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3343 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3344 Known.Zero |= (~InMask); 3345 Known.One &= (~Known.Zero); 3346 break; 3347 } 3348 case ISD::AssertAlign: { 3349 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3350 assert(LogOfAlign != 0); 3351 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3352 // well as clearing one bits. 3353 Known.Zero.setLowBits(LogOfAlign); 3354 Known.One.clearLowBits(LogOfAlign); 3355 break; 3356 } 3357 case ISD::FGETSIGN: 3358 // All bits are zero except the low bit. 3359 Known.Zero.setBitsFrom(1); 3360 break; 3361 case ISD::USUBO: 3362 case ISD::SSUBO: 3363 if (Op.getResNo() == 1) { 3364 // If we know the result of a setcc has the top bits zero, use this info. 3365 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3366 TargetLowering::ZeroOrOneBooleanContent && 3367 BitWidth > 1) 3368 Known.Zero.setBitsFrom(1); 3369 break; 3370 } 3371 LLVM_FALLTHROUGH; 3372 case ISD::SUB: 3373 case ISD::SUBC: { 3374 assert(Op.getResNo() == 0 && 3375 "We only compute knownbits for the difference here."); 3376 3377 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3378 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3379 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3380 Known, Known2); 3381 break; 3382 } 3383 case ISD::UADDO: 3384 case ISD::SADDO: 3385 case ISD::ADDCARRY: 3386 if (Op.getResNo() == 1) { 3387 // If we know the result of a setcc has the top bits zero, use this info. 3388 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3389 TargetLowering::ZeroOrOneBooleanContent && 3390 BitWidth > 1) 3391 Known.Zero.setBitsFrom(1); 3392 break; 3393 } 3394 LLVM_FALLTHROUGH; 3395 case ISD::ADD: 3396 case ISD::ADDC: 3397 case ISD::ADDE: { 3398 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3399 3400 // With ADDE and ADDCARRY, a carry bit may be added in. 3401 KnownBits Carry(1); 3402 if (Opcode == ISD::ADDE) 3403 // Can't track carry from glue, set carry to unknown. 3404 Carry.resetAll(); 3405 else if (Opcode == ISD::ADDCARRY) 3406 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3407 // the trouble (how often will we find a known carry bit). And I haven't 3408 // tested this very much yet, but something like this might work: 3409 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3410 // Carry = Carry.zextOrTrunc(1, false); 3411 Carry.resetAll(); 3412 else 3413 Carry.setAllZero(); 3414 3415 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3416 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3417 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3418 break; 3419 } 3420 case ISD::SREM: { 3421 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3422 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3423 Known = KnownBits::srem(Known, Known2); 3424 break; 3425 } 3426 case ISD::UREM: { 3427 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3428 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3429 Known = KnownBits::urem(Known, Known2); 3430 break; 3431 } 3432 case ISD::EXTRACT_ELEMENT: { 3433 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3434 const unsigned Index = Op.getConstantOperandVal(1); 3435 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3436 3437 // Remove low part of known bits mask 3438 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3439 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3440 3441 // Remove high part of known bit mask 3442 Known = Known.trunc(EltBitWidth); 3443 break; 3444 } 3445 case ISD::EXTRACT_VECTOR_ELT: { 3446 SDValue InVec = Op.getOperand(0); 3447 SDValue EltNo = Op.getOperand(1); 3448 EVT VecVT = InVec.getValueType(); 3449 // computeKnownBits not yet implemented for scalable vectors. 3450 if (VecVT.isScalableVector()) 3451 break; 3452 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3453 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3454 3455 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3456 // anything about the extended bits. 3457 if (BitWidth > EltBitWidth) 3458 Known = Known.trunc(EltBitWidth); 3459 3460 // If we know the element index, just demand that vector element, else for 3461 // an unknown element index, ignore DemandedElts and demand them all. 3462 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3463 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3464 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3465 DemandedSrcElts = 3466 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3467 3468 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3469 if (BitWidth > EltBitWidth) 3470 Known = Known.anyext(BitWidth); 3471 break; 3472 } 3473 case ISD::INSERT_VECTOR_ELT: { 3474 // If we know the element index, split the demand between the 3475 // source vector and the inserted element, otherwise assume we need 3476 // the original demanded vector elements and the value. 3477 SDValue InVec = Op.getOperand(0); 3478 SDValue InVal = Op.getOperand(1); 3479 SDValue EltNo = Op.getOperand(2); 3480 bool DemandedVal = true; 3481 APInt DemandedVecElts = DemandedElts; 3482 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3483 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3484 unsigned EltIdx = CEltNo->getZExtValue(); 3485 DemandedVal = !!DemandedElts[EltIdx]; 3486 DemandedVecElts.clearBit(EltIdx); 3487 } 3488 Known.One.setAllBits(); 3489 Known.Zero.setAllBits(); 3490 if (DemandedVal) { 3491 Known2 = computeKnownBits(InVal, Depth + 1); 3492 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3493 } 3494 if (!!DemandedVecElts) { 3495 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3496 Known = KnownBits::commonBits(Known, Known2); 3497 } 3498 break; 3499 } 3500 case ISD::BITREVERSE: { 3501 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3502 Known = Known2.reverseBits(); 3503 break; 3504 } 3505 case ISD::BSWAP: { 3506 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3507 Known = Known2.byteSwap(); 3508 break; 3509 } 3510 case ISD::ABS: { 3511 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3512 Known = Known2.abs(); 3513 break; 3514 } 3515 case ISD::USUBSAT: { 3516 // The result of usubsat will never be larger than the LHS. 3517 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3518 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3519 break; 3520 } 3521 case ISD::UMIN: { 3522 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3523 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3524 Known = KnownBits::umin(Known, Known2); 3525 break; 3526 } 3527 case ISD::UMAX: { 3528 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3529 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3530 Known = KnownBits::umax(Known, Known2); 3531 break; 3532 } 3533 case ISD::SMIN: 3534 case ISD::SMAX: { 3535 // If we have a clamp pattern, we know that the number of sign bits will be 3536 // the minimum of the clamp min/max range. 3537 bool IsMax = (Opcode == ISD::SMAX); 3538 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3539 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3540 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3541 CstHigh = 3542 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3543 if (CstLow && CstHigh) { 3544 if (!IsMax) 3545 std::swap(CstLow, CstHigh); 3546 3547 const APInt &ValueLow = CstLow->getAPIntValue(); 3548 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3549 if (ValueLow.sle(ValueHigh)) { 3550 unsigned LowSignBits = ValueLow.getNumSignBits(); 3551 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3552 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3553 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3554 Known.One.setHighBits(MinSignBits); 3555 break; 3556 } 3557 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3558 Known.Zero.setHighBits(MinSignBits); 3559 break; 3560 } 3561 } 3562 } 3563 3564 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3565 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3566 if (IsMax) 3567 Known = KnownBits::smax(Known, Known2); 3568 else 3569 Known = KnownBits::smin(Known, Known2); 3570 break; 3571 } 3572 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3573 if (Op.getResNo() == 1) { 3574 // The boolean result conforms to getBooleanContents. 3575 // If we know the result of a setcc has the top bits zero, use this info. 3576 // We know that we have an integer-based boolean since these operations 3577 // are only available for integer. 3578 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3579 TargetLowering::ZeroOrOneBooleanContent && 3580 BitWidth > 1) 3581 Known.Zero.setBitsFrom(1); 3582 break; 3583 } 3584 LLVM_FALLTHROUGH; 3585 case ISD::ATOMIC_CMP_SWAP: 3586 case ISD::ATOMIC_SWAP: 3587 case ISD::ATOMIC_LOAD_ADD: 3588 case ISD::ATOMIC_LOAD_SUB: 3589 case ISD::ATOMIC_LOAD_AND: 3590 case ISD::ATOMIC_LOAD_CLR: 3591 case ISD::ATOMIC_LOAD_OR: 3592 case ISD::ATOMIC_LOAD_XOR: 3593 case ISD::ATOMIC_LOAD_NAND: 3594 case ISD::ATOMIC_LOAD_MIN: 3595 case ISD::ATOMIC_LOAD_MAX: 3596 case ISD::ATOMIC_LOAD_UMIN: 3597 case ISD::ATOMIC_LOAD_UMAX: 3598 case ISD::ATOMIC_LOAD: { 3599 unsigned MemBits = 3600 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3601 // If we are looking at the loaded value. 3602 if (Op.getResNo() == 0) { 3603 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3604 Known.Zero.setBitsFrom(MemBits); 3605 } 3606 break; 3607 } 3608 case ISD::FrameIndex: 3609 case ISD::TargetFrameIndex: 3610 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3611 Known, getMachineFunction()); 3612 break; 3613 3614 default: 3615 if (Opcode < ISD::BUILTIN_OP_END) 3616 break; 3617 LLVM_FALLTHROUGH; 3618 case ISD::INTRINSIC_WO_CHAIN: 3619 case ISD::INTRINSIC_W_CHAIN: 3620 case ISD::INTRINSIC_VOID: 3621 // Allow the target to implement this method for its nodes. 3622 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3623 break; 3624 } 3625 3626 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3627 return Known; 3628 } 3629 3630 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3631 SDValue N1) const { 3632 // X + 0 never overflow 3633 if (isNullConstant(N1)) 3634 return OFK_Never; 3635 3636 KnownBits N1Known = computeKnownBits(N1); 3637 if (N1Known.Zero.getBoolValue()) { 3638 KnownBits N0Known = computeKnownBits(N0); 3639 3640 bool overflow; 3641 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3642 if (!overflow) 3643 return OFK_Never; 3644 } 3645 3646 // mulhi + 1 never overflow 3647 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3648 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3649 return OFK_Never; 3650 3651 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3652 KnownBits N0Known = computeKnownBits(N0); 3653 3654 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3655 return OFK_Never; 3656 } 3657 3658 return OFK_Sometime; 3659 } 3660 3661 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3662 EVT OpVT = Val.getValueType(); 3663 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3664 3665 // Is the constant a known power of 2? 3666 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3667 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3668 3669 // A left-shift of a constant one will have exactly one bit set because 3670 // shifting the bit off the end is undefined. 3671 if (Val.getOpcode() == ISD::SHL) { 3672 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3673 if (C && C->getAPIntValue() == 1) 3674 return true; 3675 } 3676 3677 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3678 // one bit set. 3679 if (Val.getOpcode() == ISD::SRL) { 3680 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3681 if (C && C->getAPIntValue().isSignMask()) 3682 return true; 3683 } 3684 3685 // Are all operands of a build vector constant powers of two? 3686 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3687 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3688 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3689 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3690 return false; 3691 })) 3692 return true; 3693 3694 // Is the operand of a splat vector a constant power of two? 3695 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3696 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3697 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3698 return true; 3699 3700 // More could be done here, though the above checks are enough 3701 // to handle some common cases. 3702 3703 // Fall back to computeKnownBits to catch other known cases. 3704 KnownBits Known = computeKnownBits(Val); 3705 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3706 } 3707 3708 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3709 EVT VT = Op.getValueType(); 3710 3711 // TODO: Assume we don't know anything for now. 3712 if (VT.isScalableVector()) 3713 return 1; 3714 3715 APInt DemandedElts = VT.isVector() 3716 ? APInt::getAllOnes(VT.getVectorNumElements()) 3717 : APInt(1, 1); 3718 return ComputeNumSignBits(Op, DemandedElts, Depth); 3719 } 3720 3721 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3722 unsigned Depth) const { 3723 EVT VT = Op.getValueType(); 3724 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3725 unsigned VTBits = VT.getScalarSizeInBits(); 3726 unsigned NumElts = DemandedElts.getBitWidth(); 3727 unsigned Tmp, Tmp2; 3728 unsigned FirstAnswer = 1; 3729 3730 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3731 const APInt &Val = C->getAPIntValue(); 3732 return Val.getNumSignBits(); 3733 } 3734 3735 if (Depth >= MaxRecursionDepth) 3736 return 1; // Limit search depth. 3737 3738 if (!DemandedElts || VT.isScalableVector()) 3739 return 1; // No demanded elts, better to assume we don't know anything. 3740 3741 unsigned Opcode = Op.getOpcode(); 3742 switch (Opcode) { 3743 default: break; 3744 case ISD::AssertSext: 3745 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3746 return VTBits-Tmp+1; 3747 case ISD::AssertZext: 3748 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3749 return VTBits-Tmp; 3750 3751 case ISD::BUILD_VECTOR: 3752 Tmp = VTBits; 3753 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3754 if (!DemandedElts[i]) 3755 continue; 3756 3757 SDValue SrcOp = Op.getOperand(i); 3758 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3759 3760 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3761 if (SrcOp.getValueSizeInBits() != VTBits) { 3762 assert(SrcOp.getValueSizeInBits() > VTBits && 3763 "Expected BUILD_VECTOR implicit truncation"); 3764 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3765 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3766 } 3767 Tmp = std::min(Tmp, Tmp2); 3768 } 3769 return Tmp; 3770 3771 case ISD::VECTOR_SHUFFLE: { 3772 // Collect the minimum number of sign bits that are shared by every vector 3773 // element referenced by the shuffle. 3774 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3775 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3776 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3777 for (unsigned i = 0; i != NumElts; ++i) { 3778 int M = SVN->getMaskElt(i); 3779 if (!DemandedElts[i]) 3780 continue; 3781 // For UNDEF elements, we don't know anything about the common state of 3782 // the shuffle result. 3783 if (M < 0) 3784 return 1; 3785 if ((unsigned)M < NumElts) 3786 DemandedLHS.setBit((unsigned)M % NumElts); 3787 else 3788 DemandedRHS.setBit((unsigned)M % NumElts); 3789 } 3790 Tmp = std::numeric_limits<unsigned>::max(); 3791 if (!!DemandedLHS) 3792 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3793 if (!!DemandedRHS) { 3794 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3795 Tmp = std::min(Tmp, Tmp2); 3796 } 3797 // If we don't know anything, early out and try computeKnownBits fall-back. 3798 if (Tmp == 1) 3799 break; 3800 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3801 return Tmp; 3802 } 3803 3804 case ISD::BITCAST: { 3805 SDValue N0 = Op.getOperand(0); 3806 EVT SrcVT = N0.getValueType(); 3807 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3808 3809 // Ignore bitcasts from unsupported types.. 3810 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3811 break; 3812 3813 // Fast handling of 'identity' bitcasts. 3814 if (VTBits == SrcBits) 3815 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3816 3817 bool IsLE = getDataLayout().isLittleEndian(); 3818 3819 // Bitcast 'large element' scalar/vector to 'small element' vector. 3820 if ((SrcBits % VTBits) == 0) { 3821 assert(VT.isVector() && "Expected bitcast to vector"); 3822 3823 unsigned Scale = SrcBits / VTBits; 3824 APInt SrcDemandedElts = 3825 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3826 3827 // Fast case - sign splat can be simply split across the small elements. 3828 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3829 if (Tmp == SrcBits) 3830 return VTBits; 3831 3832 // Slow case - determine how far the sign extends into each sub-element. 3833 Tmp2 = VTBits; 3834 for (unsigned i = 0; i != NumElts; ++i) 3835 if (DemandedElts[i]) { 3836 unsigned SubOffset = i % Scale; 3837 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3838 SubOffset = SubOffset * VTBits; 3839 if (Tmp <= SubOffset) 3840 return 1; 3841 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3842 } 3843 return Tmp2; 3844 } 3845 break; 3846 } 3847 3848 case ISD::SIGN_EXTEND: 3849 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3850 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3851 case ISD::SIGN_EXTEND_INREG: 3852 // Max of the input and what this extends. 3853 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3854 Tmp = VTBits-Tmp+1; 3855 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3856 return std::max(Tmp, Tmp2); 3857 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3858 SDValue Src = Op.getOperand(0); 3859 EVT SrcVT = Src.getValueType(); 3860 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3861 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3862 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3863 } 3864 case ISD::SRA: 3865 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3866 // SRA X, C -> adds C sign bits. 3867 if (const APInt *ShAmt = 3868 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3869 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3870 return Tmp; 3871 case ISD::SHL: 3872 if (const APInt *ShAmt = 3873 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3874 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3875 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3876 if (ShAmt->ult(Tmp)) 3877 return Tmp - ShAmt->getZExtValue(); 3878 } 3879 break; 3880 case ISD::AND: 3881 case ISD::OR: 3882 case ISD::XOR: // NOT is handled here. 3883 // Logical binary ops preserve the number of sign bits at the worst. 3884 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3885 if (Tmp != 1) { 3886 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3887 FirstAnswer = std::min(Tmp, Tmp2); 3888 // We computed what we know about the sign bits as our first 3889 // answer. Now proceed to the generic code that uses 3890 // computeKnownBits, and pick whichever answer is better. 3891 } 3892 break; 3893 3894 case ISD::SELECT: 3895 case ISD::VSELECT: 3896 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3897 if (Tmp == 1) return 1; // Early out. 3898 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3899 return std::min(Tmp, Tmp2); 3900 case ISD::SELECT_CC: 3901 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3902 if (Tmp == 1) return 1; // Early out. 3903 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3904 return std::min(Tmp, Tmp2); 3905 3906 case ISD::SMIN: 3907 case ISD::SMAX: { 3908 // If we have a clamp pattern, we know that the number of sign bits will be 3909 // the minimum of the clamp min/max range. 3910 bool IsMax = (Opcode == ISD::SMAX); 3911 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3912 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3913 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3914 CstHigh = 3915 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3916 if (CstLow && CstHigh) { 3917 if (!IsMax) 3918 std::swap(CstLow, CstHigh); 3919 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3920 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3921 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3922 return std::min(Tmp, Tmp2); 3923 } 3924 } 3925 3926 // Fallback - just get the minimum number of sign bits of the operands. 3927 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3928 if (Tmp == 1) 3929 return 1; // Early out. 3930 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3931 return std::min(Tmp, Tmp2); 3932 } 3933 case ISD::UMIN: 3934 case ISD::UMAX: 3935 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3936 if (Tmp == 1) 3937 return 1; // Early out. 3938 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3939 return std::min(Tmp, Tmp2); 3940 case ISD::SADDO: 3941 case ISD::UADDO: 3942 case ISD::SSUBO: 3943 case ISD::USUBO: 3944 case ISD::SMULO: 3945 case ISD::UMULO: 3946 if (Op.getResNo() != 1) 3947 break; 3948 // The boolean result conforms to getBooleanContents. Fall through. 3949 // If setcc returns 0/-1, all bits are sign bits. 3950 // We know that we have an integer-based boolean since these operations 3951 // are only available for integer. 3952 if (TLI->getBooleanContents(VT.isVector(), false) == 3953 TargetLowering::ZeroOrNegativeOneBooleanContent) 3954 return VTBits; 3955 break; 3956 case ISD::SETCC: 3957 case ISD::STRICT_FSETCC: 3958 case ISD::STRICT_FSETCCS: { 3959 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3960 // If setcc returns 0/-1, all bits are sign bits. 3961 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3962 TargetLowering::ZeroOrNegativeOneBooleanContent) 3963 return VTBits; 3964 break; 3965 } 3966 case ISD::ROTL: 3967 case ISD::ROTR: 3968 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3969 3970 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 3971 if (Tmp == VTBits) 3972 return VTBits; 3973 3974 if (ConstantSDNode *C = 3975 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 3976 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 3977 3978 // Handle rotate right by N like a rotate left by 32-N. 3979 if (Opcode == ISD::ROTR) 3980 RotAmt = (VTBits - RotAmt) % VTBits; 3981 3982 // If we aren't rotating out all of the known-in sign bits, return the 3983 // number that are left. This handles rotl(sext(x), 1) for example. 3984 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 3985 } 3986 break; 3987 case ISD::ADD: 3988 case ISD::ADDC: 3989 // Add can have at most one carry bit. Thus we know that the output 3990 // is, at worst, one more bit than the inputs. 3991 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3992 if (Tmp == 1) return 1; // Early out. 3993 3994 // Special case decrementing a value (ADD X, -1): 3995 if (ConstantSDNode *CRHS = 3996 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 3997 if (CRHS->isAllOnes()) { 3998 KnownBits Known = 3999 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4000 4001 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4002 // sign bits set. 4003 if ((Known.Zero | 1).isAllOnes()) 4004 return VTBits; 4005 4006 // If we are subtracting one from a positive number, there is no carry 4007 // out of the result. 4008 if (Known.isNonNegative()) 4009 return Tmp; 4010 } 4011 4012 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4013 if (Tmp2 == 1) return 1; // Early out. 4014 return std::min(Tmp, Tmp2) - 1; 4015 case ISD::SUB: 4016 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4017 if (Tmp2 == 1) return 1; // Early out. 4018 4019 // Handle NEG. 4020 if (ConstantSDNode *CLHS = 4021 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4022 if (CLHS->isZero()) { 4023 KnownBits Known = 4024 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4025 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4026 // sign bits set. 4027 if ((Known.Zero | 1).isAllOnes()) 4028 return VTBits; 4029 4030 // If the input is known to be positive (the sign bit is known clear), 4031 // the output of the NEG has the same number of sign bits as the input. 4032 if (Known.isNonNegative()) 4033 return Tmp2; 4034 4035 // Otherwise, we treat this like a SUB. 4036 } 4037 4038 // Sub can have at most one carry bit. Thus we know that the output 4039 // is, at worst, one more bit than the inputs. 4040 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4041 if (Tmp == 1) return 1; // Early out. 4042 return std::min(Tmp, Tmp2) - 1; 4043 case ISD::MUL: { 4044 // The output of the Mul can be at most twice the valid bits in the inputs. 4045 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4046 if (SignBitsOp0 == 1) 4047 break; 4048 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4049 if (SignBitsOp1 == 1) 4050 break; 4051 unsigned OutValidBits = 4052 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4053 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4054 } 4055 case ISD::SREM: 4056 // The sign bit is the LHS's sign bit, except when the result of the 4057 // remainder is zero. The magnitude of the result should be less than or 4058 // equal to the magnitude of the LHS. Therefore, the result should have 4059 // at least as many sign bits as the left hand side. 4060 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4061 case ISD::TRUNCATE: { 4062 // Check if the sign bits of source go down as far as the truncated value. 4063 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4064 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4065 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4066 return NumSrcSignBits - (NumSrcBits - VTBits); 4067 break; 4068 } 4069 case ISD::EXTRACT_ELEMENT: { 4070 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4071 const int BitWidth = Op.getValueSizeInBits(); 4072 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4073 4074 // Get reverse index (starting from 1), Op1 value indexes elements from 4075 // little end. Sign starts at big end. 4076 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4077 4078 // If the sign portion ends in our element the subtraction gives correct 4079 // result. Otherwise it gives either negative or > bitwidth result 4080 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4081 } 4082 case ISD::INSERT_VECTOR_ELT: { 4083 // If we know the element index, split the demand between the 4084 // source vector and the inserted element, otherwise assume we need 4085 // the original demanded vector elements and the value. 4086 SDValue InVec = Op.getOperand(0); 4087 SDValue InVal = Op.getOperand(1); 4088 SDValue EltNo = Op.getOperand(2); 4089 bool DemandedVal = true; 4090 APInt DemandedVecElts = DemandedElts; 4091 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4092 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4093 unsigned EltIdx = CEltNo->getZExtValue(); 4094 DemandedVal = !!DemandedElts[EltIdx]; 4095 DemandedVecElts.clearBit(EltIdx); 4096 } 4097 Tmp = std::numeric_limits<unsigned>::max(); 4098 if (DemandedVal) { 4099 // TODO - handle implicit truncation of inserted elements. 4100 if (InVal.getScalarValueSizeInBits() != VTBits) 4101 break; 4102 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4103 Tmp = std::min(Tmp, Tmp2); 4104 } 4105 if (!!DemandedVecElts) { 4106 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4107 Tmp = std::min(Tmp, Tmp2); 4108 } 4109 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4110 return Tmp; 4111 } 4112 case ISD::EXTRACT_VECTOR_ELT: { 4113 SDValue InVec = Op.getOperand(0); 4114 SDValue EltNo = Op.getOperand(1); 4115 EVT VecVT = InVec.getValueType(); 4116 // ComputeNumSignBits not yet implemented for scalable vectors. 4117 if (VecVT.isScalableVector()) 4118 break; 4119 const unsigned BitWidth = Op.getValueSizeInBits(); 4120 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4121 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4122 4123 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4124 // anything about sign bits. But if the sizes match we can derive knowledge 4125 // about sign bits from the vector operand. 4126 if (BitWidth != EltBitWidth) 4127 break; 4128 4129 // If we know the element index, just demand that vector element, else for 4130 // an unknown element index, ignore DemandedElts and demand them all. 4131 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4132 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4133 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4134 DemandedSrcElts = 4135 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4136 4137 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4138 } 4139 case ISD::EXTRACT_SUBVECTOR: { 4140 // Offset the demanded elts by the subvector index. 4141 SDValue Src = Op.getOperand(0); 4142 // Bail until we can represent demanded elements for scalable vectors. 4143 if (Src.getValueType().isScalableVector()) 4144 break; 4145 uint64_t Idx = Op.getConstantOperandVal(1); 4146 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4147 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4148 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4149 } 4150 case ISD::CONCAT_VECTORS: { 4151 // Determine the minimum number of sign bits across all demanded 4152 // elts of the input vectors. Early out if the result is already 1. 4153 Tmp = std::numeric_limits<unsigned>::max(); 4154 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4155 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4156 unsigned NumSubVectors = Op.getNumOperands(); 4157 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4158 APInt DemandedSub = 4159 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4160 if (!DemandedSub) 4161 continue; 4162 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4163 Tmp = std::min(Tmp, Tmp2); 4164 } 4165 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4166 return Tmp; 4167 } 4168 case ISD::INSERT_SUBVECTOR: { 4169 // Demand any elements from the subvector and the remainder from the src its 4170 // inserted into. 4171 SDValue Src = Op.getOperand(0); 4172 SDValue Sub = Op.getOperand(1); 4173 uint64_t Idx = Op.getConstantOperandVal(2); 4174 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4175 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4176 APInt DemandedSrcElts = DemandedElts; 4177 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4178 4179 Tmp = std::numeric_limits<unsigned>::max(); 4180 if (!!DemandedSubElts) { 4181 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4182 if (Tmp == 1) 4183 return 1; // early-out 4184 } 4185 if (!!DemandedSrcElts) { 4186 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4187 Tmp = std::min(Tmp, Tmp2); 4188 } 4189 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4190 return Tmp; 4191 } 4192 case ISD::ATOMIC_CMP_SWAP: 4193 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4194 case ISD::ATOMIC_SWAP: 4195 case ISD::ATOMIC_LOAD_ADD: 4196 case ISD::ATOMIC_LOAD_SUB: 4197 case ISD::ATOMIC_LOAD_AND: 4198 case ISD::ATOMIC_LOAD_CLR: 4199 case ISD::ATOMIC_LOAD_OR: 4200 case ISD::ATOMIC_LOAD_XOR: 4201 case ISD::ATOMIC_LOAD_NAND: 4202 case ISD::ATOMIC_LOAD_MIN: 4203 case ISD::ATOMIC_LOAD_MAX: 4204 case ISD::ATOMIC_LOAD_UMIN: 4205 case ISD::ATOMIC_LOAD_UMAX: 4206 case ISD::ATOMIC_LOAD: { 4207 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4208 // If we are looking at the loaded value. 4209 if (Op.getResNo() == 0) { 4210 if (Tmp == VTBits) 4211 return 1; // early-out 4212 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4213 return VTBits - Tmp + 1; 4214 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4215 return VTBits - Tmp; 4216 } 4217 break; 4218 } 4219 } 4220 4221 // If we are looking at the loaded value of the SDNode. 4222 if (Op.getResNo() == 0) { 4223 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4224 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4225 unsigned ExtType = LD->getExtensionType(); 4226 switch (ExtType) { 4227 default: break; 4228 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4229 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4230 return VTBits - Tmp + 1; 4231 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4232 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4233 return VTBits - Tmp; 4234 case ISD::NON_EXTLOAD: 4235 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4236 // We only need to handle vectors - computeKnownBits should handle 4237 // scalar cases. 4238 Type *CstTy = Cst->getType(); 4239 if (CstTy->isVectorTy() && 4240 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) { 4241 Tmp = VTBits; 4242 for (unsigned i = 0; i != NumElts; ++i) { 4243 if (!DemandedElts[i]) 4244 continue; 4245 if (Constant *Elt = Cst->getAggregateElement(i)) { 4246 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4247 const APInt &Value = CInt->getValue(); 4248 Tmp = std::min(Tmp, Value.getNumSignBits()); 4249 continue; 4250 } 4251 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4252 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4253 Tmp = std::min(Tmp, Value.getNumSignBits()); 4254 continue; 4255 } 4256 } 4257 // Unknown type. Conservatively assume no bits match sign bit. 4258 return 1; 4259 } 4260 return Tmp; 4261 } 4262 } 4263 break; 4264 } 4265 } 4266 } 4267 4268 // Allow the target to implement this method for its nodes. 4269 if (Opcode >= ISD::BUILTIN_OP_END || 4270 Opcode == ISD::INTRINSIC_WO_CHAIN || 4271 Opcode == ISD::INTRINSIC_W_CHAIN || 4272 Opcode == ISD::INTRINSIC_VOID) { 4273 unsigned NumBits = 4274 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4275 if (NumBits > 1) 4276 FirstAnswer = std::max(FirstAnswer, NumBits); 4277 } 4278 4279 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4280 // use this information. 4281 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4282 4283 APInt Mask; 4284 if (Known.isNonNegative()) { // sign bit is 0 4285 Mask = Known.Zero; 4286 } else if (Known.isNegative()) { // sign bit is 1; 4287 Mask = Known.One; 4288 } else { 4289 // Nothing known. 4290 return FirstAnswer; 4291 } 4292 4293 // Okay, we know that the sign bit in Mask is set. Use CLO to determine 4294 // the number of identical bits in the top of the input value. 4295 Mask <<= Mask.getBitWidth()-VTBits; 4296 return std::max(FirstAnswer, Mask.countLeadingOnes()); 4297 } 4298 4299 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4300 unsigned Depth) const { 4301 // Early out for FREEZE. 4302 if (Op.getOpcode() == ISD::FREEZE) 4303 return true; 4304 4305 // TODO: Assume we don't know anything for now. 4306 EVT VT = Op.getValueType(); 4307 if (VT.isScalableVector()) 4308 return false; 4309 4310 APInt DemandedElts = VT.isVector() 4311 ? APInt::getAllOnes(VT.getVectorNumElements()) 4312 : APInt(1, 1); 4313 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4314 } 4315 4316 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4317 const APInt &DemandedElts, 4318 bool PoisonOnly, 4319 unsigned Depth) const { 4320 unsigned Opcode = Op.getOpcode(); 4321 4322 // Early out for FREEZE. 4323 if (Opcode == ISD::FREEZE) 4324 return true; 4325 4326 if (Depth >= MaxRecursionDepth) 4327 return false; // Limit search depth. 4328 4329 if (isIntOrFPConstant(Op)) 4330 return true; 4331 4332 switch (Opcode) { 4333 case ISD::UNDEF: 4334 return PoisonOnly; 4335 4336 case ISD::BUILD_VECTOR: 4337 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4338 // this shouldn't affect the result. 4339 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4340 if (!DemandedElts[i]) 4341 continue; 4342 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4343 Depth + 1)) 4344 return false; 4345 } 4346 return true; 4347 4348 // TODO: Search for noundef attributes from library functions. 4349 4350 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4351 4352 default: 4353 // Allow the target to implement this method for its nodes. 4354 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4355 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4356 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4357 Op, DemandedElts, *this, PoisonOnly, Depth); 4358 break; 4359 } 4360 4361 return false; 4362 } 4363 4364 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4365 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4366 !isa<ConstantSDNode>(Op.getOperand(1))) 4367 return false; 4368 4369 if (Op.getOpcode() == ISD::OR && 4370 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4371 return false; 4372 4373 return true; 4374 } 4375 4376 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4377 // If we're told that NaNs won't happen, assume they won't. 4378 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4379 return true; 4380 4381 if (Depth >= MaxRecursionDepth) 4382 return false; // Limit search depth. 4383 4384 // TODO: Handle vectors. 4385 // If the value is a constant, we can obviously see if it is a NaN or not. 4386 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4387 return !C->getValueAPF().isNaN() || 4388 (SNaN && !C->getValueAPF().isSignaling()); 4389 } 4390 4391 unsigned Opcode = Op.getOpcode(); 4392 switch (Opcode) { 4393 case ISD::FADD: 4394 case ISD::FSUB: 4395 case ISD::FMUL: 4396 case ISD::FDIV: 4397 case ISD::FREM: 4398 case ISD::FSIN: 4399 case ISD::FCOS: { 4400 if (SNaN) 4401 return true; 4402 // TODO: Need isKnownNeverInfinity 4403 return false; 4404 } 4405 case ISD::FCANONICALIZE: 4406 case ISD::FEXP: 4407 case ISD::FEXP2: 4408 case ISD::FTRUNC: 4409 case ISD::FFLOOR: 4410 case ISD::FCEIL: 4411 case ISD::FROUND: 4412 case ISD::FROUNDEVEN: 4413 case ISD::FRINT: 4414 case ISD::FNEARBYINT: { 4415 if (SNaN) 4416 return true; 4417 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4418 } 4419 case ISD::FABS: 4420 case ISD::FNEG: 4421 case ISD::FCOPYSIGN: { 4422 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4423 } 4424 case ISD::SELECT: 4425 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4426 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4427 case ISD::FP_EXTEND: 4428 case ISD::FP_ROUND: { 4429 if (SNaN) 4430 return true; 4431 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4432 } 4433 case ISD::SINT_TO_FP: 4434 case ISD::UINT_TO_FP: 4435 return true; 4436 case ISD::FMA: 4437 case ISD::FMAD: { 4438 if (SNaN) 4439 return true; 4440 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4441 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4442 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4443 } 4444 case ISD::FSQRT: // Need is known positive 4445 case ISD::FLOG: 4446 case ISD::FLOG2: 4447 case ISD::FLOG10: 4448 case ISD::FPOWI: 4449 case ISD::FPOW: { 4450 if (SNaN) 4451 return true; 4452 // TODO: Refine on operand 4453 return false; 4454 } 4455 case ISD::FMINNUM: 4456 case ISD::FMAXNUM: { 4457 // Only one needs to be known not-nan, since it will be returned if the 4458 // other ends up being one. 4459 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4460 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4461 } 4462 case ISD::FMINNUM_IEEE: 4463 case ISD::FMAXNUM_IEEE: { 4464 if (SNaN) 4465 return true; 4466 // This can return a NaN if either operand is an sNaN, or if both operands 4467 // are NaN. 4468 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4469 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4470 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4471 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4472 } 4473 case ISD::FMINIMUM: 4474 case ISD::FMAXIMUM: { 4475 // TODO: Does this quiet or return the origina NaN as-is? 4476 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4477 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4478 } 4479 case ISD::EXTRACT_VECTOR_ELT: { 4480 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4481 } 4482 default: 4483 if (Opcode >= ISD::BUILTIN_OP_END || 4484 Opcode == ISD::INTRINSIC_WO_CHAIN || 4485 Opcode == ISD::INTRINSIC_W_CHAIN || 4486 Opcode == ISD::INTRINSIC_VOID) { 4487 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4488 } 4489 4490 return false; 4491 } 4492 } 4493 4494 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4495 assert(Op.getValueType().isFloatingPoint() && 4496 "Floating point type expected"); 4497 4498 // If the value is a constant, we can obviously see if it is a zero or not. 4499 // TODO: Add BuildVector support. 4500 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4501 return !C->isZero(); 4502 return false; 4503 } 4504 4505 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4506 assert(!Op.getValueType().isFloatingPoint() && 4507 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4508 4509 // If the value is a constant, we can obviously see if it is a zero or not. 4510 if (ISD::matchUnaryPredicate(Op, 4511 [](ConstantSDNode *C) { return !C->isZero(); })) 4512 return true; 4513 4514 // TODO: Recognize more cases here. 4515 switch (Op.getOpcode()) { 4516 default: break; 4517 case ISD::OR: 4518 if (isKnownNeverZero(Op.getOperand(1)) || 4519 isKnownNeverZero(Op.getOperand(0))) 4520 return true; 4521 break; 4522 } 4523 4524 return false; 4525 } 4526 4527 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4528 // Check the obvious case. 4529 if (A == B) return true; 4530 4531 // For for negative and positive zero. 4532 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4533 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4534 if (CA->isZero() && CB->isZero()) return true; 4535 4536 // Otherwise they may not be equal. 4537 return false; 4538 } 4539 4540 // FIXME: unify with llvm::haveNoCommonBitsSet. 4541 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M) 4542 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4543 assert(A.getValueType() == B.getValueType() && 4544 "Values must have the same type"); 4545 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4546 computeKnownBits(B)); 4547 } 4548 4549 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4550 SelectionDAG &DAG) { 4551 if (cast<ConstantSDNode>(Step)->isZero()) 4552 return DAG.getConstant(0, DL, VT); 4553 4554 return SDValue(); 4555 } 4556 4557 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4558 ArrayRef<SDValue> Ops, 4559 SelectionDAG &DAG) { 4560 int NumOps = Ops.size(); 4561 assert(NumOps != 0 && "Can't build an empty vector!"); 4562 assert(!VT.isScalableVector() && 4563 "BUILD_VECTOR cannot be used with scalable types"); 4564 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4565 "Incorrect element count in BUILD_VECTOR!"); 4566 4567 // BUILD_VECTOR of UNDEFs is UNDEF. 4568 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4569 return DAG.getUNDEF(VT); 4570 4571 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4572 SDValue IdentitySrc; 4573 bool IsIdentity = true; 4574 for (int i = 0; i != NumOps; ++i) { 4575 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4576 Ops[i].getOperand(0).getValueType() != VT || 4577 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4578 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4579 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4580 IsIdentity = false; 4581 break; 4582 } 4583 IdentitySrc = Ops[i].getOperand(0); 4584 } 4585 if (IsIdentity) 4586 return IdentitySrc; 4587 4588 return SDValue(); 4589 } 4590 4591 /// Try to simplify vector concatenation to an input value, undef, or build 4592 /// vector. 4593 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4594 ArrayRef<SDValue> Ops, 4595 SelectionDAG &DAG) { 4596 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4597 assert(llvm::all_of(Ops, 4598 [Ops](SDValue Op) { 4599 return Ops[0].getValueType() == Op.getValueType(); 4600 }) && 4601 "Concatenation of vectors with inconsistent value types!"); 4602 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4603 VT.getVectorElementCount() && 4604 "Incorrect element count in vector concatenation!"); 4605 4606 if (Ops.size() == 1) 4607 return Ops[0]; 4608 4609 // Concat of UNDEFs is UNDEF. 4610 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4611 return DAG.getUNDEF(VT); 4612 4613 // Scan the operands and look for extract operations from a single source 4614 // that correspond to insertion at the same location via this concatenation: 4615 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4616 SDValue IdentitySrc; 4617 bool IsIdentity = true; 4618 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4619 SDValue Op = Ops[i]; 4620 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4621 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4622 Op.getOperand(0).getValueType() != VT || 4623 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4624 Op.getConstantOperandVal(1) != IdentityIndex) { 4625 IsIdentity = false; 4626 break; 4627 } 4628 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4629 "Unexpected identity source vector for concat of extracts"); 4630 IdentitySrc = Op.getOperand(0); 4631 } 4632 if (IsIdentity) { 4633 assert(IdentitySrc && "Failed to set source vector of extracts"); 4634 return IdentitySrc; 4635 } 4636 4637 // The code below this point is only designed to work for fixed width 4638 // vectors, so we bail out for now. 4639 if (VT.isScalableVector()) 4640 return SDValue(); 4641 4642 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4643 // simplified to one big BUILD_VECTOR. 4644 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4645 EVT SVT = VT.getScalarType(); 4646 SmallVector<SDValue, 16> Elts; 4647 for (SDValue Op : Ops) { 4648 EVT OpVT = Op.getValueType(); 4649 if (Op.isUndef()) 4650 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4651 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4652 Elts.append(Op->op_begin(), Op->op_end()); 4653 else 4654 return SDValue(); 4655 } 4656 4657 // BUILD_VECTOR requires all inputs to be of the same type, find the 4658 // maximum type and extend them all. 4659 for (SDValue Op : Elts) 4660 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4661 4662 if (SVT.bitsGT(VT.getScalarType())) { 4663 for (SDValue &Op : Elts) { 4664 if (Op.isUndef()) 4665 Op = DAG.getUNDEF(SVT); 4666 else 4667 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4668 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4669 : DAG.getSExtOrTrunc(Op, DL, SVT); 4670 } 4671 } 4672 4673 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4674 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4675 return V; 4676 } 4677 4678 /// Gets or creates the specified node. 4679 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4680 FoldingSetNodeID ID; 4681 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4682 void *IP = nullptr; 4683 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4684 return SDValue(E, 0); 4685 4686 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4687 getVTList(VT)); 4688 CSEMap.InsertNode(N, IP); 4689 4690 InsertNode(N); 4691 SDValue V = SDValue(N, 0); 4692 NewSDValueDbgMsg(V, "Creating new node: ", this); 4693 return V; 4694 } 4695 4696 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4697 SDValue Operand) { 4698 SDNodeFlags Flags; 4699 if (Inserter) 4700 Flags = Inserter->getFlags(); 4701 return getNode(Opcode, DL, VT, Operand, Flags); 4702 } 4703 4704 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4705 SDValue Operand, const SDNodeFlags Flags) { 4706 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4707 "Operand is DELETED_NODE!"); 4708 // Constant fold unary operations with an integer constant operand. Even 4709 // opaque constant will be folded, because the folding of unary operations 4710 // doesn't create new constants with different values. Nevertheless, the 4711 // opaque flag is preserved during folding to prevent future folding with 4712 // other constants. 4713 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4714 const APInt &Val = C->getAPIntValue(); 4715 switch (Opcode) { 4716 default: break; 4717 case ISD::SIGN_EXTEND: 4718 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4719 C->isTargetOpcode(), C->isOpaque()); 4720 case ISD::TRUNCATE: 4721 if (C->isOpaque()) 4722 break; 4723 LLVM_FALLTHROUGH; 4724 case ISD::ZERO_EXTEND: 4725 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4726 C->isTargetOpcode(), C->isOpaque()); 4727 case ISD::ANY_EXTEND: 4728 // Some targets like RISCV prefer to sign extend some types. 4729 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4730 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4731 C->isTargetOpcode(), C->isOpaque()); 4732 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4733 C->isTargetOpcode(), C->isOpaque()); 4734 case ISD::UINT_TO_FP: 4735 case ISD::SINT_TO_FP: { 4736 APFloat apf(EVTToAPFloatSemantics(VT), 4737 APInt::getZero(VT.getSizeInBits())); 4738 (void)apf.convertFromAPInt(Val, 4739 Opcode==ISD::SINT_TO_FP, 4740 APFloat::rmNearestTiesToEven); 4741 return getConstantFP(apf, DL, VT); 4742 } 4743 case ISD::BITCAST: 4744 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4745 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4746 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4747 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4748 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4749 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4750 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4751 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4752 break; 4753 case ISD::ABS: 4754 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4755 C->isOpaque()); 4756 case ISD::BITREVERSE: 4757 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4758 C->isOpaque()); 4759 case ISD::BSWAP: 4760 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4761 C->isOpaque()); 4762 case ISD::CTPOP: 4763 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4764 C->isOpaque()); 4765 case ISD::CTLZ: 4766 case ISD::CTLZ_ZERO_UNDEF: 4767 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4768 C->isOpaque()); 4769 case ISD::CTTZ: 4770 case ISD::CTTZ_ZERO_UNDEF: 4771 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4772 C->isOpaque()); 4773 case ISD::FP16_TO_FP: { 4774 bool Ignored; 4775 APFloat FPV(APFloat::IEEEhalf(), 4776 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4777 4778 // This can return overflow, underflow, or inexact; we don't care. 4779 // FIXME need to be more flexible about rounding mode. 4780 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4781 APFloat::rmNearestTiesToEven, &Ignored); 4782 return getConstantFP(FPV, DL, VT); 4783 } 4784 case ISD::STEP_VECTOR: { 4785 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4786 return V; 4787 break; 4788 } 4789 } 4790 } 4791 4792 // Constant fold unary operations with a floating point constant operand. 4793 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4794 APFloat V = C->getValueAPF(); // make copy 4795 switch (Opcode) { 4796 case ISD::FNEG: 4797 V.changeSign(); 4798 return getConstantFP(V, DL, VT); 4799 case ISD::FABS: 4800 V.clearSign(); 4801 return getConstantFP(V, DL, VT); 4802 case ISD::FCEIL: { 4803 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4804 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4805 return getConstantFP(V, DL, VT); 4806 break; 4807 } 4808 case ISD::FTRUNC: { 4809 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4810 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4811 return getConstantFP(V, DL, VT); 4812 break; 4813 } 4814 case ISD::FFLOOR: { 4815 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4816 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4817 return getConstantFP(V, DL, VT); 4818 break; 4819 } 4820 case ISD::FP_EXTEND: { 4821 bool ignored; 4822 // This can return overflow, underflow, or inexact; we don't care. 4823 // FIXME need to be more flexible about rounding mode. 4824 (void)V.convert(EVTToAPFloatSemantics(VT), 4825 APFloat::rmNearestTiesToEven, &ignored); 4826 return getConstantFP(V, DL, VT); 4827 } 4828 case ISD::FP_TO_SINT: 4829 case ISD::FP_TO_UINT: { 4830 bool ignored; 4831 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4832 // FIXME need to be more flexible about rounding mode. 4833 APFloat::opStatus s = 4834 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4835 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4836 break; 4837 return getConstant(IntVal, DL, VT); 4838 } 4839 case ISD::BITCAST: 4840 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4841 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4842 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4843 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4844 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4845 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4846 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4847 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4848 break; 4849 case ISD::FP_TO_FP16: { 4850 bool Ignored; 4851 // This can return overflow, underflow, or inexact; we don't care. 4852 // FIXME need to be more flexible about rounding mode. 4853 (void)V.convert(APFloat::IEEEhalf(), 4854 APFloat::rmNearestTiesToEven, &Ignored); 4855 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4856 } 4857 } 4858 } 4859 4860 // Constant fold unary operations with a vector integer or float operand. 4861 switch (Opcode) { 4862 default: 4863 // FIXME: Entirely reasonable to perform folding of other unary 4864 // operations here as the need arises. 4865 break; 4866 case ISD::FNEG: 4867 case ISD::FABS: 4868 case ISD::FCEIL: 4869 case ISD::FTRUNC: 4870 case ISD::FFLOOR: 4871 case ISD::FP_EXTEND: 4872 case ISD::FP_TO_SINT: 4873 case ISD::FP_TO_UINT: 4874 case ISD::TRUNCATE: 4875 case ISD::ANY_EXTEND: 4876 case ISD::ZERO_EXTEND: 4877 case ISD::SIGN_EXTEND: 4878 case ISD::UINT_TO_FP: 4879 case ISD::SINT_TO_FP: 4880 case ISD::ABS: 4881 case ISD::BITREVERSE: 4882 case ISD::BSWAP: 4883 case ISD::CTLZ: 4884 case ISD::CTLZ_ZERO_UNDEF: 4885 case ISD::CTTZ: 4886 case ISD::CTTZ_ZERO_UNDEF: 4887 case ISD::CTPOP: { 4888 SDValue Ops = {Operand}; 4889 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 4890 return Fold; 4891 } 4892 } 4893 4894 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4895 switch (Opcode) { 4896 case ISD::STEP_VECTOR: 4897 assert(VT.isScalableVector() && 4898 "STEP_VECTOR can only be used with scalable types"); 4899 assert(OpOpcode == ISD::TargetConstant && 4900 VT.getVectorElementType() == Operand.getValueType() && 4901 "Unexpected step operand"); 4902 break; 4903 case ISD::FREEZE: 4904 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4905 break; 4906 case ISD::TokenFactor: 4907 case ISD::MERGE_VALUES: 4908 case ISD::CONCAT_VECTORS: 4909 return Operand; // Factor, merge or concat of one node? No need. 4910 case ISD::BUILD_VECTOR: { 4911 // Attempt to simplify BUILD_VECTOR. 4912 SDValue Ops[] = {Operand}; 4913 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4914 return V; 4915 break; 4916 } 4917 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4918 case ISD::FP_EXTEND: 4919 assert(VT.isFloatingPoint() && 4920 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4921 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4922 assert((!VT.isVector() || 4923 VT.getVectorElementCount() == 4924 Operand.getValueType().getVectorElementCount()) && 4925 "Vector element count mismatch!"); 4926 assert(Operand.getValueType().bitsLT(VT) && 4927 "Invalid fpext node, dst < src!"); 4928 if (Operand.isUndef()) 4929 return getUNDEF(VT); 4930 break; 4931 case ISD::FP_TO_SINT: 4932 case ISD::FP_TO_UINT: 4933 if (Operand.isUndef()) 4934 return getUNDEF(VT); 4935 break; 4936 case ISD::SINT_TO_FP: 4937 case ISD::UINT_TO_FP: 4938 // [us]itofp(undef) = 0, because the result value is bounded. 4939 if (Operand.isUndef()) 4940 return getConstantFP(0.0, DL, VT); 4941 break; 4942 case ISD::SIGN_EXTEND: 4943 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4944 "Invalid SIGN_EXTEND!"); 4945 assert(VT.isVector() == Operand.getValueType().isVector() && 4946 "SIGN_EXTEND result type type should be vector iff the operand " 4947 "type is vector!"); 4948 if (Operand.getValueType() == VT) return Operand; // noop extension 4949 assert((!VT.isVector() || 4950 VT.getVectorElementCount() == 4951 Operand.getValueType().getVectorElementCount()) && 4952 "Vector element count mismatch!"); 4953 assert(Operand.getValueType().bitsLT(VT) && 4954 "Invalid sext node, dst < src!"); 4955 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 4956 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4957 if (OpOpcode == ISD::UNDEF) 4958 // sext(undef) = 0, because the top bits will all be the same. 4959 return getConstant(0, DL, VT); 4960 break; 4961 case ISD::ZERO_EXTEND: 4962 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4963 "Invalid ZERO_EXTEND!"); 4964 assert(VT.isVector() == Operand.getValueType().isVector() && 4965 "ZERO_EXTEND result type type should be vector iff the operand " 4966 "type is vector!"); 4967 if (Operand.getValueType() == VT) return Operand; // noop extension 4968 assert((!VT.isVector() || 4969 VT.getVectorElementCount() == 4970 Operand.getValueType().getVectorElementCount()) && 4971 "Vector element count mismatch!"); 4972 assert(Operand.getValueType().bitsLT(VT) && 4973 "Invalid zext node, dst < src!"); 4974 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 4975 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 4976 if (OpOpcode == ISD::UNDEF) 4977 // zext(undef) = 0, because the top bits will be zero. 4978 return getConstant(0, DL, VT); 4979 break; 4980 case ISD::ANY_EXTEND: 4981 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4982 "Invalid ANY_EXTEND!"); 4983 assert(VT.isVector() == Operand.getValueType().isVector() && 4984 "ANY_EXTEND result type type should be vector iff the operand " 4985 "type is vector!"); 4986 if (Operand.getValueType() == VT) return Operand; // noop extension 4987 assert((!VT.isVector() || 4988 VT.getVectorElementCount() == 4989 Operand.getValueType().getVectorElementCount()) && 4990 "Vector element count mismatch!"); 4991 assert(Operand.getValueType().bitsLT(VT) && 4992 "Invalid anyext node, dst < src!"); 4993 4994 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4995 OpOpcode == ISD::ANY_EXTEND) 4996 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 4997 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4998 if (OpOpcode == ISD::UNDEF) 4999 return getUNDEF(VT); 5000 5001 // (ext (trunc x)) -> x 5002 if (OpOpcode == ISD::TRUNCATE) { 5003 SDValue OpOp = Operand.getOperand(0); 5004 if (OpOp.getValueType() == VT) { 5005 transferDbgValues(Operand, OpOp); 5006 return OpOp; 5007 } 5008 } 5009 break; 5010 case ISD::TRUNCATE: 5011 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5012 "Invalid TRUNCATE!"); 5013 assert(VT.isVector() == Operand.getValueType().isVector() && 5014 "TRUNCATE result type type should be vector iff the operand " 5015 "type is vector!"); 5016 if (Operand.getValueType() == VT) return Operand; // noop truncate 5017 assert((!VT.isVector() || 5018 VT.getVectorElementCount() == 5019 Operand.getValueType().getVectorElementCount()) && 5020 "Vector element count mismatch!"); 5021 assert(Operand.getValueType().bitsGT(VT) && 5022 "Invalid truncate node, src < dst!"); 5023 if (OpOpcode == ISD::TRUNCATE) 5024 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5025 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5026 OpOpcode == ISD::ANY_EXTEND) { 5027 // If the source is smaller than the dest, we still need an extend. 5028 if (Operand.getOperand(0).getValueType().getScalarType() 5029 .bitsLT(VT.getScalarType())) 5030 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5031 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5032 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5033 return Operand.getOperand(0); 5034 } 5035 if (OpOpcode == ISD::UNDEF) 5036 return getUNDEF(VT); 5037 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5038 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5039 break; 5040 case ISD::ANY_EXTEND_VECTOR_INREG: 5041 case ISD::ZERO_EXTEND_VECTOR_INREG: 5042 case ISD::SIGN_EXTEND_VECTOR_INREG: 5043 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5044 assert(Operand.getValueType().bitsLE(VT) && 5045 "The input must be the same size or smaller than the result."); 5046 assert(VT.getVectorMinNumElements() < 5047 Operand.getValueType().getVectorMinNumElements() && 5048 "The destination vector type must have fewer lanes than the input."); 5049 break; 5050 case ISD::ABS: 5051 assert(VT.isInteger() && VT == Operand.getValueType() && 5052 "Invalid ABS!"); 5053 if (OpOpcode == ISD::UNDEF) 5054 return getUNDEF(VT); 5055 break; 5056 case ISD::BSWAP: 5057 assert(VT.isInteger() && VT == Operand.getValueType() && 5058 "Invalid BSWAP!"); 5059 assert((VT.getScalarSizeInBits() % 16 == 0) && 5060 "BSWAP types must be a multiple of 16 bits!"); 5061 if (OpOpcode == ISD::UNDEF) 5062 return getUNDEF(VT); 5063 break; 5064 case ISD::BITREVERSE: 5065 assert(VT.isInteger() && VT == Operand.getValueType() && 5066 "Invalid BITREVERSE!"); 5067 if (OpOpcode == ISD::UNDEF) 5068 return getUNDEF(VT); 5069 break; 5070 case ISD::BITCAST: 5071 // Basic sanity checking. 5072 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5073 "Cannot BITCAST between types of different sizes!"); 5074 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5075 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5076 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5077 if (OpOpcode == ISD::UNDEF) 5078 return getUNDEF(VT); 5079 break; 5080 case ISD::SCALAR_TO_VECTOR: 5081 assert(VT.isVector() && !Operand.getValueType().isVector() && 5082 (VT.getVectorElementType() == Operand.getValueType() || 5083 (VT.getVectorElementType().isInteger() && 5084 Operand.getValueType().isInteger() && 5085 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5086 "Illegal SCALAR_TO_VECTOR node!"); 5087 if (OpOpcode == ISD::UNDEF) 5088 return getUNDEF(VT); 5089 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5090 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5091 isa<ConstantSDNode>(Operand.getOperand(1)) && 5092 Operand.getConstantOperandVal(1) == 0 && 5093 Operand.getOperand(0).getValueType() == VT) 5094 return Operand.getOperand(0); 5095 break; 5096 case ISD::FNEG: 5097 // Negation of an unknown bag of bits is still completely undefined. 5098 if (OpOpcode == ISD::UNDEF) 5099 return getUNDEF(VT); 5100 5101 if (OpOpcode == ISD::FNEG) // --X -> X 5102 return Operand.getOperand(0); 5103 break; 5104 case ISD::FABS: 5105 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5106 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5107 break; 5108 case ISD::VSCALE: 5109 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5110 break; 5111 case ISD::CTPOP: 5112 if (Operand.getValueType().getScalarType() == MVT::i1) 5113 return Operand; 5114 break; 5115 case ISD::CTLZ: 5116 case ISD::CTTZ: 5117 if (Operand.getValueType().getScalarType() == MVT::i1) 5118 return getNOT(DL, Operand, Operand.getValueType()); 5119 break; 5120 case ISD::VECREDUCE_SMIN: 5121 case ISD::VECREDUCE_UMAX: 5122 if (Operand.getValueType().getScalarType() == MVT::i1) 5123 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5124 break; 5125 case ISD::VECREDUCE_SMAX: 5126 case ISD::VECREDUCE_UMIN: 5127 if (Operand.getValueType().getScalarType() == MVT::i1) 5128 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5129 break; 5130 } 5131 5132 SDNode *N; 5133 SDVTList VTs = getVTList(VT); 5134 SDValue Ops[] = {Operand}; 5135 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5136 FoldingSetNodeID ID; 5137 AddNodeIDNode(ID, Opcode, VTs, Ops); 5138 void *IP = nullptr; 5139 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5140 E->intersectFlagsWith(Flags); 5141 return SDValue(E, 0); 5142 } 5143 5144 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5145 N->setFlags(Flags); 5146 createOperands(N, Ops); 5147 CSEMap.InsertNode(N, IP); 5148 } else { 5149 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5150 createOperands(N, Ops); 5151 } 5152 5153 InsertNode(N); 5154 SDValue V = SDValue(N, 0); 5155 NewSDValueDbgMsg(V, "Creating new node: ", this); 5156 return V; 5157 } 5158 5159 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5160 const APInt &C2) { 5161 switch (Opcode) { 5162 case ISD::ADD: return C1 + C2; 5163 case ISD::SUB: return C1 - C2; 5164 case ISD::MUL: return C1 * C2; 5165 case ISD::AND: return C1 & C2; 5166 case ISD::OR: return C1 | C2; 5167 case ISD::XOR: return C1 ^ C2; 5168 case ISD::SHL: return C1 << C2; 5169 case ISD::SRL: return C1.lshr(C2); 5170 case ISD::SRA: return C1.ashr(C2); 5171 case ISD::ROTL: return C1.rotl(C2); 5172 case ISD::ROTR: return C1.rotr(C2); 5173 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5174 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5175 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5176 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5177 case ISD::SADDSAT: return C1.sadd_sat(C2); 5178 case ISD::UADDSAT: return C1.uadd_sat(C2); 5179 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5180 case ISD::USUBSAT: return C1.usub_sat(C2); 5181 case ISD::UDIV: 5182 if (!C2.getBoolValue()) 5183 break; 5184 return C1.udiv(C2); 5185 case ISD::UREM: 5186 if (!C2.getBoolValue()) 5187 break; 5188 return C1.urem(C2); 5189 case ISD::SDIV: 5190 if (!C2.getBoolValue()) 5191 break; 5192 return C1.sdiv(C2); 5193 case ISD::SREM: 5194 if (!C2.getBoolValue()) 5195 break; 5196 return C1.srem(C2); 5197 case ISD::MULHS: { 5198 unsigned FullWidth = C1.getBitWidth() * 2; 5199 APInt C1Ext = C1.sext(FullWidth); 5200 APInt C2Ext = C2.sext(FullWidth); 5201 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5202 } 5203 case ISD::MULHU: { 5204 unsigned FullWidth = C1.getBitWidth() * 2; 5205 APInt C1Ext = C1.zext(FullWidth); 5206 APInt C2Ext = C2.zext(FullWidth); 5207 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5208 } 5209 } 5210 return llvm::None; 5211 } 5212 5213 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5214 const GlobalAddressSDNode *GA, 5215 const SDNode *N2) { 5216 if (GA->getOpcode() != ISD::GlobalAddress) 5217 return SDValue(); 5218 if (!TLI->isOffsetFoldingLegal(GA)) 5219 return SDValue(); 5220 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5221 if (!C2) 5222 return SDValue(); 5223 int64_t Offset = C2->getSExtValue(); 5224 switch (Opcode) { 5225 case ISD::ADD: break; 5226 case ISD::SUB: Offset = -uint64_t(Offset); break; 5227 default: return SDValue(); 5228 } 5229 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5230 GA->getOffset() + uint64_t(Offset)); 5231 } 5232 5233 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5234 switch (Opcode) { 5235 case ISD::SDIV: 5236 case ISD::UDIV: 5237 case ISD::SREM: 5238 case ISD::UREM: { 5239 // If a divisor is zero/undef or any element of a divisor vector is 5240 // zero/undef, the whole op is undef. 5241 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5242 SDValue Divisor = Ops[1]; 5243 if (Divisor.isUndef() || isNullConstant(Divisor)) 5244 return true; 5245 5246 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5247 llvm::any_of(Divisor->op_values(), 5248 [](SDValue V) { return V.isUndef() || 5249 isNullConstant(V); }); 5250 // TODO: Handle signed overflow. 5251 } 5252 // TODO: Handle oversized shifts. 5253 default: 5254 return false; 5255 } 5256 } 5257 5258 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5259 EVT VT, ArrayRef<SDValue> Ops) { 5260 // If the opcode is a target-specific ISD node, there's nothing we can 5261 // do here and the operand rules may not line up with the below, so 5262 // bail early. 5263 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5264 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5265 // foldCONCAT_VECTORS in getNode before this is called. 5266 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5267 return SDValue(); 5268 5269 // For now, the array Ops should only contain two values. 5270 // This enforcement will be removed once this function is merged with 5271 // FoldConstantVectorArithmetic 5272 if (Ops.size() != 2) 5273 return SDValue(); 5274 5275 if (isUndef(Opcode, Ops)) 5276 return getUNDEF(VT); 5277 5278 SDNode *N1 = Ops[0].getNode(); 5279 SDNode *N2 = Ops[1].getNode(); 5280 5281 // Handle the case of two scalars. 5282 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) { 5283 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) { 5284 if (C1->isOpaque() || C2->isOpaque()) 5285 return SDValue(); 5286 5287 Optional<APInt> FoldAttempt = 5288 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5289 if (!FoldAttempt) 5290 return SDValue(); 5291 5292 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5293 assert((!Folded || !VT.isVector()) && 5294 "Can't fold vectors ops with scalar operands"); 5295 return Folded; 5296 } 5297 } 5298 5299 // fold (add Sym, c) -> Sym+c 5300 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1)) 5301 return FoldSymbolOffset(Opcode, VT, GA, N2); 5302 if (TLI->isCommutativeBinOp(Opcode)) 5303 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2)) 5304 return FoldSymbolOffset(Opcode, VT, GA, N1); 5305 5306 // For fixed width vectors, extract each constant element and fold them 5307 // individually. Either input may be an undef value. 5308 bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR || 5309 N1->getOpcode() == ISD::SPLAT_VECTOR; 5310 if (!IsBVOrSV1 && !N1->isUndef()) 5311 return SDValue(); 5312 bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR || 5313 N2->getOpcode() == ISD::SPLAT_VECTOR; 5314 if (!IsBVOrSV2 && !N2->isUndef()) 5315 return SDValue(); 5316 // If both operands are undef, that's handled the same way as scalars. 5317 if (!IsBVOrSV1 && !IsBVOrSV2) 5318 return SDValue(); 5319 5320 EVT SVT = VT.getScalarType(); 5321 EVT LegalSVT = SVT; 5322 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5323 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5324 if (LegalSVT.bitsLT(SVT)) 5325 return SDValue(); 5326 } 5327 5328 SmallVector<SDValue, 4> Outputs; 5329 unsigned NumOps = 0; 5330 if (IsBVOrSV1) 5331 NumOps = std::max(NumOps, N1->getNumOperands()); 5332 if (IsBVOrSV2) 5333 NumOps = std::max(NumOps, N2->getNumOperands()); 5334 assert(NumOps != 0 && "Expected non-zero operands"); 5335 // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need 5336 // one iteration for that. 5337 assert((!VT.isScalableVector() || NumOps == 1) && 5338 "Scalable vector should only have one scalar"); 5339 5340 for (unsigned I = 0; I != NumOps; ++I) { 5341 // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need 5342 // to use operand 0 of the SPLAT_VECTOR for each fixed element. 5343 SDValue V1; 5344 if (N1->getOpcode() == ISD::BUILD_VECTOR) 5345 V1 = N1->getOperand(I); 5346 else if (N1->getOpcode() == ISD::SPLAT_VECTOR) 5347 V1 = N1->getOperand(0); 5348 else 5349 V1 = getUNDEF(SVT); 5350 5351 SDValue V2; 5352 if (N2->getOpcode() == ISD::BUILD_VECTOR) 5353 V2 = N2->getOperand(I); 5354 else if (N2->getOpcode() == ISD::SPLAT_VECTOR) 5355 V2 = N2->getOperand(0); 5356 else 5357 V2 = getUNDEF(SVT); 5358 5359 if (SVT.isInteger()) { 5360 if (V1.getValueType().bitsGT(SVT)) 5361 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1); 5362 if (V2.getValueType().bitsGT(SVT)) 5363 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2); 5364 } 5365 5366 if (V1.getValueType() != SVT || V2.getValueType() != SVT) 5367 return SDValue(); 5368 5369 // Fold one vector element. 5370 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2); 5371 if (LegalSVT != SVT) 5372 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5373 5374 // Scalar folding only succeeded if the result is a constant or UNDEF. 5375 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5376 ScalarResult.getOpcode() != ISD::ConstantFP) 5377 return SDValue(); 5378 Outputs.push_back(ScalarResult); 5379 } 5380 5381 if (N1->getOpcode() == ISD::BUILD_VECTOR || 5382 N2->getOpcode() == ISD::BUILD_VECTOR) { 5383 assert(VT.getVectorNumElements() == Outputs.size() && 5384 "Vector size mismatch!"); 5385 5386 // Build a big vector out of the scalar elements we generated. 5387 return getBuildVector(VT, SDLoc(), Outputs); 5388 } 5389 5390 assert((N1->getOpcode() == ISD::SPLAT_VECTOR || 5391 N2->getOpcode() == ISD::SPLAT_VECTOR) && 5392 "One operand should be a splat vector"); 5393 5394 assert(Outputs.size() == 1 && "Vector size mismatch!"); 5395 return getSplatVector(VT, SDLoc(), Outputs[0]); 5396 } 5397 5398 // TODO: Merge with FoldConstantArithmetic 5399 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 5400 const SDLoc &DL, EVT VT, 5401 ArrayRef<SDValue> Ops, 5402 const SDNodeFlags Flags) { 5403 // If the opcode is a target-specific ISD node, there's nothing we can 5404 // do here and the operand rules may not line up with the below, so 5405 // bail early. 5406 if (Opcode >= ISD::BUILTIN_OP_END) 5407 return SDValue(); 5408 5409 if (isUndef(Opcode, Ops)) 5410 return getUNDEF(VT); 5411 5412 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 5413 if (!VT.isVector()) 5414 return SDValue(); 5415 5416 ElementCount NumElts = VT.getVectorElementCount(); 5417 5418 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5419 return !Op.getValueType().isVector() || 5420 Op.getValueType().getVectorElementCount() == NumElts; 5421 }; 5422 5423 auto IsConstantBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5424 APInt SplatVal; 5425 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 5426 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5427 (BV && BV->isConstant()) || 5428 (Op.getOpcode() == ISD::SPLAT_VECTOR && 5429 ISD::isConstantSplatVector(Op.getNode(), SplatVal)); 5430 }; 5431 5432 // All operands must be vector types with the same number of elements as 5433 // the result type and must be either UNDEF or a build vector of constant 5434 // or UNDEF scalars. 5435 if (!llvm::all_of(Ops, IsConstantBuildVectorSplatVectorOrUndef) || 5436 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5437 return SDValue(); 5438 5439 // If we are comparing vectors, then the result needs to be a i1 boolean 5440 // that is then sign-extended back to the legal result type. 5441 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5442 5443 // Find legal integer scalar type for constant promotion and 5444 // ensure that its scalar size is at least as large as source. 5445 EVT LegalSVT = VT.getScalarType(); 5446 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5447 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5448 if (LegalSVT.bitsLT(VT.getScalarType())) 5449 return SDValue(); 5450 } 5451 5452 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5453 // only have one operand to check. For fixed-length vector types we may have 5454 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5455 unsigned NumOperands = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5456 5457 // Constant fold each scalar lane separately. 5458 SmallVector<SDValue, 4> ScalarResults; 5459 for (unsigned I = 0; I != NumOperands; I++) { 5460 SmallVector<SDValue, 4> ScalarOps; 5461 for (SDValue Op : Ops) { 5462 EVT InSVT = Op.getValueType().getScalarType(); 5463 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5464 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5465 // We've checked that this is UNDEF or a constant of some kind. 5466 if (Op.isUndef()) 5467 ScalarOps.push_back(getUNDEF(InSVT)); 5468 else 5469 ScalarOps.push_back(Op); 5470 continue; 5471 } 5472 5473 SDValue ScalarOp = 5474 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5475 EVT ScalarVT = ScalarOp.getValueType(); 5476 5477 // Build vector (integer) scalar operands may need implicit 5478 // truncation - do this before constant folding. 5479 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5480 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5481 5482 ScalarOps.push_back(ScalarOp); 5483 } 5484 5485 // Constant fold the scalar operands. 5486 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 5487 5488 // Legalize the (integer) scalar constant if necessary. 5489 if (LegalSVT != SVT) 5490 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5491 5492 // Scalar folding only succeeded if the result is a constant or UNDEF. 5493 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5494 ScalarResult.getOpcode() != ISD::ConstantFP) 5495 return SDValue(); 5496 ScalarResults.push_back(ScalarResult); 5497 } 5498 5499 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5500 : getBuildVector(VT, DL, ScalarResults); 5501 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5502 return V; 5503 } 5504 5505 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5506 EVT VT, SDValue N1, SDValue N2) { 5507 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5508 // should. That will require dealing with a potentially non-default 5509 // rounding mode, checking the "opStatus" return value from the APFloat 5510 // math calculations, and possibly other variations. 5511 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 5512 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 5513 if (N1CFP && N2CFP) { 5514 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF(); 5515 switch (Opcode) { 5516 case ISD::FADD: 5517 C1.add(C2, APFloat::rmNearestTiesToEven); 5518 return getConstantFP(C1, DL, VT); 5519 case ISD::FSUB: 5520 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5521 return getConstantFP(C1, DL, VT); 5522 case ISD::FMUL: 5523 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5524 return getConstantFP(C1, DL, VT); 5525 case ISD::FDIV: 5526 C1.divide(C2, APFloat::rmNearestTiesToEven); 5527 return getConstantFP(C1, DL, VT); 5528 case ISD::FREM: 5529 C1.mod(C2); 5530 return getConstantFP(C1, DL, VT); 5531 case ISD::FCOPYSIGN: 5532 C1.copySign(C2); 5533 return getConstantFP(C1, DL, VT); 5534 default: break; 5535 } 5536 } 5537 if (N1CFP && Opcode == ISD::FP_ROUND) { 5538 APFloat C1 = N1CFP->getValueAPF(); // make copy 5539 bool Unused; 5540 // This can return overflow, underflow, or inexact; we don't care. 5541 // FIXME need to be more flexible about rounding mode. 5542 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5543 &Unused); 5544 return getConstantFP(C1, DL, VT); 5545 } 5546 5547 switch (Opcode) { 5548 case ISD::FSUB: 5549 // -0.0 - undef --> undef (consistent with "fneg undef") 5550 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef()) 5551 return getUNDEF(VT); 5552 LLVM_FALLTHROUGH; 5553 5554 case ISD::FADD: 5555 case ISD::FMUL: 5556 case ISD::FDIV: 5557 case ISD::FREM: 5558 // If both operands are undef, the result is undef. If 1 operand is undef, 5559 // the result is NaN. This should match the behavior of the IR optimizer. 5560 if (N1.isUndef() && N2.isUndef()) 5561 return getUNDEF(VT); 5562 if (N1.isUndef() || N2.isUndef()) 5563 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5564 } 5565 return SDValue(); 5566 } 5567 5568 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5569 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5570 5571 // There's no need to assert on a byte-aligned pointer. All pointers are at 5572 // least byte aligned. 5573 if (A == Align(1)) 5574 return Val; 5575 5576 FoldingSetNodeID ID; 5577 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5578 ID.AddInteger(A.value()); 5579 5580 void *IP = nullptr; 5581 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5582 return SDValue(E, 0); 5583 5584 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5585 Val.getValueType(), A); 5586 createOperands(N, {Val}); 5587 5588 CSEMap.InsertNode(N, IP); 5589 InsertNode(N); 5590 5591 SDValue V(N, 0); 5592 NewSDValueDbgMsg(V, "Creating new node: ", this); 5593 return V; 5594 } 5595 5596 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5597 SDValue N1, SDValue N2) { 5598 SDNodeFlags Flags; 5599 if (Inserter) 5600 Flags = Inserter->getFlags(); 5601 return getNode(Opcode, DL, VT, N1, N2, Flags); 5602 } 5603 5604 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5605 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5606 assert(N1.getOpcode() != ISD::DELETED_NODE && 5607 N2.getOpcode() != ISD::DELETED_NODE && 5608 "Operand is DELETED_NODE!"); 5609 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5610 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5611 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5612 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5613 5614 // Canonicalize constant to RHS if commutative. 5615 if (TLI->isCommutativeBinOp(Opcode)) { 5616 if (N1C && !N2C) { 5617 std::swap(N1C, N2C); 5618 std::swap(N1, N2); 5619 } else if (N1CFP && !N2CFP) { 5620 std::swap(N1CFP, N2CFP); 5621 std::swap(N1, N2); 5622 } 5623 } 5624 5625 switch (Opcode) { 5626 default: break; 5627 case ISD::TokenFactor: 5628 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5629 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5630 // Fold trivial token factors. 5631 if (N1.getOpcode() == ISD::EntryToken) return N2; 5632 if (N2.getOpcode() == ISD::EntryToken) return N1; 5633 if (N1 == N2) return N1; 5634 break; 5635 case ISD::BUILD_VECTOR: { 5636 // Attempt to simplify BUILD_VECTOR. 5637 SDValue Ops[] = {N1, N2}; 5638 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5639 return V; 5640 break; 5641 } 5642 case ISD::CONCAT_VECTORS: { 5643 SDValue Ops[] = {N1, N2}; 5644 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5645 return V; 5646 break; 5647 } 5648 case ISD::AND: 5649 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5650 assert(N1.getValueType() == N2.getValueType() && 5651 N1.getValueType() == VT && "Binary operator types must match!"); 5652 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5653 // worth handling here. 5654 if (N2C && N2C->isZero()) 5655 return N2; 5656 if (N2C && N2C->isAllOnes()) // X & -1 -> X 5657 return N1; 5658 break; 5659 case ISD::OR: 5660 case ISD::XOR: 5661 case ISD::ADD: 5662 case ISD::SUB: 5663 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5664 assert(N1.getValueType() == N2.getValueType() && 5665 N1.getValueType() == VT && "Binary operator types must match!"); 5666 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5667 // it's worth handling here. 5668 if (N2C && N2C->isZero()) 5669 return N1; 5670 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5671 VT.getVectorElementType() == MVT::i1) 5672 return getNode(ISD::XOR, DL, VT, N1, N2); 5673 break; 5674 case ISD::MUL: 5675 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5676 assert(N1.getValueType() == N2.getValueType() && 5677 N1.getValueType() == VT && "Binary operator types must match!"); 5678 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5679 return getNode(ISD::AND, DL, VT, N1, N2); 5680 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5681 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5682 const APInt &N2CImm = N2C->getAPIntValue(); 5683 return getVScale(DL, VT, MulImm * N2CImm); 5684 } 5685 break; 5686 case ISD::UDIV: 5687 case ISD::UREM: 5688 case ISD::MULHU: 5689 case ISD::MULHS: 5690 case ISD::SDIV: 5691 case ISD::SREM: 5692 case ISD::SADDSAT: 5693 case ISD::SSUBSAT: 5694 case ISD::UADDSAT: 5695 case ISD::USUBSAT: 5696 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5697 assert(N1.getValueType() == N2.getValueType() && 5698 N1.getValueType() == VT && "Binary operator types must match!"); 5699 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5700 // fold (add_sat x, y) -> (or x, y) for bool types. 5701 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5702 return getNode(ISD::OR, DL, VT, N1, N2); 5703 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5704 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5705 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5706 } 5707 break; 5708 case ISD::SMIN: 5709 case ISD::UMAX: 5710 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5711 assert(N1.getValueType() == N2.getValueType() && 5712 N1.getValueType() == VT && "Binary operator types must match!"); 5713 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5714 return getNode(ISD::OR, DL, VT, N1, N2); 5715 break; 5716 case ISD::SMAX: 5717 case ISD::UMIN: 5718 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5719 assert(N1.getValueType() == N2.getValueType() && 5720 N1.getValueType() == VT && "Binary operator types must match!"); 5721 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5722 return getNode(ISD::AND, DL, VT, N1, N2); 5723 break; 5724 case ISD::FADD: 5725 case ISD::FSUB: 5726 case ISD::FMUL: 5727 case ISD::FDIV: 5728 case ISD::FREM: 5729 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5730 assert(N1.getValueType() == N2.getValueType() && 5731 N1.getValueType() == VT && "Binary operator types must match!"); 5732 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5733 return V; 5734 break; 5735 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5736 assert(N1.getValueType() == VT && 5737 N1.getValueType().isFloatingPoint() && 5738 N2.getValueType().isFloatingPoint() && 5739 "Invalid FCOPYSIGN!"); 5740 break; 5741 case ISD::SHL: 5742 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5743 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5744 const APInt &ShiftImm = N2C->getAPIntValue(); 5745 return getVScale(DL, VT, MulImm << ShiftImm); 5746 } 5747 LLVM_FALLTHROUGH; 5748 case ISD::SRA: 5749 case ISD::SRL: 5750 if (SDValue V = simplifyShift(N1, N2)) 5751 return V; 5752 LLVM_FALLTHROUGH; 5753 case ISD::ROTL: 5754 case ISD::ROTR: 5755 assert(VT == N1.getValueType() && 5756 "Shift operators return type must be the same as their first arg"); 5757 assert(VT.isInteger() && N2.getValueType().isInteger() && 5758 "Shifts only work on integers"); 5759 assert((!VT.isVector() || VT == N2.getValueType()) && 5760 "Vector shift amounts must be in the same as their first arg"); 5761 // Verify that the shift amount VT is big enough to hold valid shift 5762 // amounts. This catches things like trying to shift an i1024 value by an 5763 // i8, which is easy to fall into in generic code that uses 5764 // TLI.getShiftAmount(). 5765 assert(N2.getValueType().getScalarSizeInBits() >= 5766 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5767 "Invalid use of small shift amount with oversized value!"); 5768 5769 // Always fold shifts of i1 values so the code generator doesn't need to 5770 // handle them. Since we know the size of the shift has to be less than the 5771 // size of the value, the shift/rotate count is guaranteed to be zero. 5772 if (VT == MVT::i1) 5773 return N1; 5774 if (N2C && N2C->isZero()) 5775 return N1; 5776 break; 5777 case ISD::FP_ROUND: 5778 assert(VT.isFloatingPoint() && 5779 N1.getValueType().isFloatingPoint() && 5780 VT.bitsLE(N1.getValueType()) && 5781 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5782 "Invalid FP_ROUND!"); 5783 if (N1.getValueType() == VT) return N1; // noop conversion. 5784 break; 5785 case ISD::AssertSext: 5786 case ISD::AssertZext: { 5787 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5788 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5789 assert(VT.isInteger() && EVT.isInteger() && 5790 "Cannot *_EXTEND_INREG FP types"); 5791 assert(!EVT.isVector() && 5792 "AssertSExt/AssertZExt type should be the vector element type " 5793 "rather than the vector type!"); 5794 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5795 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5796 break; 5797 } 5798 case ISD::SIGN_EXTEND_INREG: { 5799 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5800 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5801 assert(VT.isInteger() && EVT.isInteger() && 5802 "Cannot *_EXTEND_INREG FP types"); 5803 assert(EVT.isVector() == VT.isVector() && 5804 "SIGN_EXTEND_INREG type should be vector iff the operand " 5805 "type is vector!"); 5806 assert((!EVT.isVector() || 5807 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5808 "Vector element counts must match in SIGN_EXTEND_INREG"); 5809 assert(EVT.bitsLE(VT) && "Not extending!"); 5810 if (EVT == VT) return N1; // Not actually extending 5811 5812 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5813 unsigned FromBits = EVT.getScalarSizeInBits(); 5814 Val <<= Val.getBitWidth() - FromBits; 5815 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5816 return getConstant(Val, DL, ConstantVT); 5817 }; 5818 5819 if (N1C) { 5820 const APInt &Val = N1C->getAPIntValue(); 5821 return SignExtendInReg(Val, VT); 5822 } 5823 5824 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5825 SmallVector<SDValue, 8> Ops; 5826 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5827 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5828 SDValue Op = N1.getOperand(i); 5829 if (Op.isUndef()) { 5830 Ops.push_back(getUNDEF(OpVT)); 5831 continue; 5832 } 5833 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5834 APInt Val = C->getAPIntValue(); 5835 Ops.push_back(SignExtendInReg(Val, OpVT)); 5836 } 5837 return getBuildVector(VT, DL, Ops); 5838 } 5839 break; 5840 } 5841 case ISD::FP_TO_SINT_SAT: 5842 case ISD::FP_TO_UINT_SAT: { 5843 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 5844 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 5845 assert(N1.getValueType().isVector() == VT.isVector() && 5846 "FP_TO_*INT_SAT type should be vector iff the operand type is " 5847 "vector!"); 5848 assert((!VT.isVector() || VT.getVectorNumElements() == 5849 N1.getValueType().getVectorNumElements()) && 5850 "Vector element counts must match in FP_TO_*INT_SAT"); 5851 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 5852 "Type to saturate to must be a scalar."); 5853 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 5854 "Not extending!"); 5855 break; 5856 } 5857 case ISD::EXTRACT_VECTOR_ELT: 5858 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5859 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5860 element type of the vector."); 5861 5862 // Extract from an undefined value or using an undefined index is undefined. 5863 if (N1.isUndef() || N2.isUndef()) 5864 return getUNDEF(VT); 5865 5866 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5867 // vectors. For scalable vectors we will provide appropriate support for 5868 // dealing with arbitrary indices. 5869 if (N2C && N1.getValueType().isFixedLengthVector() && 5870 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5871 return getUNDEF(VT); 5872 5873 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5874 // expanding copies of large vectors from registers. This only works for 5875 // fixed length vectors, since we need to know the exact number of 5876 // elements. 5877 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5878 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5879 unsigned Factor = 5880 N1.getOperand(0).getValueType().getVectorNumElements(); 5881 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5882 N1.getOperand(N2C->getZExtValue() / Factor), 5883 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5884 } 5885 5886 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5887 // lowering is expanding large vector constants. 5888 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5889 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5890 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5891 N1.getValueType().isFixedLengthVector()) && 5892 "BUILD_VECTOR used for scalable vectors"); 5893 unsigned Index = 5894 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5895 SDValue Elt = N1.getOperand(Index); 5896 5897 if (VT != Elt.getValueType()) 5898 // If the vector element type is not legal, the BUILD_VECTOR operands 5899 // are promoted and implicitly truncated, and the result implicitly 5900 // extended. Make that explicit here. 5901 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5902 5903 return Elt; 5904 } 5905 5906 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5907 // operations are lowered to scalars. 5908 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5909 // If the indices are the same, return the inserted element else 5910 // if the indices are known different, extract the element from 5911 // the original vector. 5912 SDValue N1Op2 = N1.getOperand(2); 5913 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5914 5915 if (N1Op2C && N2C) { 5916 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5917 if (VT == N1.getOperand(1).getValueType()) 5918 return N1.getOperand(1); 5919 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5920 } 5921 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5922 } 5923 } 5924 5925 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5926 // when vector types are scalarized and v1iX is legal. 5927 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5928 // Here we are completely ignoring the extract element index (N2), 5929 // which is fine for fixed width vectors, since any index other than 0 5930 // is undefined anyway. However, this cannot be ignored for scalable 5931 // vectors - in theory we could support this, but we don't want to do this 5932 // without a profitability check. 5933 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5934 N1.getValueType().isFixedLengthVector() && 5935 N1.getValueType().getVectorNumElements() == 1) { 5936 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5937 N1.getOperand(1)); 5938 } 5939 break; 5940 case ISD::EXTRACT_ELEMENT: 5941 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5942 assert(!N1.getValueType().isVector() && !VT.isVector() && 5943 (N1.getValueType().isInteger() == VT.isInteger()) && 5944 N1.getValueType() != VT && 5945 "Wrong types for EXTRACT_ELEMENT!"); 5946 5947 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5948 // 64-bit integers into 32-bit parts. Instead of building the extract of 5949 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5950 if (N1.getOpcode() == ISD::BUILD_PAIR) 5951 return N1.getOperand(N2C->getZExtValue()); 5952 5953 // EXTRACT_ELEMENT of a constant int is also very common. 5954 if (N1C) { 5955 unsigned ElementSize = VT.getSizeInBits(); 5956 unsigned Shift = ElementSize * N2C->getZExtValue(); 5957 const APInt &Val = N1C->getAPIntValue(); 5958 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 5959 } 5960 break; 5961 case ISD::EXTRACT_SUBVECTOR: { 5962 EVT N1VT = N1.getValueType(); 5963 assert(VT.isVector() && N1VT.isVector() && 5964 "Extract subvector VTs must be vectors!"); 5965 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5966 "Extract subvector VTs must have the same element type!"); 5967 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5968 "Cannot extract a scalable vector from a fixed length vector!"); 5969 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5970 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5971 "Extract subvector must be from larger vector to smaller vector!"); 5972 assert(N2C && "Extract subvector index must be a constant"); 5973 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5974 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5975 N1VT.getVectorMinNumElements()) && 5976 "Extract subvector overflow!"); 5977 assert(N2C->getAPIntValue().getBitWidth() == 5978 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5979 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 5980 5981 // Trivial extraction. 5982 if (VT == N1VT) 5983 return N1; 5984 5985 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 5986 if (N1.isUndef()) 5987 return getUNDEF(VT); 5988 5989 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 5990 // the concat have the same type as the extract. 5991 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 5992 VT == N1.getOperand(0).getValueType()) { 5993 unsigned Factor = VT.getVectorMinNumElements(); 5994 return N1.getOperand(N2C->getZExtValue() / Factor); 5995 } 5996 5997 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 5998 // during shuffle legalization. 5999 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6000 VT == N1.getOperand(1).getValueType()) 6001 return N1.getOperand(1); 6002 break; 6003 } 6004 } 6005 6006 // Perform trivial constant folding. 6007 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6008 return SV; 6009 6010 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2)) 6011 return V; 6012 6013 // Canonicalize an UNDEF to the RHS, even over a constant. 6014 if (N1.isUndef()) { 6015 if (TLI->isCommutativeBinOp(Opcode)) { 6016 std::swap(N1, N2); 6017 } else { 6018 switch (Opcode) { 6019 case ISD::SIGN_EXTEND_INREG: 6020 case ISD::SUB: 6021 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6022 case ISD::UDIV: 6023 case ISD::SDIV: 6024 case ISD::UREM: 6025 case ISD::SREM: 6026 case ISD::SSUBSAT: 6027 case ISD::USUBSAT: 6028 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6029 } 6030 } 6031 } 6032 6033 // Fold a bunch of operators when the RHS is undef. 6034 if (N2.isUndef()) { 6035 switch (Opcode) { 6036 case ISD::XOR: 6037 if (N1.isUndef()) 6038 // Handle undef ^ undef -> 0 special case. This is a common 6039 // idiom (misuse). 6040 return getConstant(0, DL, VT); 6041 LLVM_FALLTHROUGH; 6042 case ISD::ADD: 6043 case ISD::SUB: 6044 case ISD::UDIV: 6045 case ISD::SDIV: 6046 case ISD::UREM: 6047 case ISD::SREM: 6048 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6049 case ISD::MUL: 6050 case ISD::AND: 6051 case ISD::SSUBSAT: 6052 case ISD::USUBSAT: 6053 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6054 case ISD::OR: 6055 case ISD::SADDSAT: 6056 case ISD::UADDSAT: 6057 return getAllOnesConstant(DL, VT); 6058 } 6059 } 6060 6061 // Memoize this node if possible. 6062 SDNode *N; 6063 SDVTList VTs = getVTList(VT); 6064 SDValue Ops[] = {N1, N2}; 6065 if (VT != MVT::Glue) { 6066 FoldingSetNodeID ID; 6067 AddNodeIDNode(ID, Opcode, VTs, Ops); 6068 void *IP = nullptr; 6069 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6070 E->intersectFlagsWith(Flags); 6071 return SDValue(E, 0); 6072 } 6073 6074 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6075 N->setFlags(Flags); 6076 createOperands(N, Ops); 6077 CSEMap.InsertNode(N, IP); 6078 } else { 6079 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6080 createOperands(N, Ops); 6081 } 6082 6083 InsertNode(N); 6084 SDValue V = SDValue(N, 0); 6085 NewSDValueDbgMsg(V, "Creating new node: ", this); 6086 return V; 6087 } 6088 6089 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6090 SDValue N1, SDValue N2, SDValue N3) { 6091 SDNodeFlags Flags; 6092 if (Inserter) 6093 Flags = Inserter->getFlags(); 6094 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6095 } 6096 6097 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6098 SDValue N1, SDValue N2, SDValue N3, 6099 const SDNodeFlags Flags) { 6100 assert(N1.getOpcode() != ISD::DELETED_NODE && 6101 N2.getOpcode() != ISD::DELETED_NODE && 6102 N3.getOpcode() != ISD::DELETED_NODE && 6103 "Operand is DELETED_NODE!"); 6104 // Perform various simplifications. 6105 switch (Opcode) { 6106 case ISD::FMA: { 6107 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6108 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6109 N3.getValueType() == VT && "FMA types must match!"); 6110 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6111 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6112 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6113 if (N1CFP && N2CFP && N3CFP) { 6114 APFloat V1 = N1CFP->getValueAPF(); 6115 const APFloat &V2 = N2CFP->getValueAPF(); 6116 const APFloat &V3 = N3CFP->getValueAPF(); 6117 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6118 return getConstantFP(V1, DL, VT); 6119 } 6120 break; 6121 } 6122 case ISD::BUILD_VECTOR: { 6123 // Attempt to simplify BUILD_VECTOR. 6124 SDValue Ops[] = {N1, N2, N3}; 6125 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6126 return V; 6127 break; 6128 } 6129 case ISD::CONCAT_VECTORS: { 6130 SDValue Ops[] = {N1, N2, N3}; 6131 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6132 return V; 6133 break; 6134 } 6135 case ISD::SETCC: { 6136 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6137 assert(N1.getValueType() == N2.getValueType() && 6138 "SETCC operands must have the same type!"); 6139 assert(VT.isVector() == N1.getValueType().isVector() && 6140 "SETCC type should be vector iff the operand type is vector!"); 6141 assert((!VT.isVector() || VT.getVectorElementCount() == 6142 N1.getValueType().getVectorElementCount()) && 6143 "SETCC vector element counts must match!"); 6144 // Use FoldSetCC to simplify SETCC's. 6145 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6146 return V; 6147 // Vector constant folding. 6148 SDValue Ops[] = {N1, N2, N3}; 6149 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) { 6150 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6151 return V; 6152 } 6153 break; 6154 } 6155 case ISD::SELECT: 6156 case ISD::VSELECT: 6157 if (SDValue V = simplifySelect(N1, N2, N3)) 6158 return V; 6159 break; 6160 case ISD::VECTOR_SHUFFLE: 6161 llvm_unreachable("should use getVectorShuffle constructor!"); 6162 case ISD::VECTOR_SPLICE: { 6163 if (cast<ConstantSDNode>(N3)->isNullValue()) 6164 return N1; 6165 break; 6166 } 6167 case ISD::INSERT_VECTOR_ELT: { 6168 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6169 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6170 // for scalable vectors where we will generate appropriate code to 6171 // deal with out-of-bounds cases correctly. 6172 if (N3C && N1.getValueType().isFixedLengthVector() && 6173 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6174 return getUNDEF(VT); 6175 6176 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6177 if (N3.isUndef()) 6178 return getUNDEF(VT); 6179 6180 // If the inserted element is an UNDEF, just use the input vector. 6181 if (N2.isUndef()) 6182 return N1; 6183 6184 break; 6185 } 6186 case ISD::INSERT_SUBVECTOR: { 6187 // Inserting undef into undef is still undef. 6188 if (N1.isUndef() && N2.isUndef()) 6189 return getUNDEF(VT); 6190 6191 EVT N2VT = N2.getValueType(); 6192 assert(VT == N1.getValueType() && 6193 "Dest and insert subvector source types must match!"); 6194 assert(VT.isVector() && N2VT.isVector() && 6195 "Insert subvector VTs must be vectors!"); 6196 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6197 "Cannot insert a scalable vector into a fixed length vector!"); 6198 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6199 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6200 "Insert subvector must be from smaller vector to larger vector!"); 6201 assert(isa<ConstantSDNode>(N3) && 6202 "Insert subvector index must be constant"); 6203 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6204 (N2VT.getVectorMinNumElements() + 6205 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6206 VT.getVectorMinNumElements()) && 6207 "Insert subvector overflow!"); 6208 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6209 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6210 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6211 6212 // Trivial insertion. 6213 if (VT == N2VT) 6214 return N2; 6215 6216 // If this is an insert of an extracted vector into an undef vector, we 6217 // can just use the input to the extract. 6218 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6219 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6220 return N2.getOperand(0); 6221 break; 6222 } 6223 case ISD::BITCAST: 6224 // Fold bit_convert nodes from a type to themselves. 6225 if (N1.getValueType() == VT) 6226 return N1; 6227 break; 6228 } 6229 6230 // Memoize node if it doesn't produce a flag. 6231 SDNode *N; 6232 SDVTList VTs = getVTList(VT); 6233 SDValue Ops[] = {N1, N2, N3}; 6234 if (VT != MVT::Glue) { 6235 FoldingSetNodeID ID; 6236 AddNodeIDNode(ID, Opcode, VTs, Ops); 6237 void *IP = nullptr; 6238 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6239 E->intersectFlagsWith(Flags); 6240 return SDValue(E, 0); 6241 } 6242 6243 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6244 N->setFlags(Flags); 6245 createOperands(N, Ops); 6246 CSEMap.InsertNode(N, IP); 6247 } else { 6248 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6249 createOperands(N, Ops); 6250 } 6251 6252 InsertNode(N); 6253 SDValue V = SDValue(N, 0); 6254 NewSDValueDbgMsg(V, "Creating new node: ", this); 6255 return V; 6256 } 6257 6258 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6259 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6260 SDValue Ops[] = { N1, N2, N3, N4 }; 6261 return getNode(Opcode, DL, VT, Ops); 6262 } 6263 6264 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6265 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6266 SDValue N5) { 6267 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6268 return getNode(Opcode, DL, VT, Ops); 6269 } 6270 6271 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6272 /// the incoming stack arguments to be loaded from the stack. 6273 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6274 SmallVector<SDValue, 8> ArgChains; 6275 6276 // Include the original chain at the beginning of the list. When this is 6277 // used by target LowerCall hooks, this helps legalize find the 6278 // CALLSEQ_BEGIN node. 6279 ArgChains.push_back(Chain); 6280 6281 // Add a chain value for each stack argument. 6282 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 6283 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 6284 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 6285 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6286 if (FI->getIndex() < 0) 6287 ArgChains.push_back(SDValue(L, 1)); 6288 6289 // Build a tokenfactor for all the chains. 6290 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6291 } 6292 6293 /// getMemsetValue - Vectorized representation of the memset value 6294 /// operand. 6295 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6296 const SDLoc &dl) { 6297 assert(!Value.isUndef()); 6298 6299 unsigned NumBits = VT.getScalarSizeInBits(); 6300 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6301 assert(C->getAPIntValue().getBitWidth() == 8); 6302 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6303 if (VT.isInteger()) { 6304 bool IsOpaque = VT.getSizeInBits() > 64 || 6305 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6306 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6307 } 6308 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6309 VT); 6310 } 6311 6312 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6313 EVT IntVT = VT.getScalarType(); 6314 if (!IntVT.isInteger()) 6315 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6316 6317 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6318 if (NumBits > 8) { 6319 // Use a multiplication with 0x010101... to extend the input to the 6320 // required length. 6321 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6322 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6323 DAG.getConstant(Magic, dl, IntVT)); 6324 } 6325 6326 if (VT != Value.getValueType() && !VT.isInteger()) 6327 Value = DAG.getBitcast(VT.getScalarType(), Value); 6328 if (VT != Value.getValueType()) 6329 Value = DAG.getSplatBuildVector(VT, dl, Value); 6330 6331 return Value; 6332 } 6333 6334 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6335 /// used when a memcpy is turned into a memset when the source is a constant 6336 /// string ptr. 6337 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6338 const TargetLowering &TLI, 6339 const ConstantDataArraySlice &Slice) { 6340 // Handle vector with all elements zero. 6341 if (Slice.Array == nullptr) { 6342 if (VT.isInteger()) 6343 return DAG.getConstant(0, dl, VT); 6344 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6345 return DAG.getConstantFP(0.0, dl, VT); 6346 if (VT.isVector()) { 6347 unsigned NumElts = VT.getVectorNumElements(); 6348 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6349 return DAG.getNode(ISD::BITCAST, dl, VT, 6350 DAG.getConstant(0, dl, 6351 EVT::getVectorVT(*DAG.getContext(), 6352 EltVT, NumElts))); 6353 } 6354 llvm_unreachable("Expected type!"); 6355 } 6356 6357 assert(!VT.isVector() && "Can't handle vector type here!"); 6358 unsigned NumVTBits = VT.getSizeInBits(); 6359 unsigned NumVTBytes = NumVTBits / 8; 6360 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6361 6362 APInt Val(NumVTBits, 0); 6363 if (DAG.getDataLayout().isLittleEndian()) { 6364 for (unsigned i = 0; i != NumBytes; ++i) 6365 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6366 } else { 6367 for (unsigned i = 0; i != NumBytes; ++i) 6368 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6369 } 6370 6371 // If the "cost" of materializing the integer immediate is less than the cost 6372 // of a load, then it is cost effective to turn the load into the immediate. 6373 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6374 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6375 return DAG.getConstant(Val, dl, VT); 6376 return SDValue(nullptr, 0); 6377 } 6378 6379 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6380 const SDLoc &DL, 6381 const SDNodeFlags Flags) { 6382 EVT VT = Base.getValueType(); 6383 SDValue Index; 6384 6385 if (Offset.isScalable()) 6386 Index = getVScale(DL, Base.getValueType(), 6387 APInt(Base.getValueSizeInBits().getFixedSize(), 6388 Offset.getKnownMinSize())); 6389 else 6390 Index = getConstant(Offset.getFixedSize(), DL, VT); 6391 6392 return getMemBasePlusOffset(Base, Index, DL, Flags); 6393 } 6394 6395 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6396 const SDLoc &DL, 6397 const SDNodeFlags Flags) { 6398 assert(Offset.getValueType().isInteger()); 6399 EVT BasePtrVT = Ptr.getValueType(); 6400 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6401 } 6402 6403 /// Returns true if memcpy source is constant data. 6404 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6405 uint64_t SrcDelta = 0; 6406 GlobalAddressSDNode *G = nullptr; 6407 if (Src.getOpcode() == ISD::GlobalAddress) 6408 G = cast<GlobalAddressSDNode>(Src); 6409 else if (Src.getOpcode() == ISD::ADD && 6410 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6411 Src.getOperand(1).getOpcode() == ISD::Constant) { 6412 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6413 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6414 } 6415 if (!G) 6416 return false; 6417 6418 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6419 SrcDelta + G->getOffset()); 6420 } 6421 6422 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6423 SelectionDAG &DAG) { 6424 // On Darwin, -Os means optimize for size without hurting performance, so 6425 // only really optimize for size when -Oz (MinSize) is used. 6426 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6427 return MF.getFunction().hasMinSize(); 6428 return DAG.shouldOptForSize(); 6429 } 6430 6431 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6432 SmallVector<SDValue, 32> &OutChains, unsigned From, 6433 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6434 SmallVector<SDValue, 16> &OutStoreChains) { 6435 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6436 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6437 SmallVector<SDValue, 16> GluedLoadChains; 6438 for (unsigned i = From; i < To; ++i) { 6439 OutChains.push_back(OutLoadChains[i]); 6440 GluedLoadChains.push_back(OutLoadChains[i]); 6441 } 6442 6443 // Chain for all loads. 6444 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6445 GluedLoadChains); 6446 6447 for (unsigned i = From; i < To; ++i) { 6448 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6449 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6450 ST->getBasePtr(), ST->getMemoryVT(), 6451 ST->getMemOperand()); 6452 OutChains.push_back(NewStore); 6453 } 6454 } 6455 6456 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6457 SDValue Chain, SDValue Dst, SDValue Src, 6458 uint64_t Size, Align Alignment, 6459 bool isVol, bool AlwaysInline, 6460 MachinePointerInfo DstPtrInfo, 6461 MachinePointerInfo SrcPtrInfo, 6462 const AAMDNodes &AAInfo) { 6463 // Turn a memcpy of undef to nop. 6464 // FIXME: We need to honor volatile even is Src is undef. 6465 if (Src.isUndef()) 6466 return Chain; 6467 6468 // Expand memcpy to a series of load and store ops if the size operand falls 6469 // below a certain threshold. 6470 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6471 // rather than maybe a humongous number of loads and stores. 6472 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6473 const DataLayout &DL = DAG.getDataLayout(); 6474 LLVMContext &C = *DAG.getContext(); 6475 std::vector<EVT> MemOps; 6476 bool DstAlignCanChange = false; 6477 MachineFunction &MF = DAG.getMachineFunction(); 6478 MachineFrameInfo &MFI = MF.getFrameInfo(); 6479 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6480 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6481 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6482 DstAlignCanChange = true; 6483 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6484 if (!SrcAlign || Alignment > *SrcAlign) 6485 SrcAlign = Alignment; 6486 assert(SrcAlign && "SrcAlign must be set"); 6487 ConstantDataArraySlice Slice; 6488 // If marked as volatile, perform a copy even when marked as constant. 6489 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6490 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6491 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6492 const MemOp Op = isZeroConstant 6493 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6494 /*IsZeroMemset*/ true, isVol) 6495 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6496 *SrcAlign, isVol, CopyFromConstant); 6497 if (!TLI.findOptimalMemOpLowering( 6498 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6499 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6500 return SDValue(); 6501 6502 if (DstAlignCanChange) { 6503 Type *Ty = MemOps[0].getTypeForEVT(C); 6504 Align NewAlign = DL.getABITypeAlign(Ty); 6505 6506 // Don't promote to an alignment that would require dynamic stack 6507 // realignment. 6508 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6509 if (!TRI->hasStackRealignment(MF)) 6510 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6511 NewAlign = NewAlign / 2; 6512 6513 if (NewAlign > Alignment) { 6514 // Give the stack frame object a larger alignment if needed. 6515 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6516 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6517 Alignment = NewAlign; 6518 } 6519 } 6520 6521 // Prepare AAInfo for loads/stores after lowering this memcpy. 6522 AAMDNodes NewAAInfo = AAInfo; 6523 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6524 6525 MachineMemOperand::Flags MMOFlags = 6526 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6527 SmallVector<SDValue, 16> OutLoadChains; 6528 SmallVector<SDValue, 16> OutStoreChains; 6529 SmallVector<SDValue, 32> OutChains; 6530 unsigned NumMemOps = MemOps.size(); 6531 uint64_t SrcOff = 0, DstOff = 0; 6532 for (unsigned i = 0; i != NumMemOps; ++i) { 6533 EVT VT = MemOps[i]; 6534 unsigned VTSize = VT.getSizeInBits() / 8; 6535 SDValue Value, Store; 6536 6537 if (VTSize > Size) { 6538 // Issuing an unaligned load / store pair that overlaps with the previous 6539 // pair. Adjust the offset accordingly. 6540 assert(i == NumMemOps-1 && i != 0); 6541 SrcOff -= VTSize - Size; 6542 DstOff -= VTSize - Size; 6543 } 6544 6545 if (CopyFromConstant && 6546 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6547 // It's unlikely a store of a vector immediate can be done in a single 6548 // instruction. It would require a load from a constantpool first. 6549 // We only handle zero vectors here. 6550 // FIXME: Handle other cases where store of vector immediate is done in 6551 // a single instruction. 6552 ConstantDataArraySlice SubSlice; 6553 if (SrcOff < Slice.Length) { 6554 SubSlice = Slice; 6555 SubSlice.move(SrcOff); 6556 } else { 6557 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6558 SubSlice.Array = nullptr; 6559 SubSlice.Offset = 0; 6560 SubSlice.Length = VTSize; 6561 } 6562 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6563 if (Value.getNode()) { 6564 Store = DAG.getStore( 6565 Chain, dl, Value, 6566 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6567 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6568 OutChains.push_back(Store); 6569 } 6570 } 6571 6572 if (!Store.getNode()) { 6573 // The type might not be legal for the target. This should only happen 6574 // if the type is smaller than a legal type, as on PPC, so the right 6575 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6576 // to Load/Store if NVT==VT. 6577 // FIXME does the case above also need this? 6578 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6579 assert(NVT.bitsGE(VT)); 6580 6581 bool isDereferenceable = 6582 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6583 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6584 if (isDereferenceable) 6585 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6586 6587 Value = DAG.getExtLoad( 6588 ISD::EXTLOAD, dl, NVT, Chain, 6589 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6590 SrcPtrInfo.getWithOffset(SrcOff), VT, 6591 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6592 OutLoadChains.push_back(Value.getValue(1)); 6593 6594 Store = DAG.getTruncStore( 6595 Chain, dl, Value, 6596 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6597 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6598 OutStoreChains.push_back(Store); 6599 } 6600 SrcOff += VTSize; 6601 DstOff += VTSize; 6602 Size -= VTSize; 6603 } 6604 6605 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6606 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6607 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6608 6609 if (NumLdStInMemcpy) { 6610 // It may be that memcpy might be converted to memset if it's memcpy 6611 // of constants. In such a case, we won't have loads and stores, but 6612 // just stores. In the absence of loads, there is nothing to gang up. 6613 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6614 // If target does not care, just leave as it. 6615 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6616 OutChains.push_back(OutLoadChains[i]); 6617 OutChains.push_back(OutStoreChains[i]); 6618 } 6619 } else { 6620 // Ld/St less than/equal limit set by target. 6621 if (NumLdStInMemcpy <= GluedLdStLimit) { 6622 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6623 NumLdStInMemcpy, OutLoadChains, 6624 OutStoreChains); 6625 } else { 6626 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6627 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6628 unsigned GlueIter = 0; 6629 6630 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6631 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6632 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6633 6634 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6635 OutLoadChains, OutStoreChains); 6636 GlueIter += GluedLdStLimit; 6637 } 6638 6639 // Residual ld/st. 6640 if (RemainingLdStInMemcpy) { 6641 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6642 RemainingLdStInMemcpy, OutLoadChains, 6643 OutStoreChains); 6644 } 6645 } 6646 } 6647 } 6648 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6649 } 6650 6651 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6652 SDValue Chain, SDValue Dst, SDValue Src, 6653 uint64_t Size, Align Alignment, 6654 bool isVol, bool AlwaysInline, 6655 MachinePointerInfo DstPtrInfo, 6656 MachinePointerInfo SrcPtrInfo, 6657 const AAMDNodes &AAInfo) { 6658 // Turn a memmove of undef to nop. 6659 // FIXME: We need to honor volatile even is Src is undef. 6660 if (Src.isUndef()) 6661 return Chain; 6662 6663 // Expand memmove to a series of load and store ops if the size operand falls 6664 // below a certain threshold. 6665 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6666 const DataLayout &DL = DAG.getDataLayout(); 6667 LLVMContext &C = *DAG.getContext(); 6668 std::vector<EVT> MemOps; 6669 bool DstAlignCanChange = false; 6670 MachineFunction &MF = DAG.getMachineFunction(); 6671 MachineFrameInfo &MFI = MF.getFrameInfo(); 6672 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6673 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6674 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6675 DstAlignCanChange = true; 6676 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6677 if (!SrcAlign || Alignment > *SrcAlign) 6678 SrcAlign = Alignment; 6679 assert(SrcAlign && "SrcAlign must be set"); 6680 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6681 if (!TLI.findOptimalMemOpLowering( 6682 MemOps, Limit, 6683 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6684 /*IsVolatile*/ true), 6685 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6686 MF.getFunction().getAttributes())) 6687 return SDValue(); 6688 6689 if (DstAlignCanChange) { 6690 Type *Ty = MemOps[0].getTypeForEVT(C); 6691 Align NewAlign = DL.getABITypeAlign(Ty); 6692 if (NewAlign > Alignment) { 6693 // Give the stack frame object a larger alignment if needed. 6694 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6695 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6696 Alignment = NewAlign; 6697 } 6698 } 6699 6700 // Prepare AAInfo for loads/stores after lowering this memmove. 6701 AAMDNodes NewAAInfo = AAInfo; 6702 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6703 6704 MachineMemOperand::Flags MMOFlags = 6705 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6706 uint64_t SrcOff = 0, DstOff = 0; 6707 SmallVector<SDValue, 8> LoadValues; 6708 SmallVector<SDValue, 8> LoadChains; 6709 SmallVector<SDValue, 8> OutChains; 6710 unsigned NumMemOps = MemOps.size(); 6711 for (unsigned i = 0; i < NumMemOps; i++) { 6712 EVT VT = MemOps[i]; 6713 unsigned VTSize = VT.getSizeInBits() / 8; 6714 SDValue Value; 6715 6716 bool isDereferenceable = 6717 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6718 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6719 if (isDereferenceable) 6720 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6721 6722 Value = DAG.getLoad( 6723 VT, dl, Chain, 6724 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6725 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6726 LoadValues.push_back(Value); 6727 LoadChains.push_back(Value.getValue(1)); 6728 SrcOff += VTSize; 6729 } 6730 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6731 OutChains.clear(); 6732 for (unsigned i = 0; i < NumMemOps; i++) { 6733 EVT VT = MemOps[i]; 6734 unsigned VTSize = VT.getSizeInBits() / 8; 6735 SDValue Store; 6736 6737 Store = DAG.getStore( 6738 Chain, dl, LoadValues[i], 6739 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6740 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6741 OutChains.push_back(Store); 6742 DstOff += VTSize; 6743 } 6744 6745 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6746 } 6747 6748 /// Lower the call to 'memset' intrinsic function into a series of store 6749 /// operations. 6750 /// 6751 /// \param DAG Selection DAG where lowered code is placed. 6752 /// \param dl Link to corresponding IR location. 6753 /// \param Chain Control flow dependency. 6754 /// \param Dst Pointer to destination memory location. 6755 /// \param Src Value of byte to write into the memory. 6756 /// \param Size Number of bytes to write. 6757 /// \param Alignment Alignment of the destination in bytes. 6758 /// \param isVol True if destination is volatile. 6759 /// \param DstPtrInfo IR information on the memory pointer. 6760 /// \returns New head in the control flow, if lowering was successful, empty 6761 /// SDValue otherwise. 6762 /// 6763 /// The function tries to replace 'llvm.memset' intrinsic with several store 6764 /// operations and value calculation code. This is usually profitable for small 6765 /// memory size. 6766 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6767 SDValue Chain, SDValue Dst, SDValue Src, 6768 uint64_t Size, Align Alignment, bool isVol, 6769 MachinePointerInfo DstPtrInfo, 6770 const AAMDNodes &AAInfo) { 6771 // Turn a memset of undef to nop. 6772 // FIXME: We need to honor volatile even is Src is undef. 6773 if (Src.isUndef()) 6774 return Chain; 6775 6776 // Expand memset to a series of load/store ops if the size operand 6777 // falls below a certain threshold. 6778 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6779 std::vector<EVT> MemOps; 6780 bool DstAlignCanChange = false; 6781 MachineFunction &MF = DAG.getMachineFunction(); 6782 MachineFrameInfo &MFI = MF.getFrameInfo(); 6783 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6784 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6785 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6786 DstAlignCanChange = true; 6787 bool IsZeroVal = 6788 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6789 if (!TLI.findOptimalMemOpLowering( 6790 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6791 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6792 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6793 return SDValue(); 6794 6795 if (DstAlignCanChange) { 6796 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6797 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6798 if (NewAlign > Alignment) { 6799 // Give the stack frame object a larger alignment if needed. 6800 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6801 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6802 Alignment = NewAlign; 6803 } 6804 } 6805 6806 SmallVector<SDValue, 8> OutChains; 6807 uint64_t DstOff = 0; 6808 unsigned NumMemOps = MemOps.size(); 6809 6810 // Find the largest store and generate the bit pattern for it. 6811 EVT LargestVT = MemOps[0]; 6812 for (unsigned i = 1; i < NumMemOps; i++) 6813 if (MemOps[i].bitsGT(LargestVT)) 6814 LargestVT = MemOps[i]; 6815 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6816 6817 // Prepare AAInfo for loads/stores after lowering this memset. 6818 AAMDNodes NewAAInfo = AAInfo; 6819 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6820 6821 for (unsigned i = 0; i < NumMemOps; i++) { 6822 EVT VT = MemOps[i]; 6823 unsigned VTSize = VT.getSizeInBits() / 8; 6824 if (VTSize > Size) { 6825 // Issuing an unaligned load / store pair that overlaps with the previous 6826 // pair. Adjust the offset accordingly. 6827 assert(i == NumMemOps-1 && i != 0); 6828 DstOff -= VTSize - Size; 6829 } 6830 6831 // If this store is smaller than the largest store see whether we can get 6832 // the smaller value for free with a truncate. 6833 SDValue Value = MemSetValue; 6834 if (VT.bitsLT(LargestVT)) { 6835 if (!LargestVT.isVector() && !VT.isVector() && 6836 TLI.isTruncateFree(LargestVT, VT)) 6837 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6838 else 6839 Value = getMemsetValue(Src, VT, DAG, dl); 6840 } 6841 assert(Value.getValueType() == VT && "Value with wrong type."); 6842 SDValue Store = DAG.getStore( 6843 Chain, dl, Value, 6844 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6845 DstPtrInfo.getWithOffset(DstOff), Alignment, 6846 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 6847 NewAAInfo); 6848 OutChains.push_back(Store); 6849 DstOff += VT.getSizeInBits() / 8; 6850 Size -= VTSize; 6851 } 6852 6853 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6854 } 6855 6856 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6857 unsigned AS) { 6858 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6859 // pointer operands can be losslessly bitcasted to pointers of address space 0 6860 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6861 report_fatal_error("cannot lower memory intrinsic in address space " + 6862 Twine(AS)); 6863 } 6864 } 6865 6866 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6867 SDValue Src, SDValue Size, Align Alignment, 6868 bool isVol, bool AlwaysInline, bool isTailCall, 6869 MachinePointerInfo DstPtrInfo, 6870 MachinePointerInfo SrcPtrInfo, 6871 const AAMDNodes &AAInfo) { 6872 // Check to see if we should lower the memcpy to loads and stores first. 6873 // For cases within the target-specified limits, this is the best choice. 6874 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6875 if (ConstantSize) { 6876 // Memcpy with size zero? Just return the original chain. 6877 if (ConstantSize->isZero()) 6878 return Chain; 6879 6880 SDValue Result = getMemcpyLoadsAndStores( 6881 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6882 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6883 if (Result.getNode()) 6884 return Result; 6885 } 6886 6887 // Then check to see if we should lower the memcpy with target-specific 6888 // code. If the target chooses to do this, this is the next best. 6889 if (TSI) { 6890 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6891 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6892 DstPtrInfo, SrcPtrInfo); 6893 if (Result.getNode()) 6894 return Result; 6895 } 6896 6897 // If we really need inline code and the target declined to provide it, 6898 // use a (potentially long) sequence of loads and stores. 6899 if (AlwaysInline) { 6900 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6901 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6902 ConstantSize->getZExtValue(), Alignment, 6903 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 6904 } 6905 6906 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6907 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6908 6909 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6910 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6911 // respect volatile, so they may do things like read or write memory 6912 // beyond the given memory regions. But fixing this isn't easy, and most 6913 // people don't care. 6914 6915 // Emit a library call. 6916 TargetLowering::ArgListTy Args; 6917 TargetLowering::ArgListEntry Entry; 6918 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6919 Entry.Node = Dst; Args.push_back(Entry); 6920 Entry.Node = Src; Args.push_back(Entry); 6921 6922 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6923 Entry.Node = Size; Args.push_back(Entry); 6924 // FIXME: pass in SDLoc 6925 TargetLowering::CallLoweringInfo CLI(*this); 6926 CLI.setDebugLoc(dl) 6927 .setChain(Chain) 6928 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6929 Dst.getValueType().getTypeForEVT(*getContext()), 6930 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6931 TLI->getPointerTy(getDataLayout())), 6932 std::move(Args)) 6933 .setDiscardResult() 6934 .setTailCall(isTailCall); 6935 6936 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6937 return CallResult.second; 6938 } 6939 6940 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6941 SDValue Dst, unsigned DstAlign, 6942 SDValue Src, unsigned SrcAlign, 6943 SDValue Size, Type *SizeTy, 6944 unsigned ElemSz, bool isTailCall, 6945 MachinePointerInfo DstPtrInfo, 6946 MachinePointerInfo SrcPtrInfo) { 6947 // Emit a library call. 6948 TargetLowering::ArgListTy Args; 6949 TargetLowering::ArgListEntry Entry; 6950 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6951 Entry.Node = Dst; 6952 Args.push_back(Entry); 6953 6954 Entry.Node = Src; 6955 Args.push_back(Entry); 6956 6957 Entry.Ty = SizeTy; 6958 Entry.Node = Size; 6959 Args.push_back(Entry); 6960 6961 RTLIB::Libcall LibraryCall = 6962 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6963 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6964 report_fatal_error("Unsupported element size"); 6965 6966 TargetLowering::CallLoweringInfo CLI(*this); 6967 CLI.setDebugLoc(dl) 6968 .setChain(Chain) 6969 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6970 Type::getVoidTy(*getContext()), 6971 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6972 TLI->getPointerTy(getDataLayout())), 6973 std::move(Args)) 6974 .setDiscardResult() 6975 .setTailCall(isTailCall); 6976 6977 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6978 return CallResult.second; 6979 } 6980 6981 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6982 SDValue Src, SDValue Size, Align Alignment, 6983 bool isVol, bool isTailCall, 6984 MachinePointerInfo DstPtrInfo, 6985 MachinePointerInfo SrcPtrInfo, 6986 const AAMDNodes &AAInfo) { 6987 // Check to see if we should lower the memmove to loads and stores first. 6988 // For cases within the target-specified limits, this is the best choice. 6989 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6990 if (ConstantSize) { 6991 // Memmove with size zero? Just return the original chain. 6992 if (ConstantSize->isZero()) 6993 return Chain; 6994 6995 SDValue Result = getMemmoveLoadsAndStores( 6996 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6997 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6998 if (Result.getNode()) 6999 return Result; 7000 } 7001 7002 // Then check to see if we should lower the memmove with target-specific 7003 // code. If the target chooses to do this, this is the next best. 7004 if (TSI) { 7005 SDValue Result = 7006 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7007 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7008 if (Result.getNode()) 7009 return Result; 7010 } 7011 7012 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7013 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7014 7015 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7016 // not be safe. See memcpy above for more details. 7017 7018 // Emit a library call. 7019 TargetLowering::ArgListTy Args; 7020 TargetLowering::ArgListEntry Entry; 7021 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7022 Entry.Node = Dst; Args.push_back(Entry); 7023 Entry.Node = Src; Args.push_back(Entry); 7024 7025 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7026 Entry.Node = Size; Args.push_back(Entry); 7027 // FIXME: pass in SDLoc 7028 TargetLowering::CallLoweringInfo CLI(*this); 7029 CLI.setDebugLoc(dl) 7030 .setChain(Chain) 7031 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7032 Dst.getValueType().getTypeForEVT(*getContext()), 7033 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7034 TLI->getPointerTy(getDataLayout())), 7035 std::move(Args)) 7036 .setDiscardResult() 7037 .setTailCall(isTailCall); 7038 7039 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7040 return CallResult.second; 7041 } 7042 7043 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7044 SDValue Dst, unsigned DstAlign, 7045 SDValue Src, unsigned SrcAlign, 7046 SDValue Size, Type *SizeTy, 7047 unsigned ElemSz, bool isTailCall, 7048 MachinePointerInfo DstPtrInfo, 7049 MachinePointerInfo SrcPtrInfo) { 7050 // Emit a library call. 7051 TargetLowering::ArgListTy Args; 7052 TargetLowering::ArgListEntry Entry; 7053 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7054 Entry.Node = Dst; 7055 Args.push_back(Entry); 7056 7057 Entry.Node = Src; 7058 Args.push_back(Entry); 7059 7060 Entry.Ty = SizeTy; 7061 Entry.Node = Size; 7062 Args.push_back(Entry); 7063 7064 RTLIB::Libcall LibraryCall = 7065 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7066 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7067 report_fatal_error("Unsupported element size"); 7068 7069 TargetLowering::CallLoweringInfo CLI(*this); 7070 CLI.setDebugLoc(dl) 7071 .setChain(Chain) 7072 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7073 Type::getVoidTy(*getContext()), 7074 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7075 TLI->getPointerTy(getDataLayout())), 7076 std::move(Args)) 7077 .setDiscardResult() 7078 .setTailCall(isTailCall); 7079 7080 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7081 return CallResult.second; 7082 } 7083 7084 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7085 SDValue Src, SDValue Size, Align Alignment, 7086 bool isVol, bool isTailCall, 7087 MachinePointerInfo DstPtrInfo, 7088 const AAMDNodes &AAInfo) { 7089 // Check to see if we should lower the memset to stores first. 7090 // For cases within the target-specified limits, this is the best choice. 7091 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7092 if (ConstantSize) { 7093 // Memset with size zero? Just return the original chain. 7094 if (ConstantSize->isZero()) 7095 return Chain; 7096 7097 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7098 ConstantSize->getZExtValue(), Alignment, 7099 isVol, DstPtrInfo, AAInfo); 7100 7101 if (Result.getNode()) 7102 return Result; 7103 } 7104 7105 // Then check to see if we should lower the memset with target-specific 7106 // code. If the target chooses to do this, this is the next best. 7107 if (TSI) { 7108 SDValue Result = TSI->EmitTargetCodeForMemset( 7109 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7110 if (Result.getNode()) 7111 return Result; 7112 } 7113 7114 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7115 7116 // Emit a library call. 7117 TargetLowering::ArgListTy Args; 7118 TargetLowering::ArgListEntry Entry; 7119 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7120 Args.push_back(Entry); 7121 Entry.Node = Src; 7122 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7123 Args.push_back(Entry); 7124 Entry.Node = Size; 7125 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7126 Args.push_back(Entry); 7127 7128 // FIXME: pass in SDLoc 7129 TargetLowering::CallLoweringInfo CLI(*this); 7130 CLI.setDebugLoc(dl) 7131 .setChain(Chain) 7132 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7133 Dst.getValueType().getTypeForEVT(*getContext()), 7134 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7135 TLI->getPointerTy(getDataLayout())), 7136 std::move(Args)) 7137 .setDiscardResult() 7138 .setTailCall(isTailCall); 7139 7140 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7141 return CallResult.second; 7142 } 7143 7144 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7145 SDValue Dst, unsigned DstAlign, 7146 SDValue Value, SDValue Size, Type *SizeTy, 7147 unsigned ElemSz, bool isTailCall, 7148 MachinePointerInfo DstPtrInfo) { 7149 // Emit a library call. 7150 TargetLowering::ArgListTy Args; 7151 TargetLowering::ArgListEntry Entry; 7152 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7153 Entry.Node = Dst; 7154 Args.push_back(Entry); 7155 7156 Entry.Ty = Type::getInt8Ty(*getContext()); 7157 Entry.Node = Value; 7158 Args.push_back(Entry); 7159 7160 Entry.Ty = SizeTy; 7161 Entry.Node = Size; 7162 Args.push_back(Entry); 7163 7164 RTLIB::Libcall LibraryCall = 7165 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7166 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7167 report_fatal_error("Unsupported element size"); 7168 7169 TargetLowering::CallLoweringInfo CLI(*this); 7170 CLI.setDebugLoc(dl) 7171 .setChain(Chain) 7172 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7173 Type::getVoidTy(*getContext()), 7174 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7175 TLI->getPointerTy(getDataLayout())), 7176 std::move(Args)) 7177 .setDiscardResult() 7178 .setTailCall(isTailCall); 7179 7180 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7181 return CallResult.second; 7182 } 7183 7184 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7185 SDVTList VTList, ArrayRef<SDValue> Ops, 7186 MachineMemOperand *MMO) { 7187 FoldingSetNodeID ID; 7188 ID.AddInteger(MemVT.getRawBits()); 7189 AddNodeIDNode(ID, Opcode, VTList, Ops); 7190 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7191 void* IP = nullptr; 7192 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7193 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7194 return SDValue(E, 0); 7195 } 7196 7197 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7198 VTList, MemVT, MMO); 7199 createOperands(N, Ops); 7200 7201 CSEMap.InsertNode(N, IP); 7202 InsertNode(N); 7203 return SDValue(N, 0); 7204 } 7205 7206 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7207 EVT MemVT, SDVTList VTs, SDValue Chain, 7208 SDValue Ptr, SDValue Cmp, SDValue Swp, 7209 MachineMemOperand *MMO) { 7210 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7211 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7212 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7213 7214 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7215 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7216 } 7217 7218 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7219 SDValue Chain, SDValue Ptr, SDValue Val, 7220 MachineMemOperand *MMO) { 7221 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7222 Opcode == ISD::ATOMIC_LOAD_SUB || 7223 Opcode == ISD::ATOMIC_LOAD_AND || 7224 Opcode == ISD::ATOMIC_LOAD_CLR || 7225 Opcode == ISD::ATOMIC_LOAD_OR || 7226 Opcode == ISD::ATOMIC_LOAD_XOR || 7227 Opcode == ISD::ATOMIC_LOAD_NAND || 7228 Opcode == ISD::ATOMIC_LOAD_MIN || 7229 Opcode == ISD::ATOMIC_LOAD_MAX || 7230 Opcode == ISD::ATOMIC_LOAD_UMIN || 7231 Opcode == ISD::ATOMIC_LOAD_UMAX || 7232 Opcode == ISD::ATOMIC_LOAD_FADD || 7233 Opcode == ISD::ATOMIC_LOAD_FSUB || 7234 Opcode == ISD::ATOMIC_SWAP || 7235 Opcode == ISD::ATOMIC_STORE) && 7236 "Invalid Atomic Op"); 7237 7238 EVT VT = Val.getValueType(); 7239 7240 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7241 getVTList(VT, MVT::Other); 7242 SDValue Ops[] = {Chain, Ptr, Val}; 7243 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7244 } 7245 7246 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7247 EVT VT, SDValue Chain, SDValue Ptr, 7248 MachineMemOperand *MMO) { 7249 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7250 7251 SDVTList VTs = getVTList(VT, MVT::Other); 7252 SDValue Ops[] = {Chain, Ptr}; 7253 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7254 } 7255 7256 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7257 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7258 if (Ops.size() == 1) 7259 return Ops[0]; 7260 7261 SmallVector<EVT, 4> VTs; 7262 VTs.reserve(Ops.size()); 7263 for (const SDValue &Op : Ops) 7264 VTs.push_back(Op.getValueType()); 7265 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7266 } 7267 7268 SDValue SelectionDAG::getMemIntrinsicNode( 7269 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7270 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7271 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7272 if (!Size && MemVT.isScalableVector()) 7273 Size = MemoryLocation::UnknownSize; 7274 else if (!Size) 7275 Size = MemVT.getStoreSize(); 7276 7277 MachineFunction &MF = getMachineFunction(); 7278 MachineMemOperand *MMO = 7279 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7280 7281 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7282 } 7283 7284 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7285 SDVTList VTList, 7286 ArrayRef<SDValue> Ops, EVT MemVT, 7287 MachineMemOperand *MMO) { 7288 assert((Opcode == ISD::INTRINSIC_VOID || 7289 Opcode == ISD::INTRINSIC_W_CHAIN || 7290 Opcode == ISD::PREFETCH || 7291 ((int)Opcode <= std::numeric_limits<int>::max() && 7292 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7293 "Opcode is not a memory-accessing opcode!"); 7294 7295 // Memoize the node unless it returns a flag. 7296 MemIntrinsicSDNode *N; 7297 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7298 FoldingSetNodeID ID; 7299 AddNodeIDNode(ID, Opcode, VTList, Ops); 7300 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7301 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7302 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7303 void *IP = nullptr; 7304 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7305 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7306 return SDValue(E, 0); 7307 } 7308 7309 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7310 VTList, MemVT, MMO); 7311 createOperands(N, Ops); 7312 7313 CSEMap.InsertNode(N, IP); 7314 } else { 7315 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7316 VTList, MemVT, MMO); 7317 createOperands(N, Ops); 7318 } 7319 InsertNode(N); 7320 SDValue V(N, 0); 7321 NewSDValueDbgMsg(V, "Creating new node: ", this); 7322 return V; 7323 } 7324 7325 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7326 SDValue Chain, int FrameIndex, 7327 int64_t Size, int64_t Offset) { 7328 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7329 const auto VTs = getVTList(MVT::Other); 7330 SDValue Ops[2] = { 7331 Chain, 7332 getFrameIndex(FrameIndex, 7333 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7334 true)}; 7335 7336 FoldingSetNodeID ID; 7337 AddNodeIDNode(ID, Opcode, VTs, Ops); 7338 ID.AddInteger(FrameIndex); 7339 ID.AddInteger(Size); 7340 ID.AddInteger(Offset); 7341 void *IP = nullptr; 7342 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7343 return SDValue(E, 0); 7344 7345 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7346 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7347 createOperands(N, Ops); 7348 CSEMap.InsertNode(N, IP); 7349 InsertNode(N); 7350 SDValue V(N, 0); 7351 NewSDValueDbgMsg(V, "Creating new node: ", this); 7352 return V; 7353 } 7354 7355 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7356 uint64_t Guid, uint64_t Index, 7357 uint32_t Attr) { 7358 const unsigned Opcode = ISD::PSEUDO_PROBE; 7359 const auto VTs = getVTList(MVT::Other); 7360 SDValue Ops[] = {Chain}; 7361 FoldingSetNodeID ID; 7362 AddNodeIDNode(ID, Opcode, VTs, Ops); 7363 ID.AddInteger(Guid); 7364 ID.AddInteger(Index); 7365 void *IP = nullptr; 7366 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7367 return SDValue(E, 0); 7368 7369 auto *N = newSDNode<PseudoProbeSDNode>( 7370 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7371 createOperands(N, Ops); 7372 CSEMap.InsertNode(N, IP); 7373 InsertNode(N); 7374 SDValue V(N, 0); 7375 NewSDValueDbgMsg(V, "Creating new node: ", this); 7376 return V; 7377 } 7378 7379 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7380 /// MachinePointerInfo record from it. This is particularly useful because the 7381 /// code generator has many cases where it doesn't bother passing in a 7382 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7383 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7384 SelectionDAG &DAG, SDValue Ptr, 7385 int64_t Offset = 0) { 7386 // If this is FI+Offset, we can model it. 7387 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7388 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7389 FI->getIndex(), Offset); 7390 7391 // If this is (FI+Offset1)+Offset2, we can model it. 7392 if (Ptr.getOpcode() != ISD::ADD || 7393 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7394 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7395 return Info; 7396 7397 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7398 return MachinePointerInfo::getFixedStack( 7399 DAG.getMachineFunction(), FI, 7400 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7401 } 7402 7403 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7404 /// MachinePointerInfo record from it. This is particularly useful because the 7405 /// code generator has many cases where it doesn't bother passing in a 7406 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7407 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7408 SelectionDAG &DAG, SDValue Ptr, 7409 SDValue OffsetOp) { 7410 // If the 'Offset' value isn't a constant, we can't handle this. 7411 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7412 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7413 if (OffsetOp.isUndef()) 7414 return InferPointerInfo(Info, DAG, Ptr); 7415 return Info; 7416 } 7417 7418 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7419 EVT VT, const SDLoc &dl, SDValue Chain, 7420 SDValue Ptr, SDValue Offset, 7421 MachinePointerInfo PtrInfo, EVT MemVT, 7422 Align Alignment, 7423 MachineMemOperand::Flags MMOFlags, 7424 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7425 assert(Chain.getValueType() == MVT::Other && 7426 "Invalid chain type"); 7427 7428 MMOFlags |= MachineMemOperand::MOLoad; 7429 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7430 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7431 // clients. 7432 if (PtrInfo.V.isNull()) 7433 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7434 7435 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7436 MachineFunction &MF = getMachineFunction(); 7437 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7438 Alignment, AAInfo, Ranges); 7439 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7440 } 7441 7442 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7443 EVT VT, const SDLoc &dl, SDValue Chain, 7444 SDValue Ptr, SDValue Offset, EVT MemVT, 7445 MachineMemOperand *MMO) { 7446 if (VT == MemVT) { 7447 ExtType = ISD::NON_EXTLOAD; 7448 } else if (ExtType == ISD::NON_EXTLOAD) { 7449 assert(VT == MemVT && "Non-extending load from different memory type!"); 7450 } else { 7451 // Extending load. 7452 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7453 "Should only be an extending load, not truncating!"); 7454 assert(VT.isInteger() == MemVT.isInteger() && 7455 "Cannot convert from FP to Int or Int -> FP!"); 7456 assert(VT.isVector() == MemVT.isVector() && 7457 "Cannot use an ext load to convert to or from a vector!"); 7458 assert((!VT.isVector() || 7459 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7460 "Cannot use an ext load to change the number of vector elements!"); 7461 } 7462 7463 bool Indexed = AM != ISD::UNINDEXED; 7464 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7465 7466 SDVTList VTs = Indexed ? 7467 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7468 SDValue Ops[] = { Chain, Ptr, Offset }; 7469 FoldingSetNodeID ID; 7470 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7471 ID.AddInteger(MemVT.getRawBits()); 7472 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7473 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7474 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7475 void *IP = nullptr; 7476 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7477 cast<LoadSDNode>(E)->refineAlignment(MMO); 7478 return SDValue(E, 0); 7479 } 7480 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7481 ExtType, MemVT, MMO); 7482 createOperands(N, Ops); 7483 7484 CSEMap.InsertNode(N, IP); 7485 InsertNode(N); 7486 SDValue V(N, 0); 7487 NewSDValueDbgMsg(V, "Creating new node: ", this); 7488 return V; 7489 } 7490 7491 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7492 SDValue Ptr, MachinePointerInfo PtrInfo, 7493 MaybeAlign Alignment, 7494 MachineMemOperand::Flags MMOFlags, 7495 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7496 SDValue Undef = getUNDEF(Ptr.getValueType()); 7497 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7498 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7499 } 7500 7501 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7502 SDValue Ptr, MachineMemOperand *MMO) { 7503 SDValue Undef = getUNDEF(Ptr.getValueType()); 7504 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7505 VT, MMO); 7506 } 7507 7508 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7509 EVT VT, SDValue Chain, SDValue Ptr, 7510 MachinePointerInfo PtrInfo, EVT MemVT, 7511 MaybeAlign Alignment, 7512 MachineMemOperand::Flags MMOFlags, 7513 const AAMDNodes &AAInfo) { 7514 SDValue Undef = getUNDEF(Ptr.getValueType()); 7515 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7516 MemVT, Alignment, MMOFlags, AAInfo); 7517 } 7518 7519 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7520 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7521 MachineMemOperand *MMO) { 7522 SDValue Undef = getUNDEF(Ptr.getValueType()); 7523 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7524 MemVT, MMO); 7525 } 7526 7527 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7528 SDValue Base, SDValue Offset, 7529 ISD::MemIndexedMode AM) { 7530 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7531 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7532 // Don't propagate the invariant or dereferenceable flags. 7533 auto MMOFlags = 7534 LD->getMemOperand()->getFlags() & 7535 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7536 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7537 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7538 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7539 } 7540 7541 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7542 SDValue Ptr, MachinePointerInfo PtrInfo, 7543 Align Alignment, 7544 MachineMemOperand::Flags MMOFlags, 7545 const AAMDNodes &AAInfo) { 7546 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7547 7548 MMOFlags |= MachineMemOperand::MOStore; 7549 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7550 7551 if (PtrInfo.V.isNull()) 7552 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7553 7554 MachineFunction &MF = getMachineFunction(); 7555 uint64_t Size = 7556 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7557 MachineMemOperand *MMO = 7558 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7559 return getStore(Chain, dl, Val, Ptr, MMO); 7560 } 7561 7562 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7563 SDValue Ptr, MachineMemOperand *MMO) { 7564 assert(Chain.getValueType() == MVT::Other && 7565 "Invalid chain type"); 7566 EVT VT = Val.getValueType(); 7567 SDVTList VTs = getVTList(MVT::Other); 7568 SDValue Undef = getUNDEF(Ptr.getValueType()); 7569 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7570 FoldingSetNodeID ID; 7571 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7572 ID.AddInteger(VT.getRawBits()); 7573 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7574 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7575 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7576 void *IP = nullptr; 7577 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7578 cast<StoreSDNode>(E)->refineAlignment(MMO); 7579 return SDValue(E, 0); 7580 } 7581 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7582 ISD::UNINDEXED, false, VT, MMO); 7583 createOperands(N, Ops); 7584 7585 CSEMap.InsertNode(N, IP); 7586 InsertNode(N); 7587 SDValue V(N, 0); 7588 NewSDValueDbgMsg(V, "Creating new node: ", this); 7589 return V; 7590 } 7591 7592 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7593 SDValue Ptr, MachinePointerInfo PtrInfo, 7594 EVT SVT, Align Alignment, 7595 MachineMemOperand::Flags MMOFlags, 7596 const AAMDNodes &AAInfo) { 7597 assert(Chain.getValueType() == MVT::Other && 7598 "Invalid chain type"); 7599 7600 MMOFlags |= MachineMemOperand::MOStore; 7601 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7602 7603 if (PtrInfo.V.isNull()) 7604 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7605 7606 MachineFunction &MF = getMachineFunction(); 7607 MachineMemOperand *MMO = MF.getMachineMemOperand( 7608 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7609 Alignment, AAInfo); 7610 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7611 } 7612 7613 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7614 SDValue Ptr, EVT SVT, 7615 MachineMemOperand *MMO) { 7616 EVT VT = Val.getValueType(); 7617 7618 assert(Chain.getValueType() == MVT::Other && 7619 "Invalid chain type"); 7620 if (VT == SVT) 7621 return getStore(Chain, dl, Val, Ptr, MMO); 7622 7623 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7624 "Should only be a truncating store, not extending!"); 7625 assert(VT.isInteger() == SVT.isInteger() && 7626 "Can't do FP-INT conversion!"); 7627 assert(VT.isVector() == SVT.isVector() && 7628 "Cannot use trunc store to convert to or from a vector!"); 7629 assert((!VT.isVector() || 7630 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7631 "Cannot use trunc store to change the number of vector elements!"); 7632 7633 SDVTList VTs = getVTList(MVT::Other); 7634 SDValue Undef = getUNDEF(Ptr.getValueType()); 7635 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7636 FoldingSetNodeID ID; 7637 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7638 ID.AddInteger(SVT.getRawBits()); 7639 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7640 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7641 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7642 void *IP = nullptr; 7643 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7644 cast<StoreSDNode>(E)->refineAlignment(MMO); 7645 return SDValue(E, 0); 7646 } 7647 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7648 ISD::UNINDEXED, true, SVT, MMO); 7649 createOperands(N, Ops); 7650 7651 CSEMap.InsertNode(N, IP); 7652 InsertNode(N); 7653 SDValue V(N, 0); 7654 NewSDValueDbgMsg(V, "Creating new node: ", this); 7655 return V; 7656 } 7657 7658 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7659 SDValue Base, SDValue Offset, 7660 ISD::MemIndexedMode AM) { 7661 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7662 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7663 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7664 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7665 FoldingSetNodeID ID; 7666 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7667 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7668 ID.AddInteger(ST->getRawSubclassData()); 7669 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7670 void *IP = nullptr; 7671 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7672 return SDValue(E, 0); 7673 7674 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7675 ST->isTruncatingStore(), ST->getMemoryVT(), 7676 ST->getMemOperand()); 7677 createOperands(N, Ops); 7678 7679 CSEMap.InsertNode(N, IP); 7680 InsertNode(N); 7681 SDValue V(N, 0); 7682 NewSDValueDbgMsg(V, "Creating new node: ", this); 7683 return V; 7684 } 7685 7686 SDValue SelectionDAG::getLoadVP( 7687 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7688 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7689 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7690 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7691 const MDNode *Ranges, bool IsExpanding) { 7692 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7693 7694 MMOFlags |= MachineMemOperand::MOLoad; 7695 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7696 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7697 // clients. 7698 if (PtrInfo.V.isNull()) 7699 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7700 7701 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7702 MachineFunction &MF = getMachineFunction(); 7703 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7704 Alignment, AAInfo, Ranges); 7705 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7706 MMO, IsExpanding); 7707 } 7708 7709 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7710 ISD::LoadExtType ExtType, EVT VT, 7711 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7712 SDValue Offset, SDValue Mask, SDValue EVL, 7713 EVT MemVT, MachineMemOperand *MMO, 7714 bool IsExpanding) { 7715 if (VT == MemVT) { 7716 ExtType = ISD::NON_EXTLOAD; 7717 } else if (ExtType == ISD::NON_EXTLOAD) { 7718 assert(VT == MemVT && "Non-extending load from different memory type!"); 7719 } else { 7720 // Extending load. 7721 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7722 "Should only be an extending load, not truncating!"); 7723 assert(VT.isInteger() == MemVT.isInteger() && 7724 "Cannot convert from FP to Int or Int -> FP!"); 7725 assert(VT.isVector() == MemVT.isVector() && 7726 "Cannot use an ext load to convert to or from a vector!"); 7727 assert((!VT.isVector() || 7728 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7729 "Cannot use an ext load to change the number of vector elements!"); 7730 } 7731 7732 bool Indexed = AM != ISD::UNINDEXED; 7733 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7734 7735 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7736 : getVTList(VT, MVT::Other); 7737 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7738 FoldingSetNodeID ID; 7739 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7740 ID.AddInteger(VT.getRawBits()); 7741 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7742 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7743 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7744 void *IP = nullptr; 7745 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7746 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7747 return SDValue(E, 0); 7748 } 7749 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7750 ExtType, IsExpanding, MemVT, MMO); 7751 createOperands(N, Ops); 7752 7753 CSEMap.InsertNode(N, IP); 7754 InsertNode(N); 7755 SDValue V(N, 0); 7756 NewSDValueDbgMsg(V, "Creating new node: ", this); 7757 return V; 7758 } 7759 7760 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7761 SDValue Ptr, SDValue Mask, SDValue EVL, 7762 MachinePointerInfo PtrInfo, 7763 MaybeAlign Alignment, 7764 MachineMemOperand::Flags MMOFlags, 7765 const AAMDNodes &AAInfo, const MDNode *Ranges, 7766 bool IsExpanding) { 7767 SDValue Undef = getUNDEF(Ptr.getValueType()); 7768 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7769 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7770 IsExpanding); 7771 } 7772 7773 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7774 SDValue Ptr, SDValue Mask, SDValue EVL, 7775 MachineMemOperand *MMO, bool IsExpanding) { 7776 SDValue Undef = getUNDEF(Ptr.getValueType()); 7777 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7778 Mask, EVL, VT, MMO, IsExpanding); 7779 } 7780 7781 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7782 EVT VT, SDValue Chain, SDValue Ptr, 7783 SDValue Mask, SDValue EVL, 7784 MachinePointerInfo PtrInfo, EVT MemVT, 7785 MaybeAlign Alignment, 7786 MachineMemOperand::Flags MMOFlags, 7787 const AAMDNodes &AAInfo, bool IsExpanding) { 7788 SDValue Undef = getUNDEF(Ptr.getValueType()); 7789 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7790 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7791 IsExpanding); 7792 } 7793 7794 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7795 EVT VT, SDValue Chain, SDValue Ptr, 7796 SDValue Mask, SDValue EVL, EVT MemVT, 7797 MachineMemOperand *MMO, bool IsExpanding) { 7798 SDValue Undef = getUNDEF(Ptr.getValueType()); 7799 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7800 EVL, MemVT, MMO, IsExpanding); 7801 } 7802 7803 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7804 SDValue Base, SDValue Offset, 7805 ISD::MemIndexedMode AM) { 7806 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7807 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7808 // Don't propagate the invariant or dereferenceable flags. 7809 auto MMOFlags = 7810 LD->getMemOperand()->getFlags() & 7811 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7812 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7813 LD->getChain(), Base, Offset, LD->getMask(), 7814 LD->getVectorLength(), LD->getPointerInfo(), 7815 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7816 nullptr, LD->isExpandingLoad()); 7817 } 7818 7819 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7820 SDValue Ptr, SDValue Mask, SDValue EVL, 7821 MachinePointerInfo PtrInfo, Align Alignment, 7822 MachineMemOperand::Flags MMOFlags, 7823 const AAMDNodes &AAInfo, bool IsCompressing) { 7824 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7825 7826 MMOFlags |= MachineMemOperand::MOStore; 7827 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7828 7829 if (PtrInfo.V.isNull()) 7830 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7831 7832 MachineFunction &MF = getMachineFunction(); 7833 uint64_t Size = 7834 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7835 MachineMemOperand *MMO = 7836 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7837 return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing); 7838 } 7839 7840 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7841 SDValue Ptr, SDValue Mask, SDValue EVL, 7842 MachineMemOperand *MMO, bool IsCompressing) { 7843 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7844 EVT VT = Val.getValueType(); 7845 SDVTList VTs = getVTList(MVT::Other); 7846 SDValue Undef = getUNDEF(Ptr.getValueType()); 7847 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 7848 FoldingSetNodeID ID; 7849 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7850 ID.AddInteger(VT.getRawBits()); 7851 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7852 dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO)); 7853 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7854 void *IP = nullptr; 7855 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7856 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7857 return SDValue(E, 0); 7858 } 7859 auto *N = 7860 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7861 ISD::UNINDEXED, false, IsCompressing, VT, MMO); 7862 createOperands(N, Ops); 7863 7864 CSEMap.InsertNode(N, IP); 7865 InsertNode(N); 7866 SDValue V(N, 0); 7867 NewSDValueDbgMsg(V, "Creating new node: ", this); 7868 return V; 7869 } 7870 7871 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7872 SDValue Val, SDValue Ptr, SDValue Mask, 7873 SDValue EVL, MachinePointerInfo PtrInfo, 7874 EVT SVT, Align Alignment, 7875 MachineMemOperand::Flags MMOFlags, 7876 const AAMDNodes &AAInfo, 7877 bool IsCompressing) { 7878 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7879 7880 MMOFlags |= MachineMemOperand::MOStore; 7881 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7882 7883 if (PtrInfo.V.isNull()) 7884 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7885 7886 MachineFunction &MF = getMachineFunction(); 7887 MachineMemOperand *MMO = MF.getMachineMemOperand( 7888 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7889 Alignment, AAInfo); 7890 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 7891 IsCompressing); 7892 } 7893 7894 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7895 SDValue Val, SDValue Ptr, SDValue Mask, 7896 SDValue EVL, EVT SVT, 7897 MachineMemOperand *MMO, 7898 bool IsCompressing) { 7899 EVT VT = Val.getValueType(); 7900 7901 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7902 if (VT == SVT) 7903 return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing); 7904 7905 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7906 "Should only be a truncating store, not extending!"); 7907 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 7908 assert(VT.isVector() == SVT.isVector() && 7909 "Cannot use trunc store to convert to or from a vector!"); 7910 assert((!VT.isVector() || 7911 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7912 "Cannot use trunc store to change the number of vector elements!"); 7913 7914 SDVTList VTs = getVTList(MVT::Other); 7915 SDValue Undef = getUNDEF(Ptr.getValueType()); 7916 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 7917 FoldingSetNodeID ID; 7918 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7919 ID.AddInteger(SVT.getRawBits()); 7920 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7921 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 7922 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7923 void *IP = nullptr; 7924 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7925 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7926 return SDValue(E, 0); 7927 } 7928 auto *N = 7929 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7930 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 7931 createOperands(N, Ops); 7932 7933 CSEMap.InsertNode(N, IP); 7934 InsertNode(N); 7935 SDValue V(N, 0); 7936 NewSDValueDbgMsg(V, "Creating new node: ", this); 7937 return V; 7938 } 7939 7940 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 7941 SDValue Base, SDValue Offset, 7942 ISD::MemIndexedMode AM) { 7943 auto *ST = cast<VPStoreSDNode>(OrigStore); 7944 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 7945 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7946 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 7947 Offset, ST->getMask(), ST->getVectorLength()}; 7948 FoldingSetNodeID ID; 7949 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7950 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7951 ID.AddInteger(ST->getRawSubclassData()); 7952 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7953 void *IP = nullptr; 7954 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7955 return SDValue(E, 0); 7956 7957 auto *N = newSDNode<VPStoreSDNode>( 7958 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 7959 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 7960 createOperands(N, Ops); 7961 7962 CSEMap.InsertNode(N, IP); 7963 InsertNode(N); 7964 SDValue V(N, 0); 7965 NewSDValueDbgMsg(V, "Creating new node: ", this); 7966 return V; 7967 } 7968 7969 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 7970 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 7971 ISD::MemIndexType IndexType) { 7972 assert(Ops.size() == 6 && "Incompatible number of operands"); 7973 7974 FoldingSetNodeID ID; 7975 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 7976 ID.AddInteger(VT.getRawBits()); 7977 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 7978 dl.getIROrder(), VTs, VT, MMO, IndexType)); 7979 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7980 void *IP = nullptr; 7981 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7982 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 7983 return SDValue(E, 0); 7984 } 7985 7986 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7987 VT, MMO, IndexType); 7988 createOperands(N, Ops); 7989 7990 assert(N->getMask().getValueType().getVectorElementCount() == 7991 N->getValueType(0).getVectorElementCount() && 7992 "Vector width mismatch between mask and data"); 7993 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7994 N->getValueType(0).getVectorElementCount().isScalable() && 7995 "Scalable flags of index and data do not match"); 7996 assert(ElementCount::isKnownGE( 7997 N->getIndex().getValueType().getVectorElementCount(), 7998 N->getValueType(0).getVectorElementCount()) && 7999 "Vector width mismatch between index and data"); 8000 assert(isa<ConstantSDNode>(N->getScale()) && 8001 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8002 "Scale should be a constant power of 2"); 8003 8004 CSEMap.InsertNode(N, IP); 8005 InsertNode(N); 8006 SDValue V(N, 0); 8007 NewSDValueDbgMsg(V, "Creating new node: ", this); 8008 return V; 8009 } 8010 8011 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8012 ArrayRef<SDValue> Ops, 8013 MachineMemOperand *MMO, 8014 ISD::MemIndexType IndexType) { 8015 assert(Ops.size() == 7 && "Incompatible number of operands"); 8016 8017 FoldingSetNodeID ID; 8018 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8019 ID.AddInteger(VT.getRawBits()); 8020 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8021 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8022 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8023 void *IP = nullptr; 8024 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8025 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8026 return SDValue(E, 0); 8027 } 8028 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8029 VT, MMO, IndexType); 8030 createOperands(N, Ops); 8031 8032 assert(N->getMask().getValueType().getVectorElementCount() == 8033 N->getValue().getValueType().getVectorElementCount() && 8034 "Vector width mismatch between mask and data"); 8035 assert( 8036 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8037 N->getValue().getValueType().getVectorElementCount().isScalable() && 8038 "Scalable flags of index and data do not match"); 8039 assert(ElementCount::isKnownGE( 8040 N->getIndex().getValueType().getVectorElementCount(), 8041 N->getValue().getValueType().getVectorElementCount()) && 8042 "Vector width mismatch between index and data"); 8043 assert(isa<ConstantSDNode>(N->getScale()) && 8044 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8045 "Scale should be a constant power of 2"); 8046 8047 CSEMap.InsertNode(N, IP); 8048 InsertNode(N); 8049 SDValue V(N, 0); 8050 NewSDValueDbgMsg(V, "Creating new node: ", this); 8051 return V; 8052 } 8053 8054 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8055 SDValue Base, SDValue Offset, SDValue Mask, 8056 SDValue PassThru, EVT MemVT, 8057 MachineMemOperand *MMO, 8058 ISD::MemIndexedMode AM, 8059 ISD::LoadExtType ExtTy, bool isExpanding) { 8060 bool Indexed = AM != ISD::UNINDEXED; 8061 assert((Indexed || Offset.isUndef()) && 8062 "Unindexed masked load with an offset!"); 8063 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8064 : getVTList(VT, MVT::Other); 8065 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8066 FoldingSetNodeID ID; 8067 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8068 ID.AddInteger(MemVT.getRawBits()); 8069 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8070 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8071 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8072 void *IP = nullptr; 8073 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8074 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8075 return SDValue(E, 0); 8076 } 8077 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8078 AM, ExtTy, isExpanding, MemVT, MMO); 8079 createOperands(N, Ops); 8080 8081 CSEMap.InsertNode(N, IP); 8082 InsertNode(N); 8083 SDValue V(N, 0); 8084 NewSDValueDbgMsg(V, "Creating new node: ", this); 8085 return V; 8086 } 8087 8088 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8089 SDValue Base, SDValue Offset, 8090 ISD::MemIndexedMode AM) { 8091 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8092 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8093 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8094 Offset, LD->getMask(), LD->getPassThru(), 8095 LD->getMemoryVT(), LD->getMemOperand(), AM, 8096 LD->getExtensionType(), LD->isExpandingLoad()); 8097 } 8098 8099 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8100 SDValue Val, SDValue Base, SDValue Offset, 8101 SDValue Mask, EVT MemVT, 8102 MachineMemOperand *MMO, 8103 ISD::MemIndexedMode AM, bool IsTruncating, 8104 bool IsCompressing) { 8105 assert(Chain.getValueType() == MVT::Other && 8106 "Invalid chain type"); 8107 bool Indexed = AM != ISD::UNINDEXED; 8108 assert((Indexed || Offset.isUndef()) && 8109 "Unindexed masked store with an offset!"); 8110 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8111 : getVTList(MVT::Other); 8112 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8113 FoldingSetNodeID ID; 8114 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8115 ID.AddInteger(MemVT.getRawBits()); 8116 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8117 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8118 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8119 void *IP = nullptr; 8120 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8121 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8122 return SDValue(E, 0); 8123 } 8124 auto *N = 8125 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8126 IsTruncating, IsCompressing, MemVT, MMO); 8127 createOperands(N, Ops); 8128 8129 CSEMap.InsertNode(N, IP); 8130 InsertNode(N); 8131 SDValue V(N, 0); 8132 NewSDValueDbgMsg(V, "Creating new node: ", this); 8133 return V; 8134 } 8135 8136 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8137 SDValue Base, SDValue Offset, 8138 ISD::MemIndexedMode AM) { 8139 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8140 assert(ST->getOffset().isUndef() && 8141 "Masked store is already a indexed store!"); 8142 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8143 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8144 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8145 } 8146 8147 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8148 ArrayRef<SDValue> Ops, 8149 MachineMemOperand *MMO, 8150 ISD::MemIndexType IndexType, 8151 ISD::LoadExtType ExtTy) { 8152 assert(Ops.size() == 6 && "Incompatible number of operands"); 8153 8154 FoldingSetNodeID ID; 8155 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8156 ID.AddInteger(MemVT.getRawBits()); 8157 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8158 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8159 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8160 void *IP = nullptr; 8161 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8162 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8163 return SDValue(E, 0); 8164 } 8165 8166 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8167 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8168 VTs, MemVT, MMO, IndexType, ExtTy); 8169 createOperands(N, Ops); 8170 8171 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8172 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8173 assert(N->getMask().getValueType().getVectorElementCount() == 8174 N->getValueType(0).getVectorElementCount() && 8175 "Vector width mismatch between mask and data"); 8176 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8177 N->getValueType(0).getVectorElementCount().isScalable() && 8178 "Scalable flags of index and data do not match"); 8179 assert(ElementCount::isKnownGE( 8180 N->getIndex().getValueType().getVectorElementCount(), 8181 N->getValueType(0).getVectorElementCount()) && 8182 "Vector width mismatch between index and data"); 8183 assert(isa<ConstantSDNode>(N->getScale()) && 8184 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8185 "Scale should be a constant power of 2"); 8186 8187 CSEMap.InsertNode(N, IP); 8188 InsertNode(N); 8189 SDValue V(N, 0); 8190 NewSDValueDbgMsg(V, "Creating new node: ", this); 8191 return V; 8192 } 8193 8194 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8195 ArrayRef<SDValue> Ops, 8196 MachineMemOperand *MMO, 8197 ISD::MemIndexType IndexType, 8198 bool IsTrunc) { 8199 assert(Ops.size() == 6 && "Incompatible number of operands"); 8200 8201 FoldingSetNodeID ID; 8202 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8203 ID.AddInteger(MemVT.getRawBits()); 8204 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8205 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8206 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8207 void *IP = nullptr; 8208 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8209 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8210 return SDValue(E, 0); 8211 } 8212 8213 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8214 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8215 VTs, MemVT, MMO, IndexType, IsTrunc); 8216 createOperands(N, Ops); 8217 8218 assert(N->getMask().getValueType().getVectorElementCount() == 8219 N->getValue().getValueType().getVectorElementCount() && 8220 "Vector width mismatch between mask and data"); 8221 assert( 8222 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8223 N->getValue().getValueType().getVectorElementCount().isScalable() && 8224 "Scalable flags of index and data do not match"); 8225 assert(ElementCount::isKnownGE( 8226 N->getIndex().getValueType().getVectorElementCount(), 8227 N->getValue().getValueType().getVectorElementCount()) && 8228 "Vector width mismatch between index and data"); 8229 assert(isa<ConstantSDNode>(N->getScale()) && 8230 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8231 "Scale should be a constant power of 2"); 8232 8233 CSEMap.InsertNode(N, IP); 8234 InsertNode(N); 8235 SDValue V(N, 0); 8236 NewSDValueDbgMsg(V, "Creating new node: ", this); 8237 return V; 8238 } 8239 8240 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8241 // select undef, T, F --> T (if T is a constant), otherwise F 8242 // select, ?, undef, F --> F 8243 // select, ?, T, undef --> T 8244 if (Cond.isUndef()) 8245 return isConstantValueOfAnyType(T) ? T : F; 8246 if (T.isUndef()) 8247 return F; 8248 if (F.isUndef()) 8249 return T; 8250 8251 // select true, T, F --> T 8252 // select false, T, F --> F 8253 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8254 return CondC->isZero() ? F : T; 8255 8256 // TODO: This should simplify VSELECT with constant condition using something 8257 // like this (but check boolean contents to be complete?): 8258 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8259 // return T; 8260 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8261 // return F; 8262 8263 // select ?, T, T --> T 8264 if (T == F) 8265 return T; 8266 8267 return SDValue(); 8268 } 8269 8270 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8271 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8272 if (X.isUndef()) 8273 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8274 // shift X, undef --> undef (because it may shift by the bitwidth) 8275 if (Y.isUndef()) 8276 return getUNDEF(X.getValueType()); 8277 8278 // shift 0, Y --> 0 8279 // shift X, 0 --> X 8280 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8281 return X; 8282 8283 // shift X, C >= bitwidth(X) --> undef 8284 // All vector elements must be too big (or undef) to avoid partial undefs. 8285 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8286 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8287 }; 8288 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8289 return getUNDEF(X.getValueType()); 8290 8291 return SDValue(); 8292 } 8293 8294 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8295 SDNodeFlags Flags) { 8296 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8297 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8298 // operation is poison. That result can be relaxed to undef. 8299 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8300 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8301 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8302 (YC && YC->getValueAPF().isNaN()); 8303 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8304 (YC && YC->getValueAPF().isInfinity()); 8305 8306 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8307 return getUNDEF(X.getValueType()); 8308 8309 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8310 return getUNDEF(X.getValueType()); 8311 8312 if (!YC) 8313 return SDValue(); 8314 8315 // X + -0.0 --> X 8316 if (Opcode == ISD::FADD) 8317 if (YC->getValueAPF().isNegZero()) 8318 return X; 8319 8320 // X - +0.0 --> X 8321 if (Opcode == ISD::FSUB) 8322 if (YC->getValueAPF().isPosZero()) 8323 return X; 8324 8325 // X * 1.0 --> X 8326 // X / 1.0 --> X 8327 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8328 if (YC->getValueAPF().isExactlyValue(1.0)) 8329 return X; 8330 8331 // X * 0.0 --> 0.0 8332 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8333 if (YC->getValueAPF().isZero()) 8334 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8335 8336 return SDValue(); 8337 } 8338 8339 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8340 SDValue Ptr, SDValue SV, unsigned Align) { 8341 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8342 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8343 } 8344 8345 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8346 ArrayRef<SDUse> Ops) { 8347 switch (Ops.size()) { 8348 case 0: return getNode(Opcode, DL, VT); 8349 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8350 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8351 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8352 default: break; 8353 } 8354 8355 // Copy from an SDUse array into an SDValue array for use with 8356 // the regular getNode logic. 8357 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8358 return getNode(Opcode, DL, VT, NewOps); 8359 } 8360 8361 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8362 ArrayRef<SDValue> Ops) { 8363 SDNodeFlags Flags; 8364 if (Inserter) 8365 Flags = Inserter->getFlags(); 8366 return getNode(Opcode, DL, VT, Ops, Flags); 8367 } 8368 8369 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8370 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8371 unsigned NumOps = Ops.size(); 8372 switch (NumOps) { 8373 case 0: return getNode(Opcode, DL, VT); 8374 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8375 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8376 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8377 default: break; 8378 } 8379 8380 #ifndef NDEBUG 8381 for (auto &Op : Ops) 8382 assert(Op.getOpcode() != ISD::DELETED_NODE && 8383 "Operand is DELETED_NODE!"); 8384 #endif 8385 8386 switch (Opcode) { 8387 default: break; 8388 case ISD::BUILD_VECTOR: 8389 // Attempt to simplify BUILD_VECTOR. 8390 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8391 return V; 8392 break; 8393 case ISD::CONCAT_VECTORS: 8394 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8395 return V; 8396 break; 8397 case ISD::SELECT_CC: 8398 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8399 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8400 "LHS and RHS of condition must have same type!"); 8401 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8402 "True and False arms of SelectCC must have same type!"); 8403 assert(Ops[2].getValueType() == VT && 8404 "select_cc node must be of same type as true and false value!"); 8405 break; 8406 case ISD::BR_CC: 8407 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8408 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8409 "LHS/RHS of comparison should match types!"); 8410 break; 8411 } 8412 8413 // Memoize nodes. 8414 SDNode *N; 8415 SDVTList VTs = getVTList(VT); 8416 8417 if (VT != MVT::Glue) { 8418 FoldingSetNodeID ID; 8419 AddNodeIDNode(ID, Opcode, VTs, Ops); 8420 void *IP = nullptr; 8421 8422 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8423 return SDValue(E, 0); 8424 8425 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8426 createOperands(N, Ops); 8427 8428 CSEMap.InsertNode(N, IP); 8429 } else { 8430 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8431 createOperands(N, Ops); 8432 } 8433 8434 N->setFlags(Flags); 8435 InsertNode(N); 8436 SDValue V(N, 0); 8437 NewSDValueDbgMsg(V, "Creating new node: ", this); 8438 return V; 8439 } 8440 8441 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8442 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8443 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8444 } 8445 8446 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8447 ArrayRef<SDValue> Ops) { 8448 SDNodeFlags Flags; 8449 if (Inserter) 8450 Flags = Inserter->getFlags(); 8451 return getNode(Opcode, DL, VTList, Ops, Flags); 8452 } 8453 8454 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8455 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8456 if (VTList.NumVTs == 1) 8457 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8458 8459 #ifndef NDEBUG 8460 for (auto &Op : Ops) 8461 assert(Op.getOpcode() != ISD::DELETED_NODE && 8462 "Operand is DELETED_NODE!"); 8463 #endif 8464 8465 switch (Opcode) { 8466 case ISD::STRICT_FP_EXTEND: 8467 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8468 "Invalid STRICT_FP_EXTEND!"); 8469 assert(VTList.VTs[0].isFloatingPoint() && 8470 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8471 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8472 "STRICT_FP_EXTEND result type should be vector iff the operand " 8473 "type is vector!"); 8474 assert((!VTList.VTs[0].isVector() || 8475 VTList.VTs[0].getVectorNumElements() == 8476 Ops[1].getValueType().getVectorNumElements()) && 8477 "Vector element count mismatch!"); 8478 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8479 "Invalid fpext node, dst <= src!"); 8480 break; 8481 case ISD::STRICT_FP_ROUND: 8482 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8483 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8484 "STRICT_FP_ROUND result type should be vector iff the operand " 8485 "type is vector!"); 8486 assert((!VTList.VTs[0].isVector() || 8487 VTList.VTs[0].getVectorNumElements() == 8488 Ops[1].getValueType().getVectorNumElements()) && 8489 "Vector element count mismatch!"); 8490 assert(VTList.VTs[0].isFloatingPoint() && 8491 Ops[1].getValueType().isFloatingPoint() && 8492 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8493 isa<ConstantSDNode>(Ops[2]) && 8494 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8495 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8496 "Invalid STRICT_FP_ROUND!"); 8497 break; 8498 #if 0 8499 // FIXME: figure out how to safely handle things like 8500 // int foo(int x) { return 1 << (x & 255); } 8501 // int bar() { return foo(256); } 8502 case ISD::SRA_PARTS: 8503 case ISD::SRL_PARTS: 8504 case ISD::SHL_PARTS: 8505 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8506 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8507 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8508 else if (N3.getOpcode() == ISD::AND) 8509 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8510 // If the and is only masking out bits that cannot effect the shift, 8511 // eliminate the and. 8512 unsigned NumBits = VT.getScalarSizeInBits()*2; 8513 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8514 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8515 } 8516 break; 8517 #endif 8518 } 8519 8520 // Memoize the node unless it returns a flag. 8521 SDNode *N; 8522 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8523 FoldingSetNodeID ID; 8524 AddNodeIDNode(ID, Opcode, VTList, Ops); 8525 void *IP = nullptr; 8526 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8527 return SDValue(E, 0); 8528 8529 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8530 createOperands(N, Ops); 8531 CSEMap.InsertNode(N, IP); 8532 } else { 8533 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8534 createOperands(N, Ops); 8535 } 8536 8537 N->setFlags(Flags); 8538 InsertNode(N); 8539 SDValue V(N, 0); 8540 NewSDValueDbgMsg(V, "Creating new node: ", this); 8541 return V; 8542 } 8543 8544 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8545 SDVTList VTList) { 8546 return getNode(Opcode, DL, VTList, None); 8547 } 8548 8549 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8550 SDValue N1) { 8551 SDValue Ops[] = { N1 }; 8552 return getNode(Opcode, DL, VTList, Ops); 8553 } 8554 8555 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8556 SDValue N1, SDValue N2) { 8557 SDValue Ops[] = { N1, N2 }; 8558 return getNode(Opcode, DL, VTList, Ops); 8559 } 8560 8561 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8562 SDValue N1, SDValue N2, SDValue N3) { 8563 SDValue Ops[] = { N1, N2, N3 }; 8564 return getNode(Opcode, DL, VTList, Ops); 8565 } 8566 8567 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8568 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8569 SDValue Ops[] = { N1, N2, N3, N4 }; 8570 return getNode(Opcode, DL, VTList, Ops); 8571 } 8572 8573 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8574 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8575 SDValue N5) { 8576 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8577 return getNode(Opcode, DL, VTList, Ops); 8578 } 8579 8580 SDVTList SelectionDAG::getVTList(EVT VT) { 8581 return makeVTList(SDNode::getValueTypeList(VT), 1); 8582 } 8583 8584 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8585 FoldingSetNodeID ID; 8586 ID.AddInteger(2U); 8587 ID.AddInteger(VT1.getRawBits()); 8588 ID.AddInteger(VT2.getRawBits()); 8589 8590 void *IP = nullptr; 8591 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8592 if (!Result) { 8593 EVT *Array = Allocator.Allocate<EVT>(2); 8594 Array[0] = VT1; 8595 Array[1] = VT2; 8596 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8597 VTListMap.InsertNode(Result, IP); 8598 } 8599 return Result->getSDVTList(); 8600 } 8601 8602 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 8603 FoldingSetNodeID ID; 8604 ID.AddInteger(3U); 8605 ID.AddInteger(VT1.getRawBits()); 8606 ID.AddInteger(VT2.getRawBits()); 8607 ID.AddInteger(VT3.getRawBits()); 8608 8609 void *IP = nullptr; 8610 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8611 if (!Result) { 8612 EVT *Array = Allocator.Allocate<EVT>(3); 8613 Array[0] = VT1; 8614 Array[1] = VT2; 8615 Array[2] = VT3; 8616 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 8617 VTListMap.InsertNode(Result, IP); 8618 } 8619 return Result->getSDVTList(); 8620 } 8621 8622 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 8623 FoldingSetNodeID ID; 8624 ID.AddInteger(4U); 8625 ID.AddInteger(VT1.getRawBits()); 8626 ID.AddInteger(VT2.getRawBits()); 8627 ID.AddInteger(VT3.getRawBits()); 8628 ID.AddInteger(VT4.getRawBits()); 8629 8630 void *IP = nullptr; 8631 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8632 if (!Result) { 8633 EVT *Array = Allocator.Allocate<EVT>(4); 8634 Array[0] = VT1; 8635 Array[1] = VT2; 8636 Array[2] = VT3; 8637 Array[3] = VT4; 8638 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 8639 VTListMap.InsertNode(Result, IP); 8640 } 8641 return Result->getSDVTList(); 8642 } 8643 8644 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 8645 unsigned NumVTs = VTs.size(); 8646 FoldingSetNodeID ID; 8647 ID.AddInteger(NumVTs); 8648 for (unsigned index = 0; index < NumVTs; index++) { 8649 ID.AddInteger(VTs[index].getRawBits()); 8650 } 8651 8652 void *IP = nullptr; 8653 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8654 if (!Result) { 8655 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 8656 llvm::copy(VTs, Array); 8657 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 8658 VTListMap.InsertNode(Result, IP); 8659 } 8660 return Result->getSDVTList(); 8661 } 8662 8663 8664 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 8665 /// specified operands. If the resultant node already exists in the DAG, 8666 /// this does not modify the specified node, instead it returns the node that 8667 /// already exists. If the resultant node does not exist in the DAG, the 8668 /// input node is returned. As a degenerate case, if you specify the same 8669 /// input operands as the node already has, the input node is returned. 8670 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 8671 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 8672 8673 // Check to see if there is no change. 8674 if (Op == N->getOperand(0)) return N; 8675 8676 // See if the modified node already exists. 8677 void *InsertPos = nullptr; 8678 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 8679 return Existing; 8680 8681 // Nope it doesn't. Remove the node from its current place in the maps. 8682 if (InsertPos) 8683 if (!RemoveNodeFromCSEMaps(N)) 8684 InsertPos = nullptr; 8685 8686 // Now we update the operands. 8687 N->OperandList[0].set(Op); 8688 8689 updateDivergence(N); 8690 // If this gets put into a CSE map, add it. 8691 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8692 return N; 8693 } 8694 8695 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 8696 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 8697 8698 // Check to see if there is no change. 8699 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 8700 return N; // No operands changed, just return the input node. 8701 8702 // See if the modified node already exists. 8703 void *InsertPos = nullptr; 8704 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 8705 return Existing; 8706 8707 // Nope it doesn't. Remove the node from its current place in the maps. 8708 if (InsertPos) 8709 if (!RemoveNodeFromCSEMaps(N)) 8710 InsertPos = nullptr; 8711 8712 // Now we update the operands. 8713 if (N->OperandList[0] != Op1) 8714 N->OperandList[0].set(Op1); 8715 if (N->OperandList[1] != Op2) 8716 N->OperandList[1].set(Op2); 8717 8718 updateDivergence(N); 8719 // If this gets put into a CSE map, add it. 8720 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8721 return N; 8722 } 8723 8724 SDNode *SelectionDAG:: 8725 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 8726 SDValue Ops[] = { Op1, Op2, Op3 }; 8727 return UpdateNodeOperands(N, Ops); 8728 } 8729 8730 SDNode *SelectionDAG:: 8731 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8732 SDValue Op3, SDValue Op4) { 8733 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 8734 return UpdateNodeOperands(N, Ops); 8735 } 8736 8737 SDNode *SelectionDAG:: 8738 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8739 SDValue Op3, SDValue Op4, SDValue Op5) { 8740 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 8741 return UpdateNodeOperands(N, Ops); 8742 } 8743 8744 SDNode *SelectionDAG:: 8745 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 8746 unsigned NumOps = Ops.size(); 8747 assert(N->getNumOperands() == NumOps && 8748 "Update with wrong number of operands"); 8749 8750 // If no operands changed just return the input node. 8751 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 8752 return N; 8753 8754 // See if the modified node already exists. 8755 void *InsertPos = nullptr; 8756 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8757 return Existing; 8758 8759 // Nope it doesn't. Remove the node from its current place in the maps. 8760 if (InsertPos) 8761 if (!RemoveNodeFromCSEMaps(N)) 8762 InsertPos = nullptr; 8763 8764 // Now we update the operands. 8765 for (unsigned i = 0; i != NumOps; ++i) 8766 if (N->OperandList[i] != Ops[i]) 8767 N->OperandList[i].set(Ops[i]); 8768 8769 updateDivergence(N); 8770 // If this gets put into a CSE map, add it. 8771 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8772 return N; 8773 } 8774 8775 /// DropOperands - Release the operands and set this node to have 8776 /// zero operands. 8777 void SDNode::DropOperands() { 8778 // Unlike the code in MorphNodeTo that does this, we don't need to 8779 // watch for dead nodes here. 8780 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8781 SDUse &Use = *I++; 8782 Use.set(SDValue()); 8783 } 8784 } 8785 8786 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8787 ArrayRef<MachineMemOperand *> NewMemRefs) { 8788 if (NewMemRefs.empty()) { 8789 N->clearMemRefs(); 8790 return; 8791 } 8792 8793 // Check if we can avoid allocating by storing a single reference directly. 8794 if (NewMemRefs.size() == 1) { 8795 N->MemRefs = NewMemRefs[0]; 8796 N->NumMemRefs = 1; 8797 return; 8798 } 8799 8800 MachineMemOperand **MemRefsBuffer = 8801 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8802 llvm::copy(NewMemRefs, MemRefsBuffer); 8803 N->MemRefs = MemRefsBuffer; 8804 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8805 } 8806 8807 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8808 /// machine opcode. 8809 /// 8810 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8811 EVT VT) { 8812 SDVTList VTs = getVTList(VT); 8813 return SelectNodeTo(N, MachineOpc, VTs, None); 8814 } 8815 8816 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8817 EVT VT, SDValue Op1) { 8818 SDVTList VTs = getVTList(VT); 8819 SDValue Ops[] = { Op1 }; 8820 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8821 } 8822 8823 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8824 EVT VT, SDValue Op1, 8825 SDValue Op2) { 8826 SDVTList VTs = getVTList(VT); 8827 SDValue Ops[] = { Op1, Op2 }; 8828 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8829 } 8830 8831 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8832 EVT VT, SDValue Op1, 8833 SDValue Op2, SDValue Op3) { 8834 SDVTList VTs = getVTList(VT); 8835 SDValue Ops[] = { Op1, Op2, Op3 }; 8836 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8837 } 8838 8839 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8840 EVT VT, ArrayRef<SDValue> Ops) { 8841 SDVTList VTs = getVTList(VT); 8842 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8843 } 8844 8845 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8846 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8847 SDVTList VTs = getVTList(VT1, VT2); 8848 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8849 } 8850 8851 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8852 EVT VT1, EVT VT2) { 8853 SDVTList VTs = getVTList(VT1, VT2); 8854 return SelectNodeTo(N, MachineOpc, VTs, None); 8855 } 8856 8857 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8858 EVT VT1, EVT VT2, EVT VT3, 8859 ArrayRef<SDValue> Ops) { 8860 SDVTList VTs = getVTList(VT1, VT2, VT3); 8861 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8862 } 8863 8864 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8865 EVT VT1, EVT VT2, 8866 SDValue Op1, SDValue Op2) { 8867 SDVTList VTs = getVTList(VT1, VT2); 8868 SDValue Ops[] = { Op1, Op2 }; 8869 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8870 } 8871 8872 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8873 SDVTList VTs,ArrayRef<SDValue> Ops) { 8874 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8875 // Reset the NodeID to -1. 8876 New->setNodeId(-1); 8877 if (New != N) { 8878 ReplaceAllUsesWith(N, New); 8879 RemoveDeadNode(N); 8880 } 8881 return New; 8882 } 8883 8884 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8885 /// the line number information on the merged node since it is not possible to 8886 /// preserve the information that operation is associated with multiple lines. 8887 /// This will make the debugger working better at -O0, were there is a higher 8888 /// probability having other instructions associated with that line. 8889 /// 8890 /// For IROrder, we keep the smaller of the two 8891 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8892 DebugLoc NLoc = N->getDebugLoc(); 8893 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8894 N->setDebugLoc(DebugLoc()); 8895 } 8896 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8897 N->setIROrder(Order); 8898 return N; 8899 } 8900 8901 /// MorphNodeTo - This *mutates* the specified node to have the specified 8902 /// return type, opcode, and operands. 8903 /// 8904 /// Note that MorphNodeTo returns the resultant node. If there is already a 8905 /// node of the specified opcode and operands, it returns that node instead of 8906 /// the current one. Note that the SDLoc need not be the same. 8907 /// 8908 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8909 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8910 /// node, and because it doesn't require CSE recalculation for any of 8911 /// the node's users. 8912 /// 8913 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8914 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8915 /// the legalizer which maintain worklists that would need to be updated when 8916 /// deleting things. 8917 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8918 SDVTList VTs, ArrayRef<SDValue> Ops) { 8919 // If an identical node already exists, use it. 8920 void *IP = nullptr; 8921 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8922 FoldingSetNodeID ID; 8923 AddNodeIDNode(ID, Opc, VTs, Ops); 8924 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8925 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8926 } 8927 8928 if (!RemoveNodeFromCSEMaps(N)) 8929 IP = nullptr; 8930 8931 // Start the morphing. 8932 N->NodeType = Opc; 8933 N->ValueList = VTs.VTs; 8934 N->NumValues = VTs.NumVTs; 8935 8936 // Clear the operands list, updating used nodes to remove this from their 8937 // use list. Keep track of any operands that become dead as a result. 8938 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8939 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8940 SDUse &Use = *I++; 8941 SDNode *Used = Use.getNode(); 8942 Use.set(SDValue()); 8943 if (Used->use_empty()) 8944 DeadNodeSet.insert(Used); 8945 } 8946 8947 // For MachineNode, initialize the memory references information. 8948 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8949 MN->clearMemRefs(); 8950 8951 // Swap for an appropriately sized array from the recycler. 8952 removeOperands(N); 8953 createOperands(N, Ops); 8954 8955 // Delete any nodes that are still dead after adding the uses for the 8956 // new operands. 8957 if (!DeadNodeSet.empty()) { 8958 SmallVector<SDNode *, 16> DeadNodes; 8959 for (SDNode *N : DeadNodeSet) 8960 if (N->use_empty()) 8961 DeadNodes.push_back(N); 8962 RemoveDeadNodes(DeadNodes); 8963 } 8964 8965 if (IP) 8966 CSEMap.InsertNode(N, IP); // Memoize the new node. 8967 return N; 8968 } 8969 8970 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8971 unsigned OrigOpc = Node->getOpcode(); 8972 unsigned NewOpc; 8973 switch (OrigOpc) { 8974 default: 8975 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8976 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8977 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8978 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8979 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8980 #include "llvm/IR/ConstrainedOps.def" 8981 } 8982 8983 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8984 8985 // We're taking this node out of the chain, so we need to re-link things. 8986 SDValue InputChain = Node->getOperand(0); 8987 SDValue OutputChain = SDValue(Node, 1); 8988 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8989 8990 SmallVector<SDValue, 3> Ops; 8991 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8992 Ops.push_back(Node->getOperand(i)); 8993 8994 SDVTList VTs = getVTList(Node->getValueType(0)); 8995 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8996 8997 // MorphNodeTo can operate in two ways: if an existing node with the 8998 // specified operands exists, it can just return it. Otherwise, it 8999 // updates the node in place to have the requested operands. 9000 if (Res == Node) { 9001 // If we updated the node in place, reset the node ID. To the isel, 9002 // this should be just like a newly allocated machine node. 9003 Res->setNodeId(-1); 9004 } else { 9005 ReplaceAllUsesWith(Node, Res); 9006 RemoveDeadNode(Node); 9007 } 9008 9009 return Res; 9010 } 9011 9012 /// getMachineNode - These are used for target selectors to create a new node 9013 /// with specified return type(s), MachineInstr opcode, and operands. 9014 /// 9015 /// Note that getMachineNode returns the resultant node. If there is already a 9016 /// node of the specified opcode and operands, it returns that node instead of 9017 /// the current one. 9018 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9019 EVT VT) { 9020 SDVTList VTs = getVTList(VT); 9021 return getMachineNode(Opcode, dl, VTs, None); 9022 } 9023 9024 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9025 EVT VT, SDValue Op1) { 9026 SDVTList VTs = getVTList(VT); 9027 SDValue Ops[] = { Op1 }; 9028 return getMachineNode(Opcode, dl, VTs, Ops); 9029 } 9030 9031 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9032 EVT VT, SDValue Op1, SDValue Op2) { 9033 SDVTList VTs = getVTList(VT); 9034 SDValue Ops[] = { Op1, Op2 }; 9035 return getMachineNode(Opcode, dl, VTs, Ops); 9036 } 9037 9038 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9039 EVT VT, SDValue Op1, SDValue Op2, 9040 SDValue Op3) { 9041 SDVTList VTs = getVTList(VT); 9042 SDValue Ops[] = { Op1, Op2, Op3 }; 9043 return getMachineNode(Opcode, dl, VTs, Ops); 9044 } 9045 9046 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9047 EVT VT, ArrayRef<SDValue> Ops) { 9048 SDVTList VTs = getVTList(VT); 9049 return getMachineNode(Opcode, dl, VTs, Ops); 9050 } 9051 9052 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9053 EVT VT1, EVT VT2, SDValue Op1, 9054 SDValue Op2) { 9055 SDVTList VTs = getVTList(VT1, VT2); 9056 SDValue Ops[] = { Op1, Op2 }; 9057 return getMachineNode(Opcode, dl, VTs, Ops); 9058 } 9059 9060 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9061 EVT VT1, EVT VT2, SDValue Op1, 9062 SDValue Op2, SDValue Op3) { 9063 SDVTList VTs = getVTList(VT1, VT2); 9064 SDValue Ops[] = { Op1, Op2, Op3 }; 9065 return getMachineNode(Opcode, dl, VTs, Ops); 9066 } 9067 9068 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9069 EVT VT1, EVT VT2, 9070 ArrayRef<SDValue> Ops) { 9071 SDVTList VTs = getVTList(VT1, VT2); 9072 return getMachineNode(Opcode, dl, VTs, Ops); 9073 } 9074 9075 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9076 EVT VT1, EVT VT2, EVT VT3, 9077 SDValue Op1, SDValue Op2) { 9078 SDVTList VTs = getVTList(VT1, VT2, VT3); 9079 SDValue Ops[] = { Op1, Op2 }; 9080 return getMachineNode(Opcode, dl, VTs, Ops); 9081 } 9082 9083 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9084 EVT VT1, EVT VT2, EVT VT3, 9085 SDValue Op1, SDValue Op2, 9086 SDValue Op3) { 9087 SDVTList VTs = getVTList(VT1, VT2, VT3); 9088 SDValue Ops[] = { Op1, Op2, Op3 }; 9089 return getMachineNode(Opcode, dl, VTs, Ops); 9090 } 9091 9092 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9093 EVT VT1, EVT VT2, EVT VT3, 9094 ArrayRef<SDValue> Ops) { 9095 SDVTList VTs = getVTList(VT1, VT2, VT3); 9096 return getMachineNode(Opcode, dl, VTs, Ops); 9097 } 9098 9099 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9100 ArrayRef<EVT> ResultTys, 9101 ArrayRef<SDValue> Ops) { 9102 SDVTList VTs = getVTList(ResultTys); 9103 return getMachineNode(Opcode, dl, VTs, Ops); 9104 } 9105 9106 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9107 SDVTList VTs, 9108 ArrayRef<SDValue> Ops) { 9109 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9110 MachineSDNode *N; 9111 void *IP = nullptr; 9112 9113 if (DoCSE) { 9114 FoldingSetNodeID ID; 9115 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9116 IP = nullptr; 9117 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9118 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9119 } 9120 } 9121 9122 // Allocate a new MachineSDNode. 9123 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9124 createOperands(N, Ops); 9125 9126 if (DoCSE) 9127 CSEMap.InsertNode(N, IP); 9128 9129 InsertNode(N); 9130 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9131 return N; 9132 } 9133 9134 /// getTargetExtractSubreg - A convenience function for creating 9135 /// TargetOpcode::EXTRACT_SUBREG nodes. 9136 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9137 SDValue Operand) { 9138 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9139 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9140 VT, Operand, SRIdxVal); 9141 return SDValue(Subreg, 0); 9142 } 9143 9144 /// getTargetInsertSubreg - A convenience function for creating 9145 /// TargetOpcode::INSERT_SUBREG nodes. 9146 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9147 SDValue Operand, SDValue Subreg) { 9148 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9149 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9150 VT, Operand, Subreg, SRIdxVal); 9151 return SDValue(Result, 0); 9152 } 9153 9154 /// getNodeIfExists - Get the specified node if it's already available, or 9155 /// else return NULL. 9156 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9157 ArrayRef<SDValue> Ops) { 9158 SDNodeFlags Flags; 9159 if (Inserter) 9160 Flags = Inserter->getFlags(); 9161 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9162 } 9163 9164 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9165 ArrayRef<SDValue> Ops, 9166 const SDNodeFlags Flags) { 9167 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9168 FoldingSetNodeID ID; 9169 AddNodeIDNode(ID, Opcode, VTList, Ops); 9170 void *IP = nullptr; 9171 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9172 E->intersectFlagsWith(Flags); 9173 return E; 9174 } 9175 } 9176 return nullptr; 9177 } 9178 9179 /// doesNodeExist - Check if a node exists without modifying its flags. 9180 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9181 ArrayRef<SDValue> Ops) { 9182 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9183 FoldingSetNodeID ID; 9184 AddNodeIDNode(ID, Opcode, VTList, Ops); 9185 void *IP = nullptr; 9186 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9187 return true; 9188 } 9189 return false; 9190 } 9191 9192 /// getDbgValue - Creates a SDDbgValue node. 9193 /// 9194 /// SDNode 9195 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9196 SDNode *N, unsigned R, bool IsIndirect, 9197 const DebugLoc &DL, unsigned O) { 9198 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9199 "Expected inlined-at fields to agree"); 9200 return new (DbgInfo->getAlloc()) 9201 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9202 {}, IsIndirect, DL, O, 9203 /*IsVariadic=*/false); 9204 } 9205 9206 /// Constant 9207 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9208 DIExpression *Expr, 9209 const Value *C, 9210 const DebugLoc &DL, unsigned O) { 9211 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9212 "Expected inlined-at fields to agree"); 9213 return new (DbgInfo->getAlloc()) 9214 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9215 /*IsIndirect=*/false, DL, O, 9216 /*IsVariadic=*/false); 9217 } 9218 9219 /// FrameIndex 9220 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9221 DIExpression *Expr, unsigned FI, 9222 bool IsIndirect, 9223 const DebugLoc &DL, 9224 unsigned O) { 9225 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9226 "Expected inlined-at fields to agree"); 9227 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9228 } 9229 9230 /// FrameIndex with dependencies 9231 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9232 DIExpression *Expr, unsigned FI, 9233 ArrayRef<SDNode *> Dependencies, 9234 bool IsIndirect, 9235 const DebugLoc &DL, 9236 unsigned O) { 9237 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9238 "Expected inlined-at fields to agree"); 9239 return new (DbgInfo->getAlloc()) 9240 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9241 Dependencies, IsIndirect, DL, O, 9242 /*IsVariadic=*/false); 9243 } 9244 9245 /// VReg 9246 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9247 unsigned VReg, bool IsIndirect, 9248 const DebugLoc &DL, unsigned O) { 9249 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9250 "Expected inlined-at fields to agree"); 9251 return new (DbgInfo->getAlloc()) 9252 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9253 {}, IsIndirect, DL, O, 9254 /*IsVariadic=*/false); 9255 } 9256 9257 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9258 ArrayRef<SDDbgOperand> Locs, 9259 ArrayRef<SDNode *> Dependencies, 9260 bool IsIndirect, const DebugLoc &DL, 9261 unsigned O, bool IsVariadic) { 9262 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9263 "Expected inlined-at fields to agree"); 9264 return new (DbgInfo->getAlloc()) 9265 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9266 DL, O, IsVariadic); 9267 } 9268 9269 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9270 unsigned OffsetInBits, unsigned SizeInBits, 9271 bool InvalidateDbg) { 9272 SDNode *FromNode = From.getNode(); 9273 SDNode *ToNode = To.getNode(); 9274 assert(FromNode && ToNode && "Can't modify dbg values"); 9275 9276 // PR35338 9277 // TODO: assert(From != To && "Redundant dbg value transfer"); 9278 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9279 if (From == To || FromNode == ToNode) 9280 return; 9281 9282 if (!FromNode->getHasDebugValue()) 9283 return; 9284 9285 SDDbgOperand FromLocOp = 9286 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9287 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9288 9289 SmallVector<SDDbgValue *, 2> ClonedDVs; 9290 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9291 if (Dbg->isInvalidated()) 9292 continue; 9293 9294 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9295 9296 // Create a new location ops vector that is equal to the old vector, but 9297 // with each instance of FromLocOp replaced with ToLocOp. 9298 bool Changed = false; 9299 auto NewLocOps = Dbg->copyLocationOps(); 9300 std::replace_if( 9301 NewLocOps.begin(), NewLocOps.end(), 9302 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9303 bool Match = Op == FromLocOp; 9304 Changed |= Match; 9305 return Match; 9306 }, 9307 ToLocOp); 9308 // Ignore this SDDbgValue if we didn't find a matching location. 9309 if (!Changed) 9310 continue; 9311 9312 DIVariable *Var = Dbg->getVariable(); 9313 auto *Expr = Dbg->getExpression(); 9314 // If a fragment is requested, update the expression. 9315 if (SizeInBits) { 9316 // When splitting a larger (e.g., sign-extended) value whose 9317 // lower bits are described with an SDDbgValue, do not attempt 9318 // to transfer the SDDbgValue to the upper bits. 9319 if (auto FI = Expr->getFragmentInfo()) 9320 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9321 continue; 9322 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9323 SizeInBits); 9324 if (!Fragment) 9325 continue; 9326 Expr = *Fragment; 9327 } 9328 9329 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9330 // Clone the SDDbgValue and move it to To. 9331 SDDbgValue *Clone = getDbgValueList( 9332 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9333 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9334 Dbg->isVariadic()); 9335 ClonedDVs.push_back(Clone); 9336 9337 if (InvalidateDbg) { 9338 // Invalidate value and indicate the SDDbgValue should not be emitted. 9339 Dbg->setIsInvalidated(); 9340 Dbg->setIsEmitted(); 9341 } 9342 } 9343 9344 for (SDDbgValue *Dbg : ClonedDVs) { 9345 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9346 "Transferred DbgValues should depend on the new SDNode"); 9347 AddDbgValue(Dbg, false); 9348 } 9349 } 9350 9351 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9352 if (!N.getHasDebugValue()) 9353 return; 9354 9355 SmallVector<SDDbgValue *, 2> ClonedDVs; 9356 for (auto DV : GetDbgValues(&N)) { 9357 if (DV->isInvalidated()) 9358 continue; 9359 switch (N.getOpcode()) { 9360 default: 9361 break; 9362 case ISD::ADD: 9363 SDValue N0 = N.getOperand(0); 9364 SDValue N1 = N.getOperand(1); 9365 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9366 isConstantIntBuildVectorOrConstantInt(N1)) { 9367 uint64_t Offset = N.getConstantOperandVal(1); 9368 9369 // Rewrite an ADD constant node into a DIExpression. Since we are 9370 // performing arithmetic to compute the variable's *value* in the 9371 // DIExpression, we need to mark the expression with a 9372 // DW_OP_stack_value. 9373 auto *DIExpr = DV->getExpression(); 9374 auto NewLocOps = DV->copyLocationOps(); 9375 bool Changed = false; 9376 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9377 // We're not given a ResNo to compare against because the whole 9378 // node is going away. We know that any ISD::ADD only has one 9379 // result, so we can assume any node match is using the result. 9380 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9381 NewLocOps[i].getSDNode() != &N) 9382 continue; 9383 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9384 SmallVector<uint64_t, 3> ExprOps; 9385 DIExpression::appendOffset(ExprOps, Offset); 9386 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9387 Changed = true; 9388 } 9389 (void)Changed; 9390 assert(Changed && "Salvage target doesn't use N"); 9391 9392 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9393 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9394 NewLocOps, AdditionalDependencies, 9395 DV->isIndirect(), DV->getDebugLoc(), 9396 DV->getOrder(), DV->isVariadic()); 9397 ClonedDVs.push_back(Clone); 9398 DV->setIsInvalidated(); 9399 DV->setIsEmitted(); 9400 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9401 N0.getNode()->dumprFull(this); 9402 dbgs() << " into " << *DIExpr << '\n'); 9403 } 9404 } 9405 } 9406 9407 for (SDDbgValue *Dbg : ClonedDVs) { 9408 assert(!Dbg->getSDNodes().empty() && 9409 "Salvaged DbgValue should depend on a new SDNode"); 9410 AddDbgValue(Dbg, false); 9411 } 9412 } 9413 9414 /// Creates a SDDbgLabel node. 9415 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9416 const DebugLoc &DL, unsigned O) { 9417 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9418 "Expected inlined-at fields to agree"); 9419 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9420 } 9421 9422 namespace { 9423 9424 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9425 /// pointed to by a use iterator is deleted, increment the use iterator 9426 /// so that it doesn't dangle. 9427 /// 9428 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9429 SDNode::use_iterator &UI; 9430 SDNode::use_iterator &UE; 9431 9432 void NodeDeleted(SDNode *N, SDNode *E) override { 9433 // Increment the iterator as needed. 9434 while (UI != UE && N == *UI) 9435 ++UI; 9436 } 9437 9438 public: 9439 RAUWUpdateListener(SelectionDAG &d, 9440 SDNode::use_iterator &ui, 9441 SDNode::use_iterator &ue) 9442 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9443 }; 9444 9445 } // end anonymous namespace 9446 9447 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9448 /// This can cause recursive merging of nodes in the DAG. 9449 /// 9450 /// This version assumes From has a single result value. 9451 /// 9452 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9453 SDNode *From = FromN.getNode(); 9454 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9455 "Cannot replace with this method!"); 9456 assert(From != To.getNode() && "Cannot replace uses of with self"); 9457 9458 // Preserve Debug Values 9459 transferDbgValues(FromN, To); 9460 9461 // Iterate over all the existing uses of From. New uses will be added 9462 // to the beginning of the use list, which we avoid visiting. 9463 // This specifically avoids visiting uses of From that arise while the 9464 // replacement is happening, because any such uses would be the result 9465 // of CSE: If an existing node looks like From after one of its operands 9466 // is replaced by To, we don't want to replace of all its users with To 9467 // too. See PR3018 for more info. 9468 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9469 RAUWUpdateListener Listener(*this, UI, UE); 9470 while (UI != UE) { 9471 SDNode *User = *UI; 9472 9473 // This node is about to morph, remove its old self from the CSE maps. 9474 RemoveNodeFromCSEMaps(User); 9475 9476 // A user can appear in a use list multiple times, and when this 9477 // happens the uses are usually next to each other in the list. 9478 // To help reduce the number of CSE recomputations, process all 9479 // the uses of this user that we can find this way. 9480 do { 9481 SDUse &Use = UI.getUse(); 9482 ++UI; 9483 Use.set(To); 9484 if (To->isDivergent() != From->isDivergent()) 9485 updateDivergence(User); 9486 } while (UI != UE && *UI == User); 9487 // Now that we have modified User, add it back to the CSE maps. If it 9488 // already exists there, recursively merge the results together. 9489 AddModifiedNodeToCSEMaps(User); 9490 } 9491 9492 // If we just RAUW'd the root, take note. 9493 if (FromN == getRoot()) 9494 setRoot(To); 9495 } 9496 9497 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9498 /// This can cause recursive merging of nodes in the DAG. 9499 /// 9500 /// This version assumes that for each value of From, there is a 9501 /// corresponding value in To in the same position with the same type. 9502 /// 9503 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9504 #ifndef NDEBUG 9505 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9506 assert((!From->hasAnyUseOfValue(i) || 9507 From->getValueType(i) == To->getValueType(i)) && 9508 "Cannot use this version of ReplaceAllUsesWith!"); 9509 #endif 9510 9511 // Handle the trivial case. 9512 if (From == To) 9513 return; 9514 9515 // Preserve Debug Info. Only do this if there's a use. 9516 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9517 if (From->hasAnyUseOfValue(i)) { 9518 assert((i < To->getNumValues()) && "Invalid To location"); 9519 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9520 } 9521 9522 // Iterate over just the existing users of From. See the comments in 9523 // the ReplaceAllUsesWith above. 9524 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9525 RAUWUpdateListener Listener(*this, UI, UE); 9526 while (UI != UE) { 9527 SDNode *User = *UI; 9528 9529 // This node is about to morph, remove its old self from the CSE maps. 9530 RemoveNodeFromCSEMaps(User); 9531 9532 // A user can appear in a use list multiple times, and when this 9533 // happens the uses are usually next to each other in the list. 9534 // To help reduce the number of CSE recomputations, process all 9535 // the uses of this user that we can find this way. 9536 do { 9537 SDUse &Use = UI.getUse(); 9538 ++UI; 9539 Use.setNode(To); 9540 if (To->isDivergent() != From->isDivergent()) 9541 updateDivergence(User); 9542 } while (UI != UE && *UI == User); 9543 9544 // Now that we have modified User, add it back to the CSE maps. If it 9545 // already exists there, recursively merge the results together. 9546 AddModifiedNodeToCSEMaps(User); 9547 } 9548 9549 // If we just RAUW'd the root, take note. 9550 if (From == getRoot().getNode()) 9551 setRoot(SDValue(To, getRoot().getResNo())); 9552 } 9553 9554 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9555 /// This can cause recursive merging of nodes in the DAG. 9556 /// 9557 /// This version can replace From with any result values. To must match the 9558 /// number and types of values returned by From. 9559 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9560 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9561 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9562 9563 // Preserve Debug Info. 9564 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9565 transferDbgValues(SDValue(From, i), To[i]); 9566 9567 // Iterate over just the existing users of From. See the comments in 9568 // the ReplaceAllUsesWith above. 9569 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9570 RAUWUpdateListener Listener(*this, UI, UE); 9571 while (UI != UE) { 9572 SDNode *User = *UI; 9573 9574 // This node is about to morph, remove its old self from the CSE maps. 9575 RemoveNodeFromCSEMaps(User); 9576 9577 // A user can appear in a use list multiple times, and when this happens the 9578 // uses are usually next to each other in the list. To help reduce the 9579 // number of CSE and divergence recomputations, process all the uses of this 9580 // user that we can find this way. 9581 bool To_IsDivergent = false; 9582 do { 9583 SDUse &Use = UI.getUse(); 9584 const SDValue &ToOp = To[Use.getResNo()]; 9585 ++UI; 9586 Use.set(ToOp); 9587 To_IsDivergent |= ToOp->isDivergent(); 9588 } while (UI != UE && *UI == User); 9589 9590 if (To_IsDivergent != From->isDivergent()) 9591 updateDivergence(User); 9592 9593 // Now that we have modified User, add it back to the CSE maps. If it 9594 // already exists there, recursively merge the results together. 9595 AddModifiedNodeToCSEMaps(User); 9596 } 9597 9598 // If we just RAUW'd the root, take note. 9599 if (From == getRoot().getNode()) 9600 setRoot(SDValue(To[getRoot().getResNo()])); 9601 } 9602 9603 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 9604 /// uses of other values produced by From.getNode() alone. The Deleted 9605 /// vector is handled the same way as for ReplaceAllUsesWith. 9606 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 9607 // Handle the really simple, really trivial case efficiently. 9608 if (From == To) return; 9609 9610 // Handle the simple, trivial, case efficiently. 9611 if (From.getNode()->getNumValues() == 1) { 9612 ReplaceAllUsesWith(From, To); 9613 return; 9614 } 9615 9616 // Preserve Debug Info. 9617 transferDbgValues(From, To); 9618 9619 // Iterate over just the existing users of From. See the comments in 9620 // the ReplaceAllUsesWith above. 9621 SDNode::use_iterator UI = From.getNode()->use_begin(), 9622 UE = From.getNode()->use_end(); 9623 RAUWUpdateListener Listener(*this, UI, UE); 9624 while (UI != UE) { 9625 SDNode *User = *UI; 9626 bool UserRemovedFromCSEMaps = false; 9627 9628 // A user can appear in a use list multiple times, and when this 9629 // happens the uses are usually next to each other in the list. 9630 // To help reduce the number of CSE recomputations, process all 9631 // the uses of this user that we can find this way. 9632 do { 9633 SDUse &Use = UI.getUse(); 9634 9635 // Skip uses of different values from the same node. 9636 if (Use.getResNo() != From.getResNo()) { 9637 ++UI; 9638 continue; 9639 } 9640 9641 // If this node hasn't been modified yet, it's still in the CSE maps, 9642 // so remove its old self from the CSE maps. 9643 if (!UserRemovedFromCSEMaps) { 9644 RemoveNodeFromCSEMaps(User); 9645 UserRemovedFromCSEMaps = true; 9646 } 9647 9648 ++UI; 9649 Use.set(To); 9650 if (To->isDivergent() != From->isDivergent()) 9651 updateDivergence(User); 9652 } while (UI != UE && *UI == User); 9653 // We are iterating over all uses of the From node, so if a use 9654 // doesn't use the specific value, no changes are made. 9655 if (!UserRemovedFromCSEMaps) 9656 continue; 9657 9658 // Now that we have modified User, add it back to the CSE maps. If it 9659 // already exists there, recursively merge the results together. 9660 AddModifiedNodeToCSEMaps(User); 9661 } 9662 9663 // If we just RAUW'd the root, take note. 9664 if (From == getRoot()) 9665 setRoot(To); 9666 } 9667 9668 namespace { 9669 9670 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 9671 /// to record information about a use. 9672 struct UseMemo { 9673 SDNode *User; 9674 unsigned Index; 9675 SDUse *Use; 9676 }; 9677 9678 /// operator< - Sort Memos by User. 9679 bool operator<(const UseMemo &L, const UseMemo &R) { 9680 return (intptr_t)L.User < (intptr_t)R.User; 9681 } 9682 9683 } // end anonymous namespace 9684 9685 bool SelectionDAG::calculateDivergence(SDNode *N) { 9686 if (TLI->isSDNodeAlwaysUniform(N)) { 9687 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 9688 "Conflicting divergence information!"); 9689 return false; 9690 } 9691 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 9692 return true; 9693 for (auto &Op : N->ops()) { 9694 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 9695 return true; 9696 } 9697 return false; 9698 } 9699 9700 void SelectionDAG::updateDivergence(SDNode *N) { 9701 SmallVector<SDNode *, 16> Worklist(1, N); 9702 do { 9703 N = Worklist.pop_back_val(); 9704 bool IsDivergent = calculateDivergence(N); 9705 if (N->SDNodeBits.IsDivergent != IsDivergent) { 9706 N->SDNodeBits.IsDivergent = IsDivergent; 9707 llvm::append_range(Worklist, N->uses()); 9708 } 9709 } while (!Worklist.empty()); 9710 } 9711 9712 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 9713 DenseMap<SDNode *, unsigned> Degree; 9714 Order.reserve(AllNodes.size()); 9715 for (auto &N : allnodes()) { 9716 unsigned NOps = N.getNumOperands(); 9717 Degree[&N] = NOps; 9718 if (0 == NOps) 9719 Order.push_back(&N); 9720 } 9721 for (size_t I = 0; I != Order.size(); ++I) { 9722 SDNode *N = Order[I]; 9723 for (auto U : N->uses()) { 9724 unsigned &UnsortedOps = Degree[U]; 9725 if (0 == --UnsortedOps) 9726 Order.push_back(U); 9727 } 9728 } 9729 } 9730 9731 #ifndef NDEBUG 9732 void SelectionDAG::VerifyDAGDivergence() { 9733 std::vector<SDNode *> TopoOrder; 9734 CreateTopologicalOrder(TopoOrder); 9735 for (auto *N : TopoOrder) { 9736 assert(calculateDivergence(N) == N->isDivergent() && 9737 "Divergence bit inconsistency detected"); 9738 } 9739 } 9740 #endif 9741 9742 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 9743 /// uses of other values produced by From.getNode() alone. The same value 9744 /// may appear in both the From and To list. The Deleted vector is 9745 /// handled the same way as for ReplaceAllUsesWith. 9746 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 9747 const SDValue *To, 9748 unsigned Num){ 9749 // Handle the simple, trivial case efficiently. 9750 if (Num == 1) 9751 return ReplaceAllUsesOfValueWith(*From, *To); 9752 9753 transferDbgValues(*From, *To); 9754 9755 // Read up all the uses and make records of them. This helps 9756 // processing new uses that are introduced during the 9757 // replacement process. 9758 SmallVector<UseMemo, 4> Uses; 9759 for (unsigned i = 0; i != Num; ++i) { 9760 unsigned FromResNo = From[i].getResNo(); 9761 SDNode *FromNode = From[i].getNode(); 9762 for (SDNode::use_iterator UI = FromNode->use_begin(), 9763 E = FromNode->use_end(); UI != E; ++UI) { 9764 SDUse &Use = UI.getUse(); 9765 if (Use.getResNo() == FromResNo) { 9766 UseMemo Memo = { *UI, i, &Use }; 9767 Uses.push_back(Memo); 9768 } 9769 } 9770 } 9771 9772 // Sort the uses, so that all the uses from a given User are together. 9773 llvm::sort(Uses); 9774 9775 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 9776 UseIndex != UseIndexEnd; ) { 9777 // We know that this user uses some value of From. If it is the right 9778 // value, update it. 9779 SDNode *User = Uses[UseIndex].User; 9780 9781 // This node is about to morph, remove its old self from the CSE maps. 9782 RemoveNodeFromCSEMaps(User); 9783 9784 // The Uses array is sorted, so all the uses for a given User 9785 // are next to each other in the list. 9786 // To help reduce the number of CSE recomputations, process all 9787 // the uses of this user that we can find this way. 9788 do { 9789 unsigned i = Uses[UseIndex].Index; 9790 SDUse &Use = *Uses[UseIndex].Use; 9791 ++UseIndex; 9792 9793 Use.set(To[i]); 9794 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 9795 9796 // Now that we have modified User, add it back to the CSE maps. If it 9797 // already exists there, recursively merge the results together. 9798 AddModifiedNodeToCSEMaps(User); 9799 } 9800 } 9801 9802 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 9803 /// based on their topological order. It returns the maximum id and a vector 9804 /// of the SDNodes* in assigned order by reference. 9805 unsigned SelectionDAG::AssignTopologicalOrder() { 9806 unsigned DAGSize = 0; 9807 9808 // SortedPos tracks the progress of the algorithm. Nodes before it are 9809 // sorted, nodes after it are unsorted. When the algorithm completes 9810 // it is at the end of the list. 9811 allnodes_iterator SortedPos = allnodes_begin(); 9812 9813 // Visit all the nodes. Move nodes with no operands to the front of 9814 // the list immediately. Annotate nodes that do have operands with their 9815 // operand count. Before we do this, the Node Id fields of the nodes 9816 // may contain arbitrary values. After, the Node Id fields for nodes 9817 // before SortedPos will contain the topological sort index, and the 9818 // Node Id fields for nodes At SortedPos and after will contain the 9819 // count of outstanding operands. 9820 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 9821 SDNode *N = &*I++; 9822 checkForCycles(N, this); 9823 unsigned Degree = N->getNumOperands(); 9824 if (Degree == 0) { 9825 // A node with no uses, add it to the result array immediately. 9826 N->setNodeId(DAGSize++); 9827 allnodes_iterator Q(N); 9828 if (Q != SortedPos) 9829 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 9830 assert(SortedPos != AllNodes.end() && "Overran node list"); 9831 ++SortedPos; 9832 } else { 9833 // Temporarily use the Node Id as scratch space for the degree count. 9834 N->setNodeId(Degree); 9835 } 9836 } 9837 9838 // Visit all the nodes. As we iterate, move nodes into sorted order, 9839 // such that by the time the end is reached all nodes will be sorted. 9840 for (SDNode &Node : allnodes()) { 9841 SDNode *N = &Node; 9842 checkForCycles(N, this); 9843 // N is in sorted position, so all its uses have one less operand 9844 // that needs to be sorted. 9845 for (SDNode *P : N->uses()) { 9846 unsigned Degree = P->getNodeId(); 9847 assert(Degree != 0 && "Invalid node degree"); 9848 --Degree; 9849 if (Degree == 0) { 9850 // All of P's operands are sorted, so P may sorted now. 9851 P->setNodeId(DAGSize++); 9852 if (P->getIterator() != SortedPos) 9853 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9854 assert(SortedPos != AllNodes.end() && "Overran node list"); 9855 ++SortedPos; 9856 } else { 9857 // Update P's outstanding operand count. 9858 P->setNodeId(Degree); 9859 } 9860 } 9861 if (Node.getIterator() == SortedPos) { 9862 #ifndef NDEBUG 9863 allnodes_iterator I(N); 9864 SDNode *S = &*++I; 9865 dbgs() << "Overran sorted position:\n"; 9866 S->dumprFull(this); dbgs() << "\n"; 9867 dbgs() << "Checking if this is due to cycles\n"; 9868 checkForCycles(this, true); 9869 #endif 9870 llvm_unreachable(nullptr); 9871 } 9872 } 9873 9874 assert(SortedPos == AllNodes.end() && 9875 "Topological sort incomplete!"); 9876 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9877 "First node in topological sort is not the entry token!"); 9878 assert(AllNodes.front().getNodeId() == 0 && 9879 "First node in topological sort has non-zero id!"); 9880 assert(AllNodes.front().getNumOperands() == 0 && 9881 "First node in topological sort has operands!"); 9882 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9883 "Last node in topologic sort has unexpected id!"); 9884 assert(AllNodes.back().use_empty() && 9885 "Last node in topologic sort has users!"); 9886 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9887 return DAGSize; 9888 } 9889 9890 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9891 /// value is produced by SD. 9892 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 9893 for (SDNode *SD : DB->getSDNodes()) { 9894 if (!SD) 9895 continue; 9896 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9897 SD->setHasDebugValue(true); 9898 } 9899 DbgInfo->add(DB, isParameter); 9900 } 9901 9902 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 9903 9904 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9905 SDValue NewMemOpChain) { 9906 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9907 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9908 // The new memory operation must have the same position as the old load in 9909 // terms of memory dependency. Create a TokenFactor for the old load and new 9910 // memory operation and update uses of the old load's output chain to use that 9911 // TokenFactor. 9912 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9913 return NewMemOpChain; 9914 9915 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9916 OldChain, NewMemOpChain); 9917 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9918 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9919 return TokenFactor; 9920 } 9921 9922 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9923 SDValue NewMemOp) { 9924 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9925 SDValue OldChain = SDValue(OldLoad, 1); 9926 SDValue NewMemOpChain = NewMemOp.getValue(1); 9927 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9928 } 9929 9930 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9931 Function **OutFunction) { 9932 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9933 9934 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9935 auto *Module = MF->getFunction().getParent(); 9936 auto *Function = Module->getFunction(Symbol); 9937 9938 if (OutFunction != nullptr) 9939 *OutFunction = Function; 9940 9941 if (Function != nullptr) { 9942 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9943 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9944 } 9945 9946 std::string ErrorStr; 9947 raw_string_ostream ErrorFormatter(ErrorStr); 9948 ErrorFormatter << "Undefined external symbol "; 9949 ErrorFormatter << '"' << Symbol << '"'; 9950 report_fatal_error(Twine(ErrorFormatter.str())); 9951 } 9952 9953 //===----------------------------------------------------------------------===// 9954 // SDNode Class 9955 //===----------------------------------------------------------------------===// 9956 9957 bool llvm::isNullConstant(SDValue V) { 9958 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9959 return Const != nullptr && Const->isZero(); 9960 } 9961 9962 bool llvm::isNullFPConstant(SDValue V) { 9963 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9964 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9965 } 9966 9967 bool llvm::isAllOnesConstant(SDValue V) { 9968 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9969 return Const != nullptr && Const->isAllOnes(); 9970 } 9971 9972 bool llvm::isOneConstant(SDValue V) { 9973 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9974 return Const != nullptr && Const->isOne(); 9975 } 9976 9977 SDValue llvm::peekThroughBitcasts(SDValue V) { 9978 while (V.getOpcode() == ISD::BITCAST) 9979 V = V.getOperand(0); 9980 return V; 9981 } 9982 9983 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9984 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9985 V = V.getOperand(0); 9986 return V; 9987 } 9988 9989 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9990 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9991 V = V.getOperand(0); 9992 return V; 9993 } 9994 9995 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9996 if (V.getOpcode() != ISD::XOR) 9997 return false; 9998 V = peekThroughBitcasts(V.getOperand(1)); 9999 unsigned NumBits = V.getScalarValueSizeInBits(); 10000 ConstantSDNode *C = 10001 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10002 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10003 } 10004 10005 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10006 bool AllowTruncation) { 10007 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10008 return CN; 10009 10010 // SplatVectors can truncate their operands. Ignore that case here unless 10011 // AllowTruncation is set. 10012 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10013 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10014 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10015 EVT CVT = CN->getValueType(0); 10016 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10017 if (AllowTruncation || CVT == VecEltVT) 10018 return CN; 10019 } 10020 } 10021 10022 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10023 BitVector UndefElements; 10024 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10025 10026 // BuildVectors can truncate their operands. Ignore that case here unless 10027 // AllowTruncation is set. 10028 if (CN && (UndefElements.none() || AllowUndefs)) { 10029 EVT CVT = CN->getValueType(0); 10030 EVT NSVT = N.getValueType().getScalarType(); 10031 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10032 if (AllowTruncation || (CVT == NSVT)) 10033 return CN; 10034 } 10035 } 10036 10037 return nullptr; 10038 } 10039 10040 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10041 bool AllowUndefs, 10042 bool AllowTruncation) { 10043 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10044 return CN; 10045 10046 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10047 BitVector UndefElements; 10048 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10049 10050 // BuildVectors can truncate their operands. Ignore that case here unless 10051 // AllowTruncation is set. 10052 if (CN && (UndefElements.none() || AllowUndefs)) { 10053 EVT CVT = CN->getValueType(0); 10054 EVT NSVT = N.getValueType().getScalarType(); 10055 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10056 if (AllowTruncation || (CVT == NSVT)) 10057 return CN; 10058 } 10059 } 10060 10061 return nullptr; 10062 } 10063 10064 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10065 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10066 return CN; 10067 10068 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10069 BitVector UndefElements; 10070 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10071 if (CN && (UndefElements.none() || AllowUndefs)) 10072 return CN; 10073 } 10074 10075 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10076 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10077 return CN; 10078 10079 return nullptr; 10080 } 10081 10082 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10083 const APInt &DemandedElts, 10084 bool AllowUndefs) { 10085 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10086 return CN; 10087 10088 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10089 BitVector UndefElements; 10090 ConstantFPSDNode *CN = 10091 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10092 if (CN && (UndefElements.none() || AllowUndefs)) 10093 return CN; 10094 } 10095 10096 return nullptr; 10097 } 10098 10099 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10100 // TODO: may want to use peekThroughBitcast() here. 10101 ConstantSDNode *C = 10102 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10103 return C && C->isZero(); 10104 } 10105 10106 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10107 // TODO: may want to use peekThroughBitcast() here. 10108 unsigned BitWidth = N.getScalarValueSizeInBits(); 10109 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10110 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10111 } 10112 10113 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10114 N = peekThroughBitcasts(N); 10115 unsigned BitWidth = N.getScalarValueSizeInBits(); 10116 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10117 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10118 } 10119 10120 HandleSDNode::~HandleSDNode() { 10121 DropOperands(); 10122 } 10123 10124 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10125 const DebugLoc &DL, 10126 const GlobalValue *GA, EVT VT, 10127 int64_t o, unsigned TF) 10128 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10129 TheGlobal = GA; 10130 } 10131 10132 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10133 EVT VT, unsigned SrcAS, 10134 unsigned DestAS) 10135 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10136 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10137 10138 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10139 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10140 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10141 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10142 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10143 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10144 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10145 10146 // We check here that the size of the memory operand fits within the size of 10147 // the MMO. This is because the MMO might indicate only a possible address 10148 // range instead of specifying the affected memory addresses precisely. 10149 // TODO: Make MachineMemOperands aware of scalable vectors. 10150 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10151 "Size mismatch!"); 10152 } 10153 10154 /// Profile - Gather unique data for the node. 10155 /// 10156 void SDNode::Profile(FoldingSetNodeID &ID) const { 10157 AddNodeIDNode(ID, this); 10158 } 10159 10160 namespace { 10161 10162 struct EVTArray { 10163 std::vector<EVT> VTs; 10164 10165 EVTArray() { 10166 VTs.reserve(MVT::VALUETYPE_SIZE); 10167 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10168 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10169 } 10170 }; 10171 10172 } // end anonymous namespace 10173 10174 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10175 static ManagedStatic<EVTArray> SimpleVTArray; 10176 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10177 10178 /// getValueTypeList - Return a pointer to the specified value type. 10179 /// 10180 const EVT *SDNode::getValueTypeList(EVT VT) { 10181 if (VT.isExtended()) { 10182 sys::SmartScopedLock<true> Lock(*VTMutex); 10183 return &(*EVTs->insert(VT).first); 10184 } 10185 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10186 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10187 } 10188 10189 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10190 /// indicated value. This method ignores uses of other values defined by this 10191 /// operation. 10192 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10193 assert(Value < getNumValues() && "Bad value!"); 10194 10195 // TODO: Only iterate over uses of a given value of the node 10196 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10197 if (UI.getUse().getResNo() == Value) { 10198 if (NUses == 0) 10199 return false; 10200 --NUses; 10201 } 10202 } 10203 10204 // Found exactly the right number of uses? 10205 return NUses == 0; 10206 } 10207 10208 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10209 /// value. This method ignores uses of other values defined by this operation. 10210 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10211 assert(Value < getNumValues() && "Bad value!"); 10212 10213 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10214 if (UI.getUse().getResNo() == Value) 10215 return true; 10216 10217 return false; 10218 } 10219 10220 /// isOnlyUserOf - Return true if this node is the only use of N. 10221 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10222 bool Seen = false; 10223 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 10224 SDNode *User = *I; 10225 if (User == this) 10226 Seen = true; 10227 else 10228 return false; 10229 } 10230 10231 return Seen; 10232 } 10233 10234 /// Return true if the only users of N are contained in Nodes. 10235 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10236 bool Seen = false; 10237 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 10238 SDNode *User = *I; 10239 if (llvm::is_contained(Nodes, User)) 10240 Seen = true; 10241 else 10242 return false; 10243 } 10244 10245 return Seen; 10246 } 10247 10248 /// isOperand - Return true if this node is an operand of N. 10249 bool SDValue::isOperandOf(const SDNode *N) const { 10250 return is_contained(N->op_values(), *this); 10251 } 10252 10253 bool SDNode::isOperandOf(const SDNode *N) const { 10254 return any_of(N->op_values(), 10255 [this](SDValue Op) { return this == Op.getNode(); }); 10256 } 10257 10258 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10259 /// be a chain) reaches the specified operand without crossing any 10260 /// side-effecting instructions on any chain path. In practice, this looks 10261 /// through token factors and non-volatile loads. In order to remain efficient, 10262 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10263 /// 10264 /// Note that we only need to examine chains when we're searching for 10265 /// side-effects; SelectionDAG requires that all side-effects are represented 10266 /// by chains, even if another operand would force a specific ordering. This 10267 /// constraint is necessary to allow transformations like splitting loads. 10268 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10269 unsigned Depth) const { 10270 if (*this == Dest) return true; 10271 10272 // Don't search too deeply, we just want to be able to see through 10273 // TokenFactor's etc. 10274 if (Depth == 0) return false; 10275 10276 // If this is a token factor, all inputs to the TF happen in parallel. 10277 if (getOpcode() == ISD::TokenFactor) { 10278 // First, try a shallow search. 10279 if (is_contained((*this)->ops(), Dest)) { 10280 // We found the chain we want as an operand of this TokenFactor. 10281 // Essentially, we reach the chain without side-effects if we could 10282 // serialize the TokenFactor into a simple chain of operations with 10283 // Dest as the last operation. This is automatically true if the 10284 // chain has one use: there are no other ordering constraints. 10285 // If the chain has more than one use, we give up: some other 10286 // use of Dest might force a side-effect between Dest and the current 10287 // node. 10288 if (Dest.hasOneUse()) 10289 return true; 10290 } 10291 // Next, try a deep search: check whether every operand of the TokenFactor 10292 // reaches Dest. 10293 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10294 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10295 }); 10296 } 10297 10298 // Loads don't have side effects, look through them. 10299 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10300 if (Ld->isUnordered()) 10301 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10302 } 10303 return false; 10304 } 10305 10306 bool SDNode::hasPredecessor(const SDNode *N) const { 10307 SmallPtrSet<const SDNode *, 32> Visited; 10308 SmallVector<const SDNode *, 16> Worklist; 10309 Worklist.push_back(this); 10310 return hasPredecessorHelper(N, Visited, Worklist); 10311 } 10312 10313 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10314 this->Flags.intersectWith(Flags); 10315 } 10316 10317 SDValue 10318 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10319 ArrayRef<ISD::NodeType> CandidateBinOps, 10320 bool AllowPartials) { 10321 // The pattern must end in an extract from index 0. 10322 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10323 !isNullConstant(Extract->getOperand(1))) 10324 return SDValue(); 10325 10326 // Match against one of the candidate binary ops. 10327 SDValue Op = Extract->getOperand(0); 10328 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10329 return Op.getOpcode() == unsigned(BinOp); 10330 })) 10331 return SDValue(); 10332 10333 // Floating-point reductions may require relaxed constraints on the final step 10334 // of the reduction because they may reorder intermediate operations. 10335 unsigned CandidateBinOp = Op.getOpcode(); 10336 if (Op.getValueType().isFloatingPoint()) { 10337 SDNodeFlags Flags = Op->getFlags(); 10338 switch (CandidateBinOp) { 10339 case ISD::FADD: 10340 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10341 return SDValue(); 10342 break; 10343 default: 10344 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10345 } 10346 } 10347 10348 // Matching failed - attempt to see if we did enough stages that a partial 10349 // reduction from a subvector is possible. 10350 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10351 if (!AllowPartials || !Op) 10352 return SDValue(); 10353 EVT OpVT = Op.getValueType(); 10354 EVT OpSVT = OpVT.getScalarType(); 10355 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10356 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10357 return SDValue(); 10358 BinOp = (ISD::NodeType)CandidateBinOp; 10359 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10360 getVectorIdxConstant(0, SDLoc(Op))); 10361 }; 10362 10363 // At each stage, we're looking for something that looks like: 10364 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10365 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10366 // i32 undef, i32 undef, i32 undef, i32 undef> 10367 // %a = binop <8 x i32> %op, %s 10368 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10369 // we expect something like: 10370 // <4,5,6,7,u,u,u,u> 10371 // <2,3,u,u,u,u,u,u> 10372 // <1,u,u,u,u,u,u,u> 10373 // While a partial reduction match would be: 10374 // <2,3,u,u,u,u,u,u> 10375 // <1,u,u,u,u,u,u,u> 10376 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10377 SDValue PrevOp; 10378 for (unsigned i = 0; i < Stages; ++i) { 10379 unsigned MaskEnd = (1 << i); 10380 10381 if (Op.getOpcode() != CandidateBinOp) 10382 return PartialReduction(PrevOp, MaskEnd); 10383 10384 SDValue Op0 = Op.getOperand(0); 10385 SDValue Op1 = Op.getOperand(1); 10386 10387 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10388 if (Shuffle) { 10389 Op = Op1; 10390 } else { 10391 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10392 Op = Op0; 10393 } 10394 10395 // The first operand of the shuffle should be the same as the other operand 10396 // of the binop. 10397 if (!Shuffle || Shuffle->getOperand(0) != Op) 10398 return PartialReduction(PrevOp, MaskEnd); 10399 10400 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10401 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10402 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10403 return PartialReduction(PrevOp, MaskEnd); 10404 10405 PrevOp = Op; 10406 } 10407 10408 // Handle subvector reductions, which tend to appear after the shuffle 10409 // reduction stages. 10410 while (Op.getOpcode() == CandidateBinOp) { 10411 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10412 SDValue Op0 = Op.getOperand(0); 10413 SDValue Op1 = Op.getOperand(1); 10414 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10415 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10416 Op0.getOperand(0) != Op1.getOperand(0)) 10417 break; 10418 SDValue Src = Op0.getOperand(0); 10419 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10420 if (NumSrcElts != (2 * NumElts)) 10421 break; 10422 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10423 Op1.getConstantOperandAPInt(1) == NumElts) && 10424 !(Op1.getConstantOperandAPInt(1) == 0 && 10425 Op0.getConstantOperandAPInt(1) == NumElts)) 10426 break; 10427 Op = Src; 10428 } 10429 10430 BinOp = (ISD::NodeType)CandidateBinOp; 10431 return Op; 10432 } 10433 10434 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10435 assert(N->getNumValues() == 1 && 10436 "Can't unroll a vector with multiple results!"); 10437 10438 EVT VT = N->getValueType(0); 10439 unsigned NE = VT.getVectorNumElements(); 10440 EVT EltVT = VT.getVectorElementType(); 10441 SDLoc dl(N); 10442 10443 SmallVector<SDValue, 8> Scalars; 10444 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10445 10446 // If ResNE is 0, fully unroll the vector op. 10447 if (ResNE == 0) 10448 ResNE = NE; 10449 else if (NE > ResNE) 10450 NE = ResNE; 10451 10452 unsigned i; 10453 for (i= 0; i != NE; ++i) { 10454 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10455 SDValue Operand = N->getOperand(j); 10456 EVT OperandVT = Operand.getValueType(); 10457 if (OperandVT.isVector()) { 10458 // A vector operand; extract a single element. 10459 EVT OperandEltVT = OperandVT.getVectorElementType(); 10460 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10461 Operand, getVectorIdxConstant(i, dl)); 10462 } else { 10463 // A scalar operand; just use it as is. 10464 Operands[j] = Operand; 10465 } 10466 } 10467 10468 switch (N->getOpcode()) { 10469 default: { 10470 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10471 N->getFlags())); 10472 break; 10473 } 10474 case ISD::VSELECT: 10475 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10476 break; 10477 case ISD::SHL: 10478 case ISD::SRA: 10479 case ISD::SRL: 10480 case ISD::ROTL: 10481 case ISD::ROTR: 10482 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10483 getShiftAmountOperand(Operands[0].getValueType(), 10484 Operands[1]))); 10485 break; 10486 case ISD::SIGN_EXTEND_INREG: { 10487 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10488 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10489 Operands[0], 10490 getValueType(ExtVT))); 10491 } 10492 } 10493 } 10494 10495 for (; i < ResNE; ++i) 10496 Scalars.push_back(getUNDEF(EltVT)); 10497 10498 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10499 return getBuildVector(VecVT, dl, Scalars); 10500 } 10501 10502 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10503 SDNode *N, unsigned ResNE) { 10504 unsigned Opcode = N->getOpcode(); 10505 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10506 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10507 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10508 "Expected an overflow opcode"); 10509 10510 EVT ResVT = N->getValueType(0); 10511 EVT OvVT = N->getValueType(1); 10512 EVT ResEltVT = ResVT.getVectorElementType(); 10513 EVT OvEltVT = OvVT.getVectorElementType(); 10514 SDLoc dl(N); 10515 10516 // If ResNE is 0, fully unroll the vector op. 10517 unsigned NE = ResVT.getVectorNumElements(); 10518 if (ResNE == 0) 10519 ResNE = NE; 10520 else if (NE > ResNE) 10521 NE = ResNE; 10522 10523 SmallVector<SDValue, 8> LHSScalars; 10524 SmallVector<SDValue, 8> RHSScalars; 10525 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10526 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10527 10528 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10529 SDVTList VTs = getVTList(ResEltVT, SVT); 10530 SmallVector<SDValue, 8> ResScalars; 10531 SmallVector<SDValue, 8> OvScalars; 10532 for (unsigned i = 0; i < NE; ++i) { 10533 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10534 SDValue Ov = 10535 getSelect(dl, OvEltVT, Res.getValue(1), 10536 getBoolConstant(true, dl, OvEltVT, ResVT), 10537 getConstant(0, dl, OvEltVT)); 10538 10539 ResScalars.push_back(Res); 10540 OvScalars.push_back(Ov); 10541 } 10542 10543 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10544 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10545 10546 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10547 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10548 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10549 getBuildVector(NewOvVT, dl, OvScalars)); 10550 } 10551 10552 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10553 LoadSDNode *Base, 10554 unsigned Bytes, 10555 int Dist) const { 10556 if (LD->isVolatile() || Base->isVolatile()) 10557 return false; 10558 // TODO: probably too restrictive for atomics, revisit 10559 if (!LD->isSimple()) 10560 return false; 10561 if (LD->isIndexed() || Base->isIndexed()) 10562 return false; 10563 if (LD->getChain() != Base->getChain()) 10564 return false; 10565 EVT VT = LD->getValueType(0); 10566 if (VT.getSizeInBits() / 8 != Bytes) 10567 return false; 10568 10569 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10570 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10571 10572 int64_t Offset = 0; 10573 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 10574 return (Dist * Bytes == Offset); 10575 return false; 10576 } 10577 10578 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 10579 /// if it cannot be inferred. 10580 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 10581 // If this is a GlobalAddress + cst, return the alignment. 10582 const GlobalValue *GV = nullptr; 10583 int64_t GVOffset = 0; 10584 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 10585 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 10586 KnownBits Known(PtrWidth); 10587 llvm::computeKnownBits(GV, Known, getDataLayout()); 10588 unsigned AlignBits = Known.countMinTrailingZeros(); 10589 if (AlignBits) 10590 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 10591 } 10592 10593 // If this is a direct reference to a stack slot, use information about the 10594 // stack slot's alignment. 10595 int FrameIdx = INT_MIN; 10596 int64_t FrameOffset = 0; 10597 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 10598 FrameIdx = FI->getIndex(); 10599 } else if (isBaseWithConstantOffset(Ptr) && 10600 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 10601 // Handle FI+Cst 10602 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 10603 FrameOffset = Ptr.getConstantOperandVal(1); 10604 } 10605 10606 if (FrameIdx != INT_MIN) { 10607 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 10608 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 10609 } 10610 10611 return None; 10612 } 10613 10614 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 10615 /// which is split (or expanded) into two not necessarily identical pieces. 10616 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 10617 // Currently all types are split in half. 10618 EVT LoVT, HiVT; 10619 if (!VT.isVector()) 10620 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 10621 else 10622 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 10623 10624 return std::make_pair(LoVT, HiVT); 10625 } 10626 10627 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 10628 /// type, dependent on an enveloping VT that has been split into two identical 10629 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 10630 std::pair<EVT, EVT> 10631 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 10632 bool *HiIsEmpty) const { 10633 EVT EltTp = VT.getVectorElementType(); 10634 // Examples: 10635 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 10636 // custom VL=9 with enveloping VL=8/8 yields 8/1 10637 // custom VL=10 with enveloping VL=8/8 yields 8/2 10638 // etc. 10639 ElementCount VTNumElts = VT.getVectorElementCount(); 10640 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 10641 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 10642 "Mixing fixed width and scalable vectors when enveloping a type"); 10643 EVT LoVT, HiVT; 10644 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 10645 LoVT = EnvVT; 10646 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 10647 *HiIsEmpty = false; 10648 } else { 10649 // Flag that hi type has zero storage size, but return split envelop type 10650 // (this would be easier if vector types with zero elements were allowed). 10651 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 10652 HiVT = EnvVT; 10653 *HiIsEmpty = true; 10654 } 10655 return std::make_pair(LoVT, HiVT); 10656 } 10657 10658 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 10659 /// low/high part. 10660 std::pair<SDValue, SDValue> 10661 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 10662 const EVT &HiVT) { 10663 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 10664 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 10665 "Splitting vector with an invalid mixture of fixed and scalable " 10666 "vector types"); 10667 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 10668 N.getValueType().getVectorMinNumElements() && 10669 "More vector elements requested than available!"); 10670 SDValue Lo, Hi; 10671 Lo = 10672 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 10673 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 10674 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 10675 // IDX with the runtime scaling factor of the result vector type. For 10676 // fixed-width result vectors, that runtime scaling factor is 1. 10677 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 10678 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 10679 return std::make_pair(Lo, Hi); 10680 } 10681 10682 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 10683 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 10684 EVT VT = N.getValueType(); 10685 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 10686 NextPowerOf2(VT.getVectorNumElements())); 10687 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 10688 getVectorIdxConstant(0, DL)); 10689 } 10690 10691 void SelectionDAG::ExtractVectorElements(SDValue Op, 10692 SmallVectorImpl<SDValue> &Args, 10693 unsigned Start, unsigned Count, 10694 EVT EltVT) { 10695 EVT VT = Op.getValueType(); 10696 if (Count == 0) 10697 Count = VT.getVectorNumElements(); 10698 if (EltVT == EVT()) 10699 EltVT = VT.getVectorElementType(); 10700 SDLoc SL(Op); 10701 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 10702 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 10703 getVectorIdxConstant(i, SL))); 10704 } 10705 } 10706 10707 // getAddressSpace - Return the address space this GlobalAddress belongs to. 10708 unsigned GlobalAddressSDNode::getAddressSpace() const { 10709 return getGlobal()->getType()->getAddressSpace(); 10710 } 10711 10712 Type *ConstantPoolSDNode::getType() const { 10713 if (isMachineConstantPoolEntry()) 10714 return Val.MachineCPVal->getType(); 10715 return Val.ConstVal->getType(); 10716 } 10717 10718 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 10719 unsigned &SplatBitSize, 10720 bool &HasAnyUndefs, 10721 unsigned MinSplatBits, 10722 bool IsBigEndian) const { 10723 EVT VT = getValueType(0); 10724 assert(VT.isVector() && "Expected a vector type"); 10725 unsigned VecWidth = VT.getSizeInBits(); 10726 if (MinSplatBits > VecWidth) 10727 return false; 10728 10729 // FIXME: The widths are based on this node's type, but build vectors can 10730 // truncate their operands. 10731 SplatValue = APInt(VecWidth, 0); 10732 SplatUndef = APInt(VecWidth, 0); 10733 10734 // Get the bits. Bits with undefined values (when the corresponding element 10735 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 10736 // in SplatValue. If any of the values are not constant, give up and return 10737 // false. 10738 unsigned int NumOps = getNumOperands(); 10739 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 10740 unsigned EltWidth = VT.getScalarSizeInBits(); 10741 10742 for (unsigned j = 0; j < NumOps; ++j) { 10743 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 10744 SDValue OpVal = getOperand(i); 10745 unsigned BitPos = j * EltWidth; 10746 10747 if (OpVal.isUndef()) 10748 SplatUndef.setBits(BitPos, BitPos + EltWidth); 10749 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 10750 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 10751 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 10752 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 10753 else 10754 return false; 10755 } 10756 10757 // The build_vector is all constants or undefs. Find the smallest element 10758 // size that splats the vector. 10759 HasAnyUndefs = (SplatUndef != 0); 10760 10761 // FIXME: This does not work for vectors with elements less than 8 bits. 10762 while (VecWidth > 8) { 10763 unsigned HalfSize = VecWidth / 2; 10764 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 10765 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 10766 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 10767 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 10768 10769 // If the two halves do not match (ignoring undef bits), stop here. 10770 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 10771 MinSplatBits > HalfSize) 10772 break; 10773 10774 SplatValue = HighValue | LowValue; 10775 SplatUndef = HighUndef & LowUndef; 10776 10777 VecWidth = HalfSize; 10778 } 10779 10780 SplatBitSize = VecWidth; 10781 return true; 10782 } 10783 10784 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 10785 BitVector *UndefElements) const { 10786 unsigned NumOps = getNumOperands(); 10787 if (UndefElements) { 10788 UndefElements->clear(); 10789 UndefElements->resize(NumOps); 10790 } 10791 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10792 if (!DemandedElts) 10793 return SDValue(); 10794 SDValue Splatted; 10795 for (unsigned i = 0; i != NumOps; ++i) { 10796 if (!DemandedElts[i]) 10797 continue; 10798 SDValue Op = getOperand(i); 10799 if (Op.isUndef()) { 10800 if (UndefElements) 10801 (*UndefElements)[i] = true; 10802 } else if (!Splatted) { 10803 Splatted = Op; 10804 } else if (Splatted != Op) { 10805 return SDValue(); 10806 } 10807 } 10808 10809 if (!Splatted) { 10810 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 10811 assert(getOperand(FirstDemandedIdx).isUndef() && 10812 "Can only have a splat without a constant for all undefs."); 10813 return getOperand(FirstDemandedIdx); 10814 } 10815 10816 return Splatted; 10817 } 10818 10819 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 10820 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10821 return getSplatValue(DemandedElts, UndefElements); 10822 } 10823 10824 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 10825 SmallVectorImpl<SDValue> &Sequence, 10826 BitVector *UndefElements) const { 10827 unsigned NumOps = getNumOperands(); 10828 Sequence.clear(); 10829 if (UndefElements) { 10830 UndefElements->clear(); 10831 UndefElements->resize(NumOps); 10832 } 10833 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10834 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10835 return false; 10836 10837 // Set the undefs even if we don't find a sequence (like getSplatValue). 10838 if (UndefElements) 10839 for (unsigned I = 0; I != NumOps; ++I) 10840 if (DemandedElts[I] && getOperand(I).isUndef()) 10841 (*UndefElements)[I] = true; 10842 10843 // Iteratively widen the sequence length looking for repetitions. 10844 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10845 Sequence.append(SeqLen, SDValue()); 10846 for (unsigned I = 0; I != NumOps; ++I) { 10847 if (!DemandedElts[I]) 10848 continue; 10849 SDValue &SeqOp = Sequence[I % SeqLen]; 10850 SDValue Op = getOperand(I); 10851 if (Op.isUndef()) { 10852 if (!SeqOp) 10853 SeqOp = Op; 10854 continue; 10855 } 10856 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10857 Sequence.clear(); 10858 break; 10859 } 10860 SeqOp = Op; 10861 } 10862 if (!Sequence.empty()) 10863 return true; 10864 } 10865 10866 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10867 return false; 10868 } 10869 10870 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10871 BitVector *UndefElements) const { 10872 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10873 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10874 } 10875 10876 ConstantSDNode * 10877 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10878 BitVector *UndefElements) const { 10879 return dyn_cast_or_null<ConstantSDNode>( 10880 getSplatValue(DemandedElts, UndefElements)); 10881 } 10882 10883 ConstantSDNode * 10884 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10885 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10886 } 10887 10888 ConstantFPSDNode * 10889 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10890 BitVector *UndefElements) const { 10891 return dyn_cast_or_null<ConstantFPSDNode>( 10892 getSplatValue(DemandedElts, UndefElements)); 10893 } 10894 10895 ConstantFPSDNode * 10896 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10897 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10898 } 10899 10900 int32_t 10901 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10902 uint32_t BitWidth) const { 10903 if (ConstantFPSDNode *CN = 10904 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10905 bool IsExact; 10906 APSInt IntVal(BitWidth); 10907 const APFloat &APF = CN->getValueAPF(); 10908 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10909 APFloat::opOK || 10910 !IsExact) 10911 return -1; 10912 10913 return IntVal.exactLogBase2(); 10914 } 10915 return -1; 10916 } 10917 10918 bool BuildVectorSDNode::isConstant() const { 10919 for (const SDValue &Op : op_values()) { 10920 unsigned Opc = Op.getOpcode(); 10921 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 10922 return false; 10923 } 10924 return true; 10925 } 10926 10927 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 10928 // Find the first non-undef value in the shuffle mask. 10929 unsigned i, e; 10930 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 10931 /* search */; 10932 10933 // If all elements are undefined, this shuffle can be considered a splat 10934 // (although it should eventually get simplified away completely). 10935 if (i == e) 10936 return true; 10937 10938 // Make sure all remaining elements are either undef or the same as the first 10939 // non-undef value. 10940 for (int Idx = Mask[i]; i != e; ++i) 10941 if (Mask[i] >= 0 && Mask[i] != Idx) 10942 return false; 10943 return true; 10944 } 10945 10946 // Returns the SDNode if it is a constant integer BuildVector 10947 // or constant integer. 10948 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 10949 if (isa<ConstantSDNode>(N)) 10950 return N.getNode(); 10951 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 10952 return N.getNode(); 10953 // Treat a GlobalAddress supporting constant offset folding as a 10954 // constant integer. 10955 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 10956 if (GA->getOpcode() == ISD::GlobalAddress && 10957 TLI->isOffsetFoldingLegal(GA)) 10958 return GA; 10959 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 10960 isa<ConstantSDNode>(N.getOperand(0))) 10961 return N.getNode(); 10962 return nullptr; 10963 } 10964 10965 // Returns the SDNode if it is a constant float BuildVector 10966 // or constant float. 10967 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 10968 if (isa<ConstantFPSDNode>(N)) 10969 return N.getNode(); 10970 10971 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 10972 return N.getNode(); 10973 10974 return nullptr; 10975 } 10976 10977 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 10978 assert(!Node->OperandList && "Node already has operands"); 10979 assert(SDNode::getMaxNumOperands() >= Vals.size() && 10980 "too many operands to fit into SDNode"); 10981 SDUse *Ops = OperandRecycler.allocate( 10982 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 10983 10984 bool IsDivergent = false; 10985 for (unsigned I = 0; I != Vals.size(); ++I) { 10986 Ops[I].setUser(Node); 10987 Ops[I].setInitial(Vals[I]); 10988 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 10989 IsDivergent |= Ops[I].getNode()->isDivergent(); 10990 } 10991 Node->NumOperands = Vals.size(); 10992 Node->OperandList = Ops; 10993 if (!TLI->isSDNodeAlwaysUniform(Node)) { 10994 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 10995 Node->SDNodeBits.IsDivergent = IsDivergent; 10996 } 10997 checkForCycles(Node); 10998 } 10999 11000 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11001 SmallVectorImpl<SDValue> &Vals) { 11002 size_t Limit = SDNode::getMaxNumOperands(); 11003 while (Vals.size() > Limit) { 11004 unsigned SliceIdx = Vals.size() - Limit; 11005 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11006 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11007 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11008 Vals.emplace_back(NewTF); 11009 } 11010 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11011 } 11012 11013 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11014 EVT VT, SDNodeFlags Flags) { 11015 switch (Opcode) { 11016 default: 11017 return SDValue(); 11018 case ISD::ADD: 11019 case ISD::OR: 11020 case ISD::XOR: 11021 case ISD::UMAX: 11022 return getConstant(0, DL, VT); 11023 case ISD::MUL: 11024 return getConstant(1, DL, VT); 11025 case ISD::AND: 11026 case ISD::UMIN: 11027 return getAllOnesConstant(DL, VT); 11028 case ISD::SMAX: 11029 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11030 case ISD::SMIN: 11031 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11032 case ISD::FADD: 11033 return getConstantFP(-0.0, DL, VT); 11034 case ISD::FMUL: 11035 return getConstantFP(1.0, DL, VT); 11036 case ISD::FMINNUM: 11037 case ISD::FMAXNUM: { 11038 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11039 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11040 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11041 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11042 APFloat::getLargest(Semantics); 11043 if (Opcode == ISD::FMAXNUM) 11044 NeutralAF.changeSign(); 11045 11046 return getConstantFP(NeutralAF, DL, VT); 11047 } 11048 } 11049 } 11050 11051 #ifndef NDEBUG 11052 static void checkForCyclesHelper(const SDNode *N, 11053 SmallPtrSetImpl<const SDNode*> &Visited, 11054 SmallPtrSetImpl<const SDNode*> &Checked, 11055 const llvm::SelectionDAG *DAG) { 11056 // If this node has already been checked, don't check it again. 11057 if (Checked.count(N)) 11058 return; 11059 11060 // If a node has already been visited on this depth-first walk, reject it as 11061 // a cycle. 11062 if (!Visited.insert(N).second) { 11063 errs() << "Detected cycle in SelectionDAG\n"; 11064 dbgs() << "Offending node:\n"; 11065 N->dumprFull(DAG); dbgs() << "\n"; 11066 abort(); 11067 } 11068 11069 for (const SDValue &Op : N->op_values()) 11070 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11071 11072 Checked.insert(N); 11073 Visited.erase(N); 11074 } 11075 #endif 11076 11077 void llvm::checkForCycles(const llvm::SDNode *N, 11078 const llvm::SelectionDAG *DAG, 11079 bool force) { 11080 #ifndef NDEBUG 11081 bool check = force; 11082 #ifdef EXPENSIVE_CHECKS 11083 check = true; 11084 #endif // EXPENSIVE_CHECKS 11085 if (check) { 11086 assert(N && "Checking nonexistent SDNode"); 11087 SmallPtrSet<const SDNode*, 32> visited; 11088 SmallPtrSet<const SDNode*, 32> checked; 11089 checkForCyclesHelper(N, visited, checked, DAG); 11090 } 11091 #endif // !NDEBUG 11092 } 11093 11094 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11095 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11096 } 11097