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.isAllOnesValue(); 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.isNullValue(); 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 /// The operand position of the vector mask. 416 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 417 switch (Opcode) { 418 default: 419 return None; 420 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...) \ 421 case ISD::SDOPC: \ 422 return MASKPOS; 423 #include "llvm/IR/VPIntrinsics.def" 424 } 425 } 426 427 /// The operand position of the explicit vector length parameter. 428 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 429 switch (Opcode) { 430 default: 431 return None; 432 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 433 case ISD::SDOPC: \ 434 return EVLPOS; 435 #include "llvm/IR/VPIntrinsics.def" 436 } 437 } 438 439 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 440 switch (ExtType) { 441 case ISD::EXTLOAD: 442 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 443 case ISD::SEXTLOAD: 444 return ISD::SIGN_EXTEND; 445 case ISD::ZEXTLOAD: 446 return ISD::ZERO_EXTEND; 447 default: 448 break; 449 } 450 451 llvm_unreachable("Invalid LoadExtType"); 452 } 453 454 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 455 // To perform this operation, we just need to swap the L and G bits of the 456 // operation. 457 unsigned OldL = (Operation >> 2) & 1; 458 unsigned OldG = (Operation >> 1) & 1; 459 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 460 (OldL << 1) | // New G bit 461 (OldG << 2)); // New L bit. 462 } 463 464 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 465 unsigned Operation = Op; 466 if (isIntegerLike) 467 Operation ^= 7; // Flip L, G, E bits, but not U. 468 else 469 Operation ^= 15; // Flip all of the condition bits. 470 471 if (Operation > ISD::SETTRUE2) 472 Operation &= ~8; // Don't let N and U bits get set. 473 474 return ISD::CondCode(Operation); 475 } 476 477 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 478 return getSetCCInverseImpl(Op, Type.isInteger()); 479 } 480 481 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 482 bool isIntegerLike) { 483 return getSetCCInverseImpl(Op, isIntegerLike); 484 } 485 486 /// For an integer comparison, return 1 if the comparison is a signed operation 487 /// and 2 if the result is an unsigned comparison. Return zero if the operation 488 /// does not depend on the sign of the input (setne and seteq). 489 static int isSignedOp(ISD::CondCode Opcode) { 490 switch (Opcode) { 491 default: llvm_unreachable("Illegal integer setcc operation!"); 492 case ISD::SETEQ: 493 case ISD::SETNE: return 0; 494 case ISD::SETLT: 495 case ISD::SETLE: 496 case ISD::SETGT: 497 case ISD::SETGE: return 1; 498 case ISD::SETULT: 499 case ISD::SETULE: 500 case ISD::SETUGT: 501 case ISD::SETUGE: return 2; 502 } 503 } 504 505 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 506 EVT Type) { 507 bool IsInteger = Type.isInteger(); 508 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 509 // Cannot fold a signed integer setcc with an unsigned integer setcc. 510 return ISD::SETCC_INVALID; 511 512 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 513 514 // If the N and U bits get set, then the resultant comparison DOES suddenly 515 // care about orderedness, and it is true when ordered. 516 if (Op > ISD::SETTRUE2) 517 Op &= ~16; // Clear the U bit if the N bit is set. 518 519 // Canonicalize illegal integer setcc's. 520 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 521 Op = ISD::SETNE; 522 523 return ISD::CondCode(Op); 524 } 525 526 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 527 EVT Type) { 528 bool IsInteger = Type.isInteger(); 529 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 530 // Cannot fold a signed setcc with an unsigned setcc. 531 return ISD::SETCC_INVALID; 532 533 // Combine all of the condition bits. 534 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 535 536 // Canonicalize illegal integer setcc's. 537 if (IsInteger) { 538 switch (Result) { 539 default: break; 540 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 541 case ISD::SETOEQ: // SETEQ & SETU[LG]E 542 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 543 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 544 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 545 } 546 } 547 548 return Result; 549 } 550 551 //===----------------------------------------------------------------------===// 552 // SDNode Profile Support 553 //===----------------------------------------------------------------------===// 554 555 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 556 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 557 ID.AddInteger(OpC); 558 } 559 560 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 561 /// solely with their pointer. 562 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 563 ID.AddPointer(VTList.VTs); 564 } 565 566 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 567 static void AddNodeIDOperands(FoldingSetNodeID &ID, 568 ArrayRef<SDValue> Ops) { 569 for (auto& Op : Ops) { 570 ID.AddPointer(Op.getNode()); 571 ID.AddInteger(Op.getResNo()); 572 } 573 } 574 575 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 576 static void AddNodeIDOperands(FoldingSetNodeID &ID, 577 ArrayRef<SDUse> Ops) { 578 for (auto& Op : Ops) { 579 ID.AddPointer(Op.getNode()); 580 ID.AddInteger(Op.getResNo()); 581 } 582 } 583 584 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 585 SDVTList VTList, ArrayRef<SDValue> OpList) { 586 AddNodeIDOpcode(ID, OpC); 587 AddNodeIDValueTypes(ID, VTList); 588 AddNodeIDOperands(ID, OpList); 589 } 590 591 /// If this is an SDNode with special info, add this info to the NodeID data. 592 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 593 switch (N->getOpcode()) { 594 case ISD::TargetExternalSymbol: 595 case ISD::ExternalSymbol: 596 case ISD::MCSymbol: 597 llvm_unreachable("Should only be used on nodes with operands"); 598 default: break; // Normal nodes don't need extra info. 599 case ISD::TargetConstant: 600 case ISD::Constant: { 601 const ConstantSDNode *C = cast<ConstantSDNode>(N); 602 ID.AddPointer(C->getConstantIntValue()); 603 ID.AddBoolean(C->isOpaque()); 604 break; 605 } 606 case ISD::TargetConstantFP: 607 case ISD::ConstantFP: 608 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 609 break; 610 case ISD::TargetGlobalAddress: 611 case ISD::GlobalAddress: 612 case ISD::TargetGlobalTLSAddress: 613 case ISD::GlobalTLSAddress: { 614 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 615 ID.AddPointer(GA->getGlobal()); 616 ID.AddInteger(GA->getOffset()); 617 ID.AddInteger(GA->getTargetFlags()); 618 break; 619 } 620 case ISD::BasicBlock: 621 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 622 break; 623 case ISD::Register: 624 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 625 break; 626 case ISD::RegisterMask: 627 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 628 break; 629 case ISD::SRCVALUE: 630 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 631 break; 632 case ISD::FrameIndex: 633 case ISD::TargetFrameIndex: 634 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 635 break; 636 case ISD::LIFETIME_START: 637 case ISD::LIFETIME_END: 638 if (cast<LifetimeSDNode>(N)->hasOffset()) { 639 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 640 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 641 } 642 break; 643 case ISD::PSEUDO_PROBE: 644 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 645 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 646 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 647 break; 648 case ISD::JumpTable: 649 case ISD::TargetJumpTable: 650 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 651 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 652 break; 653 case ISD::ConstantPool: 654 case ISD::TargetConstantPool: { 655 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 656 ID.AddInteger(CP->getAlign().value()); 657 ID.AddInteger(CP->getOffset()); 658 if (CP->isMachineConstantPoolEntry()) 659 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 660 else 661 ID.AddPointer(CP->getConstVal()); 662 ID.AddInteger(CP->getTargetFlags()); 663 break; 664 } 665 case ISD::TargetIndex: { 666 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 667 ID.AddInteger(TI->getIndex()); 668 ID.AddInteger(TI->getOffset()); 669 ID.AddInteger(TI->getTargetFlags()); 670 break; 671 } 672 case ISD::LOAD: { 673 const LoadSDNode *LD = cast<LoadSDNode>(N); 674 ID.AddInteger(LD->getMemoryVT().getRawBits()); 675 ID.AddInteger(LD->getRawSubclassData()); 676 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 677 break; 678 } 679 case ISD::STORE: { 680 const StoreSDNode *ST = cast<StoreSDNode>(N); 681 ID.AddInteger(ST->getMemoryVT().getRawBits()); 682 ID.AddInteger(ST->getRawSubclassData()); 683 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 684 break; 685 } 686 case ISD::VP_LOAD: { 687 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 688 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 689 ID.AddInteger(ELD->getRawSubclassData()); 690 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 691 break; 692 } 693 case ISD::VP_STORE: { 694 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 695 ID.AddInteger(EST->getMemoryVT().getRawBits()); 696 ID.AddInteger(EST->getRawSubclassData()); 697 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 698 break; 699 } 700 case ISD::VP_GATHER: { 701 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 702 ID.AddInteger(EG->getMemoryVT().getRawBits()); 703 ID.AddInteger(EG->getRawSubclassData()); 704 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 705 break; 706 } 707 case ISD::VP_SCATTER: { 708 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 709 ID.AddInteger(ES->getMemoryVT().getRawBits()); 710 ID.AddInteger(ES->getRawSubclassData()); 711 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 712 break; 713 } 714 case ISD::MLOAD: { 715 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 716 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 717 ID.AddInteger(MLD->getRawSubclassData()); 718 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 719 break; 720 } 721 case ISD::MSTORE: { 722 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 723 ID.AddInteger(MST->getMemoryVT().getRawBits()); 724 ID.AddInteger(MST->getRawSubclassData()); 725 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 726 break; 727 } 728 case ISD::MGATHER: { 729 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 730 ID.AddInteger(MG->getMemoryVT().getRawBits()); 731 ID.AddInteger(MG->getRawSubclassData()); 732 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 733 break; 734 } 735 case ISD::MSCATTER: { 736 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 737 ID.AddInteger(MS->getMemoryVT().getRawBits()); 738 ID.AddInteger(MS->getRawSubclassData()); 739 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 740 break; 741 } 742 case ISD::ATOMIC_CMP_SWAP: 743 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 744 case ISD::ATOMIC_SWAP: 745 case ISD::ATOMIC_LOAD_ADD: 746 case ISD::ATOMIC_LOAD_SUB: 747 case ISD::ATOMIC_LOAD_AND: 748 case ISD::ATOMIC_LOAD_CLR: 749 case ISD::ATOMIC_LOAD_OR: 750 case ISD::ATOMIC_LOAD_XOR: 751 case ISD::ATOMIC_LOAD_NAND: 752 case ISD::ATOMIC_LOAD_MIN: 753 case ISD::ATOMIC_LOAD_MAX: 754 case ISD::ATOMIC_LOAD_UMIN: 755 case ISD::ATOMIC_LOAD_UMAX: 756 case ISD::ATOMIC_LOAD: 757 case ISD::ATOMIC_STORE: { 758 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 759 ID.AddInteger(AT->getMemoryVT().getRawBits()); 760 ID.AddInteger(AT->getRawSubclassData()); 761 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 762 break; 763 } 764 case ISD::PREFETCH: { 765 const MemSDNode *PF = cast<MemSDNode>(N); 766 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 767 break; 768 } 769 case ISD::VECTOR_SHUFFLE: { 770 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 771 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 772 i != e; ++i) 773 ID.AddInteger(SVN->getMaskElt(i)); 774 break; 775 } 776 case ISD::TargetBlockAddress: 777 case ISD::BlockAddress: { 778 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 779 ID.AddPointer(BA->getBlockAddress()); 780 ID.AddInteger(BA->getOffset()); 781 ID.AddInteger(BA->getTargetFlags()); 782 break; 783 } 784 } // end switch (N->getOpcode()) 785 786 // Target specific memory nodes could also have address spaces to check. 787 if (N->isTargetMemoryOpcode()) 788 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 789 } 790 791 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 792 /// data. 793 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 794 AddNodeIDOpcode(ID, N->getOpcode()); 795 // Add the return value info. 796 AddNodeIDValueTypes(ID, N->getVTList()); 797 // Add the operand info. 798 AddNodeIDOperands(ID, N->ops()); 799 800 // Handle SDNode leafs with special info. 801 AddNodeIDCustom(ID, N); 802 } 803 804 //===----------------------------------------------------------------------===// 805 // SelectionDAG Class 806 //===----------------------------------------------------------------------===// 807 808 /// doNotCSE - Return true if CSE should not be performed for this node. 809 static bool doNotCSE(SDNode *N) { 810 if (N->getValueType(0) == MVT::Glue) 811 return true; // Never CSE anything that produces a flag. 812 813 switch (N->getOpcode()) { 814 default: break; 815 case ISD::HANDLENODE: 816 case ISD::EH_LABEL: 817 return true; // Never CSE these nodes. 818 } 819 820 // Check that remaining values produced are not flags. 821 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 822 if (N->getValueType(i) == MVT::Glue) 823 return true; // Never CSE anything that produces a flag. 824 825 return false; 826 } 827 828 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 829 /// SelectionDAG. 830 void SelectionDAG::RemoveDeadNodes() { 831 // Create a dummy node (which is not added to allnodes), that adds a reference 832 // to the root node, preventing it from being deleted. 833 HandleSDNode Dummy(getRoot()); 834 835 SmallVector<SDNode*, 128> DeadNodes; 836 837 // Add all obviously-dead nodes to the DeadNodes worklist. 838 for (SDNode &Node : allnodes()) 839 if (Node.use_empty()) 840 DeadNodes.push_back(&Node); 841 842 RemoveDeadNodes(DeadNodes); 843 844 // If the root changed (e.g. it was a dead load, update the root). 845 setRoot(Dummy.getValue()); 846 } 847 848 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 849 /// given list, and any nodes that become unreachable as a result. 850 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 851 852 // Process the worklist, deleting the nodes and adding their uses to the 853 // worklist. 854 while (!DeadNodes.empty()) { 855 SDNode *N = DeadNodes.pop_back_val(); 856 // Skip to next node if we've already managed to delete the node. This could 857 // happen if replacing a node causes a node previously added to the node to 858 // be deleted. 859 if (N->getOpcode() == ISD::DELETED_NODE) 860 continue; 861 862 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 863 DUL->NodeDeleted(N, nullptr); 864 865 // Take the node out of the appropriate CSE map. 866 RemoveNodeFromCSEMaps(N); 867 868 // Next, brutally remove the operand list. This is safe to do, as there are 869 // no cycles in the graph. 870 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 871 SDUse &Use = *I++; 872 SDNode *Operand = Use.getNode(); 873 Use.set(SDValue()); 874 875 // Now that we removed this operand, see if there are no uses of it left. 876 if (Operand->use_empty()) 877 DeadNodes.push_back(Operand); 878 } 879 880 DeallocateNode(N); 881 } 882 } 883 884 void SelectionDAG::RemoveDeadNode(SDNode *N){ 885 SmallVector<SDNode*, 16> DeadNodes(1, N); 886 887 // Create a dummy node that adds a reference to the root node, preventing 888 // it from being deleted. (This matters if the root is an operand of the 889 // dead node.) 890 HandleSDNode Dummy(getRoot()); 891 892 RemoveDeadNodes(DeadNodes); 893 } 894 895 void SelectionDAG::DeleteNode(SDNode *N) { 896 // First take this out of the appropriate CSE map. 897 RemoveNodeFromCSEMaps(N); 898 899 // Finally, remove uses due to operands of this node, remove from the 900 // AllNodes list, and delete the node. 901 DeleteNodeNotInCSEMaps(N); 902 } 903 904 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 905 assert(N->getIterator() != AllNodes.begin() && 906 "Cannot delete the entry node!"); 907 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 908 909 // Drop all of the operands and decrement used node's use counts. 910 N->DropOperands(); 911 912 DeallocateNode(N); 913 } 914 915 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 916 assert(!(V->isVariadic() && isParameter)); 917 if (isParameter) 918 ByvalParmDbgValues.push_back(V); 919 else 920 DbgValues.push_back(V); 921 for (const SDNode *Node : V->getSDNodes()) 922 if (Node) 923 DbgValMap[Node].push_back(V); 924 } 925 926 void SDDbgInfo::erase(const SDNode *Node) { 927 DbgValMapType::iterator I = DbgValMap.find(Node); 928 if (I == DbgValMap.end()) 929 return; 930 for (auto &Val: I->second) 931 Val->setIsInvalidated(); 932 DbgValMap.erase(I); 933 } 934 935 void SelectionDAG::DeallocateNode(SDNode *N) { 936 // If we have operands, deallocate them. 937 removeOperands(N); 938 939 NodeAllocator.Deallocate(AllNodes.remove(N)); 940 941 // Set the opcode to DELETED_NODE to help catch bugs when node 942 // memory is reallocated. 943 // FIXME: There are places in SDag that have grown a dependency on the opcode 944 // value in the released node. 945 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 946 N->NodeType = ISD::DELETED_NODE; 947 948 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 949 // them and forget about that node. 950 DbgInfo->erase(N); 951 } 952 953 #ifndef NDEBUG 954 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 955 static void VerifySDNode(SDNode *N) { 956 switch (N->getOpcode()) { 957 default: 958 break; 959 case ISD::BUILD_PAIR: { 960 EVT VT = N->getValueType(0); 961 assert(N->getNumValues() == 1 && "Too many results!"); 962 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 963 "Wrong return type!"); 964 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 965 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 966 "Mismatched operand types!"); 967 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 968 "Wrong operand type!"); 969 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 970 "Wrong return type size"); 971 break; 972 } 973 case ISD::BUILD_VECTOR: { 974 assert(N->getNumValues() == 1 && "Too many results!"); 975 assert(N->getValueType(0).isVector() && "Wrong return type!"); 976 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 977 "Wrong number of operands!"); 978 EVT EltVT = N->getValueType(0).getVectorElementType(); 979 for (const SDUse &Op : N->ops()) { 980 assert((Op.getValueType() == EltVT || 981 (EltVT.isInteger() && Op.getValueType().isInteger() && 982 EltVT.bitsLE(Op.getValueType()))) && 983 "Wrong operand type!"); 984 assert(Op.getValueType() == N->getOperand(0).getValueType() && 985 "Operands must all have the same type"); 986 } 987 break; 988 } 989 } 990 } 991 #endif // NDEBUG 992 993 /// Insert a newly allocated node into the DAG. 994 /// 995 /// Handles insertion into the all nodes list and CSE map, as well as 996 /// verification and other common operations when a new node is allocated. 997 void SelectionDAG::InsertNode(SDNode *N) { 998 AllNodes.push_back(N); 999 #ifndef NDEBUG 1000 N->PersistentId = NextPersistentId++; 1001 VerifySDNode(N); 1002 #endif 1003 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1004 DUL->NodeInserted(N); 1005 } 1006 1007 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1008 /// correspond to it. This is useful when we're about to delete or repurpose 1009 /// the node. We don't want future request for structurally identical nodes 1010 /// to return N anymore. 1011 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1012 bool Erased = false; 1013 switch (N->getOpcode()) { 1014 case ISD::HANDLENODE: return false; // noop. 1015 case ISD::CONDCODE: 1016 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1017 "Cond code doesn't exist!"); 1018 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1019 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1020 break; 1021 case ISD::ExternalSymbol: 1022 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1023 break; 1024 case ISD::TargetExternalSymbol: { 1025 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1026 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1027 ESN->getSymbol(), ESN->getTargetFlags())); 1028 break; 1029 } 1030 case ISD::MCSymbol: { 1031 auto *MCSN = cast<MCSymbolSDNode>(N); 1032 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1033 break; 1034 } 1035 case ISD::VALUETYPE: { 1036 EVT VT = cast<VTSDNode>(N)->getVT(); 1037 if (VT.isExtended()) { 1038 Erased = ExtendedValueTypeNodes.erase(VT); 1039 } else { 1040 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1041 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1042 } 1043 break; 1044 } 1045 default: 1046 // Remove it from the CSE Map. 1047 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1048 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1049 Erased = CSEMap.RemoveNode(N); 1050 break; 1051 } 1052 #ifndef NDEBUG 1053 // Verify that the node was actually in one of the CSE maps, unless it has a 1054 // flag result (which cannot be CSE'd) or is one of the special cases that are 1055 // not subject to CSE. 1056 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1057 !N->isMachineOpcode() && !doNotCSE(N)) { 1058 N->dump(this); 1059 dbgs() << "\n"; 1060 llvm_unreachable("Node is not in map!"); 1061 } 1062 #endif 1063 return Erased; 1064 } 1065 1066 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1067 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1068 /// node already exists, in which case transfer all its users to the existing 1069 /// node. This transfer can potentially trigger recursive merging. 1070 void 1071 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1072 // For node types that aren't CSE'd, just act as if no identical node 1073 // already exists. 1074 if (!doNotCSE(N)) { 1075 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1076 if (Existing != N) { 1077 // If there was already an existing matching node, use ReplaceAllUsesWith 1078 // to replace the dead one with the existing one. This can cause 1079 // recursive merging of other unrelated nodes down the line. 1080 ReplaceAllUsesWith(N, Existing); 1081 1082 // N is now dead. Inform the listeners and delete it. 1083 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1084 DUL->NodeDeleted(N, Existing); 1085 DeleteNodeNotInCSEMaps(N); 1086 return; 1087 } 1088 } 1089 1090 // If the node doesn't already exist, we updated it. Inform listeners. 1091 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1092 DUL->NodeUpdated(N); 1093 } 1094 1095 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1096 /// were replaced with those specified. If this node is never memoized, 1097 /// return null, otherwise return a pointer to the slot it would take. If a 1098 /// node already exists with these operands, the slot will be non-null. 1099 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1100 void *&InsertPos) { 1101 if (doNotCSE(N)) 1102 return nullptr; 1103 1104 SDValue Ops[] = { Op }; 1105 FoldingSetNodeID ID; 1106 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1107 AddNodeIDCustom(ID, N); 1108 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1109 if (Node) 1110 Node->intersectFlagsWith(N->getFlags()); 1111 return Node; 1112 } 1113 1114 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1115 /// were replaced with those specified. If this node is never memoized, 1116 /// return null, otherwise return a pointer to the slot it would take. If a 1117 /// node already exists with these operands, the slot will be non-null. 1118 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1119 SDValue Op1, SDValue Op2, 1120 void *&InsertPos) { 1121 if (doNotCSE(N)) 1122 return nullptr; 1123 1124 SDValue Ops[] = { Op1, Op2 }; 1125 FoldingSetNodeID ID; 1126 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1127 AddNodeIDCustom(ID, N); 1128 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1129 if (Node) 1130 Node->intersectFlagsWith(N->getFlags()); 1131 return Node; 1132 } 1133 1134 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1135 /// were replaced with those specified. If this node is never memoized, 1136 /// return null, otherwise return a pointer to the slot it would take. If a 1137 /// node already exists with these operands, the slot will be non-null. 1138 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1139 void *&InsertPos) { 1140 if (doNotCSE(N)) 1141 return nullptr; 1142 1143 FoldingSetNodeID ID; 1144 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1145 AddNodeIDCustom(ID, N); 1146 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1147 if (Node) 1148 Node->intersectFlagsWith(N->getFlags()); 1149 return Node; 1150 } 1151 1152 Align SelectionDAG::getEVTAlign(EVT VT) const { 1153 Type *Ty = VT == MVT::iPTR ? 1154 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1155 VT.getTypeForEVT(*getContext()); 1156 1157 return getDataLayout().getABITypeAlign(Ty); 1158 } 1159 1160 // EntryNode could meaningfully have debug info if we can find it... 1161 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1162 : TM(tm), OptLevel(OL), 1163 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1164 Root(getEntryNode()) { 1165 InsertNode(&EntryNode); 1166 DbgInfo = new SDDbgInfo(); 1167 } 1168 1169 void SelectionDAG::init(MachineFunction &NewMF, 1170 OptimizationRemarkEmitter &NewORE, 1171 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1172 LegacyDivergenceAnalysis * Divergence, 1173 ProfileSummaryInfo *PSIin, 1174 BlockFrequencyInfo *BFIin) { 1175 MF = &NewMF; 1176 SDAGISelPass = PassPtr; 1177 ORE = &NewORE; 1178 TLI = getSubtarget().getTargetLowering(); 1179 TSI = getSubtarget().getSelectionDAGInfo(); 1180 LibInfo = LibraryInfo; 1181 Context = &MF->getFunction().getContext(); 1182 DA = Divergence; 1183 PSI = PSIin; 1184 BFI = BFIin; 1185 } 1186 1187 SelectionDAG::~SelectionDAG() { 1188 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1189 allnodes_clear(); 1190 OperandRecycler.clear(OperandAllocator); 1191 delete DbgInfo; 1192 } 1193 1194 bool SelectionDAG::shouldOptForSize() const { 1195 return MF->getFunction().hasOptSize() || 1196 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1197 } 1198 1199 void SelectionDAG::allnodes_clear() { 1200 assert(&*AllNodes.begin() == &EntryNode); 1201 AllNodes.remove(AllNodes.begin()); 1202 while (!AllNodes.empty()) 1203 DeallocateNode(&AllNodes.front()); 1204 #ifndef NDEBUG 1205 NextPersistentId = 0; 1206 #endif 1207 } 1208 1209 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1210 void *&InsertPos) { 1211 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1212 if (N) { 1213 switch (N->getOpcode()) { 1214 default: break; 1215 case ISD::Constant: 1216 case ISD::ConstantFP: 1217 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1218 "debug location. Use another overload."); 1219 } 1220 } 1221 return N; 1222 } 1223 1224 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1225 const SDLoc &DL, void *&InsertPos) { 1226 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1227 if (N) { 1228 switch (N->getOpcode()) { 1229 case ISD::Constant: 1230 case ISD::ConstantFP: 1231 // Erase debug location from the node if the node is used at several 1232 // different places. Do not propagate one location to all uses as it 1233 // will cause a worse single stepping debugging experience. 1234 if (N->getDebugLoc() != DL.getDebugLoc()) 1235 N->setDebugLoc(DebugLoc()); 1236 break; 1237 default: 1238 // When the node's point of use is located earlier in the instruction 1239 // sequence than its prior point of use, update its debug info to the 1240 // earlier location. 1241 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1242 N->setDebugLoc(DL.getDebugLoc()); 1243 break; 1244 } 1245 } 1246 return N; 1247 } 1248 1249 void SelectionDAG::clear() { 1250 allnodes_clear(); 1251 OperandRecycler.clear(OperandAllocator); 1252 OperandAllocator.Reset(); 1253 CSEMap.clear(); 1254 1255 ExtendedValueTypeNodes.clear(); 1256 ExternalSymbols.clear(); 1257 TargetExternalSymbols.clear(); 1258 MCSymbols.clear(); 1259 SDCallSiteDbgInfo.clear(); 1260 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1261 static_cast<CondCodeSDNode*>(nullptr)); 1262 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1263 static_cast<SDNode*>(nullptr)); 1264 1265 EntryNode.UseList = nullptr; 1266 InsertNode(&EntryNode); 1267 Root = getEntryNode(); 1268 DbgInfo->clear(); 1269 } 1270 1271 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1272 return VT.bitsGT(Op.getValueType()) 1273 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1274 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1275 } 1276 1277 std::pair<SDValue, SDValue> 1278 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1279 const SDLoc &DL, EVT VT) { 1280 assert(!VT.bitsEq(Op.getValueType()) && 1281 "Strict no-op FP extend/round not allowed."); 1282 SDValue Res = 1283 VT.bitsGT(Op.getValueType()) 1284 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1285 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1286 {Chain, Op, getIntPtrConstant(0, DL)}); 1287 1288 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1289 } 1290 1291 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1292 return VT.bitsGT(Op.getValueType()) ? 1293 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1294 getNode(ISD::TRUNCATE, DL, VT, Op); 1295 } 1296 1297 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1298 return VT.bitsGT(Op.getValueType()) ? 1299 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1300 getNode(ISD::TRUNCATE, DL, VT, Op); 1301 } 1302 1303 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1304 return VT.bitsGT(Op.getValueType()) ? 1305 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1306 getNode(ISD::TRUNCATE, DL, VT, Op); 1307 } 1308 1309 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1310 EVT OpVT) { 1311 if (VT.bitsLE(Op.getValueType())) 1312 return getNode(ISD::TRUNCATE, SL, VT, Op); 1313 1314 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1315 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1316 } 1317 1318 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1319 EVT OpVT = Op.getValueType(); 1320 assert(VT.isInteger() && OpVT.isInteger() && 1321 "Cannot getZeroExtendInReg FP types"); 1322 assert(VT.isVector() == OpVT.isVector() && 1323 "getZeroExtendInReg type should be vector iff the operand " 1324 "type is vector!"); 1325 assert((!VT.isVector() || 1326 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1327 "Vector element counts must match in getZeroExtendInReg"); 1328 assert(VT.bitsLE(OpVT) && "Not extending!"); 1329 if (OpVT == VT) 1330 return Op; 1331 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1332 VT.getScalarSizeInBits()); 1333 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1334 } 1335 1336 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1337 // Only unsigned pointer semantics are supported right now. In the future this 1338 // might delegate to TLI to check pointer signedness. 1339 return getZExtOrTrunc(Op, DL, VT); 1340 } 1341 1342 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1343 // Only unsigned pointer semantics are supported right now. In the future this 1344 // might delegate to TLI to check pointer signedness. 1345 return getZeroExtendInReg(Op, DL, VT); 1346 } 1347 1348 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1349 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1350 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1351 } 1352 1353 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1354 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1355 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1356 } 1357 1358 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1359 EVT OpVT) { 1360 if (!V) 1361 return getConstant(0, DL, VT); 1362 1363 switch (TLI->getBooleanContents(OpVT)) { 1364 case TargetLowering::ZeroOrOneBooleanContent: 1365 case TargetLowering::UndefinedBooleanContent: 1366 return getConstant(1, DL, VT); 1367 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1368 return getAllOnesConstant(DL, VT); 1369 } 1370 llvm_unreachable("Unexpected boolean content enum!"); 1371 } 1372 1373 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1374 bool isT, bool isO) { 1375 EVT EltVT = VT.getScalarType(); 1376 assert((EltVT.getSizeInBits() >= 64 || 1377 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1378 "getConstant with a uint64_t value that doesn't fit in the type!"); 1379 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1380 } 1381 1382 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1383 bool isT, bool isO) { 1384 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1385 } 1386 1387 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1388 EVT VT, bool isT, bool isO) { 1389 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1390 1391 EVT EltVT = VT.getScalarType(); 1392 const ConstantInt *Elt = &Val; 1393 1394 // In some cases the vector type is legal but the element type is illegal and 1395 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1396 // inserted value (the type does not need to match the vector element type). 1397 // Any extra bits introduced will be truncated away. 1398 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1399 TargetLowering::TypePromoteInteger) { 1400 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1401 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1402 Elt = ConstantInt::get(*getContext(), NewVal); 1403 } 1404 // In other cases the element type is illegal and needs to be expanded, for 1405 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1406 // the value into n parts and use a vector type with n-times the elements. 1407 // Then bitcast to the type requested. 1408 // Legalizing constants too early makes the DAGCombiner's job harder so we 1409 // only legalize if the DAG tells us we must produce legal types. 1410 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1411 TLI->getTypeAction(*getContext(), EltVT) == 1412 TargetLowering::TypeExpandInteger) { 1413 const APInt &NewVal = Elt->getValue(); 1414 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1415 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1416 1417 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1418 if (VT.isScalableVector()) { 1419 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1420 "Can only handle an even split!"); 1421 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1422 1423 SmallVector<SDValue, 2> ScalarParts; 1424 for (unsigned i = 0; i != Parts; ++i) 1425 ScalarParts.push_back(getConstant( 1426 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1427 ViaEltVT, isT, isO)); 1428 1429 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1430 } 1431 1432 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1433 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1434 1435 // Check the temporary vector is the correct size. If this fails then 1436 // getTypeToTransformTo() probably returned a type whose size (in bits) 1437 // isn't a power-of-2 factor of the requested type size. 1438 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1439 1440 SmallVector<SDValue, 2> EltParts; 1441 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1442 EltParts.push_back(getConstant( 1443 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1444 ViaEltVT, isT, isO)); 1445 1446 // EltParts is currently in little endian order. If we actually want 1447 // big-endian order then reverse it now. 1448 if (getDataLayout().isBigEndian()) 1449 std::reverse(EltParts.begin(), EltParts.end()); 1450 1451 // The elements must be reversed when the element order is different 1452 // to the endianness of the elements (because the BITCAST is itself a 1453 // vector shuffle in this situation). However, we do not need any code to 1454 // perform this reversal because getConstant() is producing a vector 1455 // splat. 1456 // This situation occurs in MIPS MSA. 1457 1458 SmallVector<SDValue, 8> Ops; 1459 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1460 llvm::append_range(Ops, EltParts); 1461 1462 SDValue V = 1463 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1464 return V; 1465 } 1466 1467 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1468 "APInt size does not match type size!"); 1469 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1470 FoldingSetNodeID ID; 1471 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1472 ID.AddPointer(Elt); 1473 ID.AddBoolean(isO); 1474 void *IP = nullptr; 1475 SDNode *N = nullptr; 1476 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1477 if (!VT.isVector()) 1478 return SDValue(N, 0); 1479 1480 if (!N) { 1481 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1482 CSEMap.InsertNode(N, IP); 1483 InsertNode(N); 1484 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1485 } 1486 1487 SDValue Result(N, 0); 1488 if (VT.isScalableVector()) 1489 Result = getSplatVector(VT, DL, Result); 1490 else if (VT.isVector()) 1491 Result = getSplatBuildVector(VT, DL, Result); 1492 1493 return Result; 1494 } 1495 1496 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1497 bool isTarget) { 1498 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1499 } 1500 1501 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1502 const SDLoc &DL, bool LegalTypes) { 1503 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1504 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1505 return getConstant(Val, DL, ShiftVT); 1506 } 1507 1508 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1509 bool isTarget) { 1510 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1511 } 1512 1513 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1514 bool isTarget) { 1515 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1516 } 1517 1518 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1519 EVT VT, bool isTarget) { 1520 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1521 1522 EVT EltVT = VT.getScalarType(); 1523 1524 // Do the map lookup using the actual bit pattern for the floating point 1525 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1526 // we don't have issues with SNANs. 1527 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1528 FoldingSetNodeID ID; 1529 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1530 ID.AddPointer(&V); 1531 void *IP = nullptr; 1532 SDNode *N = nullptr; 1533 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1534 if (!VT.isVector()) 1535 return SDValue(N, 0); 1536 1537 if (!N) { 1538 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1539 CSEMap.InsertNode(N, IP); 1540 InsertNode(N); 1541 } 1542 1543 SDValue Result(N, 0); 1544 if (VT.isScalableVector()) 1545 Result = getSplatVector(VT, DL, Result); 1546 else if (VT.isVector()) 1547 Result = getSplatBuildVector(VT, DL, Result); 1548 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1549 return Result; 1550 } 1551 1552 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1553 bool isTarget) { 1554 EVT EltVT = VT.getScalarType(); 1555 if (EltVT == MVT::f32) 1556 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1557 if (EltVT == MVT::f64) 1558 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1559 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1560 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1561 bool Ignored; 1562 APFloat APF = APFloat(Val); 1563 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1564 &Ignored); 1565 return getConstantFP(APF, DL, VT, isTarget); 1566 } 1567 llvm_unreachable("Unsupported type in getConstantFP"); 1568 } 1569 1570 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1571 EVT VT, int64_t Offset, bool isTargetGA, 1572 unsigned TargetFlags) { 1573 assert((TargetFlags == 0 || isTargetGA) && 1574 "Cannot set target flags on target-independent globals"); 1575 1576 // Truncate (with sign-extension) the offset value to the pointer size. 1577 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1578 if (BitWidth < 64) 1579 Offset = SignExtend64(Offset, BitWidth); 1580 1581 unsigned Opc; 1582 if (GV->isThreadLocal()) 1583 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1584 else 1585 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1586 1587 FoldingSetNodeID ID; 1588 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1589 ID.AddPointer(GV); 1590 ID.AddInteger(Offset); 1591 ID.AddInteger(TargetFlags); 1592 void *IP = nullptr; 1593 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1594 return SDValue(E, 0); 1595 1596 auto *N = newSDNode<GlobalAddressSDNode>( 1597 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1598 CSEMap.InsertNode(N, IP); 1599 InsertNode(N); 1600 return SDValue(N, 0); 1601 } 1602 1603 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1604 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1605 FoldingSetNodeID ID; 1606 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1607 ID.AddInteger(FI); 1608 void *IP = nullptr; 1609 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1610 return SDValue(E, 0); 1611 1612 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1613 CSEMap.InsertNode(N, IP); 1614 InsertNode(N); 1615 return SDValue(N, 0); 1616 } 1617 1618 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1619 unsigned TargetFlags) { 1620 assert((TargetFlags == 0 || isTarget) && 1621 "Cannot set target flags on target-independent jump tables"); 1622 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1623 FoldingSetNodeID ID; 1624 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1625 ID.AddInteger(JTI); 1626 ID.AddInteger(TargetFlags); 1627 void *IP = nullptr; 1628 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1629 return SDValue(E, 0); 1630 1631 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1632 CSEMap.InsertNode(N, IP); 1633 InsertNode(N); 1634 return SDValue(N, 0); 1635 } 1636 1637 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1638 MaybeAlign Alignment, int Offset, 1639 bool isTarget, unsigned TargetFlags) { 1640 assert((TargetFlags == 0 || isTarget) && 1641 "Cannot set target flags on target-independent globals"); 1642 if (!Alignment) 1643 Alignment = shouldOptForSize() 1644 ? getDataLayout().getABITypeAlign(C->getType()) 1645 : getDataLayout().getPrefTypeAlign(C->getType()); 1646 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1647 FoldingSetNodeID ID; 1648 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1649 ID.AddInteger(Alignment->value()); 1650 ID.AddInteger(Offset); 1651 ID.AddPointer(C); 1652 ID.AddInteger(TargetFlags); 1653 void *IP = nullptr; 1654 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1655 return SDValue(E, 0); 1656 1657 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1658 TargetFlags); 1659 CSEMap.InsertNode(N, IP); 1660 InsertNode(N); 1661 SDValue V = SDValue(N, 0); 1662 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1663 return V; 1664 } 1665 1666 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1667 MaybeAlign Alignment, int Offset, 1668 bool isTarget, unsigned TargetFlags) { 1669 assert((TargetFlags == 0 || isTarget) && 1670 "Cannot set target flags on target-independent globals"); 1671 if (!Alignment) 1672 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1673 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1674 FoldingSetNodeID ID; 1675 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1676 ID.AddInteger(Alignment->value()); 1677 ID.AddInteger(Offset); 1678 C->addSelectionDAGCSEId(ID); 1679 ID.AddInteger(TargetFlags); 1680 void *IP = nullptr; 1681 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1682 return SDValue(E, 0); 1683 1684 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1685 TargetFlags); 1686 CSEMap.InsertNode(N, IP); 1687 InsertNode(N); 1688 return SDValue(N, 0); 1689 } 1690 1691 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1692 unsigned TargetFlags) { 1693 FoldingSetNodeID ID; 1694 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1695 ID.AddInteger(Index); 1696 ID.AddInteger(Offset); 1697 ID.AddInteger(TargetFlags); 1698 void *IP = nullptr; 1699 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1700 return SDValue(E, 0); 1701 1702 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1703 CSEMap.InsertNode(N, IP); 1704 InsertNode(N); 1705 return SDValue(N, 0); 1706 } 1707 1708 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1709 FoldingSetNodeID ID; 1710 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1711 ID.AddPointer(MBB); 1712 void *IP = nullptr; 1713 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1714 return SDValue(E, 0); 1715 1716 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1717 CSEMap.InsertNode(N, IP); 1718 InsertNode(N); 1719 return SDValue(N, 0); 1720 } 1721 1722 SDValue SelectionDAG::getValueType(EVT VT) { 1723 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1724 ValueTypeNodes.size()) 1725 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1726 1727 SDNode *&N = VT.isExtended() ? 1728 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1729 1730 if (N) return SDValue(N, 0); 1731 N = newSDNode<VTSDNode>(VT); 1732 InsertNode(N); 1733 return SDValue(N, 0); 1734 } 1735 1736 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1737 SDNode *&N = ExternalSymbols[Sym]; 1738 if (N) return SDValue(N, 0); 1739 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1740 InsertNode(N); 1741 return SDValue(N, 0); 1742 } 1743 1744 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1745 SDNode *&N = MCSymbols[Sym]; 1746 if (N) 1747 return SDValue(N, 0); 1748 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1749 InsertNode(N); 1750 return SDValue(N, 0); 1751 } 1752 1753 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1754 unsigned TargetFlags) { 1755 SDNode *&N = 1756 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1757 if (N) return SDValue(N, 0); 1758 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1759 InsertNode(N); 1760 return SDValue(N, 0); 1761 } 1762 1763 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1764 if ((unsigned)Cond >= CondCodeNodes.size()) 1765 CondCodeNodes.resize(Cond+1); 1766 1767 if (!CondCodeNodes[Cond]) { 1768 auto *N = newSDNode<CondCodeSDNode>(Cond); 1769 CondCodeNodes[Cond] = N; 1770 InsertNode(N); 1771 } 1772 1773 return SDValue(CondCodeNodes[Cond], 0); 1774 } 1775 1776 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1777 APInt One(ResVT.getScalarSizeInBits(), 1); 1778 return getStepVector(DL, ResVT, One); 1779 } 1780 1781 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1782 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1783 if (ResVT.isScalableVector()) 1784 return getNode( 1785 ISD::STEP_VECTOR, DL, ResVT, 1786 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1787 1788 SmallVector<SDValue, 16> OpsStepConstants; 1789 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1790 OpsStepConstants.push_back( 1791 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1792 return getBuildVector(ResVT, DL, OpsStepConstants); 1793 } 1794 1795 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1796 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1797 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1798 std::swap(N1, N2); 1799 ShuffleVectorSDNode::commuteMask(M); 1800 } 1801 1802 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1803 SDValue N2, ArrayRef<int> Mask) { 1804 assert(VT.getVectorNumElements() == Mask.size() && 1805 "Must have the same number of vector elements as mask elements!"); 1806 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1807 "Invalid VECTOR_SHUFFLE"); 1808 1809 // Canonicalize shuffle undef, undef -> undef 1810 if (N1.isUndef() && N2.isUndef()) 1811 return getUNDEF(VT); 1812 1813 // Validate that all indices in Mask are within the range of the elements 1814 // input to the shuffle. 1815 int NElts = Mask.size(); 1816 assert(llvm::all_of(Mask, 1817 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1818 "Index out of range"); 1819 1820 // Copy the mask so we can do any needed cleanup. 1821 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1822 1823 // Canonicalize shuffle v, v -> v, undef 1824 if (N1 == N2) { 1825 N2 = getUNDEF(VT); 1826 for (int i = 0; i != NElts; ++i) 1827 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1828 } 1829 1830 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1831 if (N1.isUndef()) 1832 commuteShuffle(N1, N2, MaskVec); 1833 1834 if (TLI->hasVectorBlend()) { 1835 // If shuffling a splat, try to blend the splat instead. We do this here so 1836 // that even when this arises during lowering we don't have to re-handle it. 1837 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1838 BitVector UndefElements; 1839 SDValue Splat = BV->getSplatValue(&UndefElements); 1840 if (!Splat) 1841 return; 1842 1843 for (int i = 0; i < NElts; ++i) { 1844 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1845 continue; 1846 1847 // If this input comes from undef, mark it as such. 1848 if (UndefElements[MaskVec[i] - Offset]) { 1849 MaskVec[i] = -1; 1850 continue; 1851 } 1852 1853 // If we can blend a non-undef lane, use that instead. 1854 if (!UndefElements[i]) 1855 MaskVec[i] = i + Offset; 1856 } 1857 }; 1858 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1859 BlendSplat(N1BV, 0); 1860 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1861 BlendSplat(N2BV, NElts); 1862 } 1863 1864 // Canonicalize all index into lhs, -> shuffle lhs, undef 1865 // Canonicalize all index into rhs, -> shuffle rhs, undef 1866 bool AllLHS = true, AllRHS = true; 1867 bool N2Undef = N2.isUndef(); 1868 for (int i = 0; i != NElts; ++i) { 1869 if (MaskVec[i] >= NElts) { 1870 if (N2Undef) 1871 MaskVec[i] = -1; 1872 else 1873 AllLHS = false; 1874 } else if (MaskVec[i] >= 0) { 1875 AllRHS = false; 1876 } 1877 } 1878 if (AllLHS && AllRHS) 1879 return getUNDEF(VT); 1880 if (AllLHS && !N2Undef) 1881 N2 = getUNDEF(VT); 1882 if (AllRHS) { 1883 N1 = getUNDEF(VT); 1884 commuteShuffle(N1, N2, MaskVec); 1885 } 1886 // Reset our undef status after accounting for the mask. 1887 N2Undef = N2.isUndef(); 1888 // Re-check whether both sides ended up undef. 1889 if (N1.isUndef() && N2Undef) 1890 return getUNDEF(VT); 1891 1892 // If Identity shuffle return that node. 1893 bool Identity = true, AllSame = true; 1894 for (int i = 0; i != NElts; ++i) { 1895 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1896 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1897 } 1898 if (Identity && NElts) 1899 return N1; 1900 1901 // Shuffling a constant splat doesn't change the result. 1902 if (N2Undef) { 1903 SDValue V = N1; 1904 1905 // Look through any bitcasts. We check that these don't change the number 1906 // (and size) of elements and just changes their types. 1907 while (V.getOpcode() == ISD::BITCAST) 1908 V = V->getOperand(0); 1909 1910 // A splat should always show up as a build vector node. 1911 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1912 BitVector UndefElements; 1913 SDValue Splat = BV->getSplatValue(&UndefElements); 1914 // If this is a splat of an undef, shuffling it is also undef. 1915 if (Splat && Splat.isUndef()) 1916 return getUNDEF(VT); 1917 1918 bool SameNumElts = 1919 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1920 1921 // We only have a splat which can skip shuffles if there is a splatted 1922 // value and no undef lanes rearranged by the shuffle. 1923 if (Splat && UndefElements.none()) { 1924 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1925 // number of elements match or the value splatted is a zero constant. 1926 if (SameNumElts) 1927 return N1; 1928 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1929 if (C->isZero()) 1930 return N1; 1931 } 1932 1933 // If the shuffle itself creates a splat, build the vector directly. 1934 if (AllSame && SameNumElts) { 1935 EVT BuildVT = BV->getValueType(0); 1936 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1937 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1938 1939 // We may have jumped through bitcasts, so the type of the 1940 // BUILD_VECTOR may not match the type of the shuffle. 1941 if (BuildVT != VT) 1942 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1943 return NewBV; 1944 } 1945 } 1946 } 1947 1948 FoldingSetNodeID ID; 1949 SDValue Ops[2] = { N1, N2 }; 1950 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1951 for (int i = 0; i != NElts; ++i) 1952 ID.AddInteger(MaskVec[i]); 1953 1954 void* IP = nullptr; 1955 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1956 return SDValue(E, 0); 1957 1958 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1959 // SDNode doesn't have access to it. This memory will be "leaked" when 1960 // the node is deallocated, but recovered when the NodeAllocator is released. 1961 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1962 llvm::copy(MaskVec, MaskAlloc); 1963 1964 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 1965 dl.getDebugLoc(), MaskAlloc); 1966 createOperands(N, Ops); 1967 1968 CSEMap.InsertNode(N, IP); 1969 InsertNode(N); 1970 SDValue V = SDValue(N, 0); 1971 NewSDValueDbgMsg(V, "Creating new node: ", this); 1972 return V; 1973 } 1974 1975 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 1976 EVT VT = SV.getValueType(0); 1977 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 1978 ShuffleVectorSDNode::commuteMask(MaskVec); 1979 1980 SDValue Op0 = SV.getOperand(0); 1981 SDValue Op1 = SV.getOperand(1); 1982 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 1983 } 1984 1985 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1986 FoldingSetNodeID ID; 1987 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 1988 ID.AddInteger(RegNo); 1989 void *IP = nullptr; 1990 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1991 return SDValue(E, 0); 1992 1993 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 1994 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 1995 CSEMap.InsertNode(N, IP); 1996 InsertNode(N); 1997 return SDValue(N, 0); 1998 } 1999 2000 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2001 FoldingSetNodeID ID; 2002 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2003 ID.AddPointer(RegMask); 2004 void *IP = nullptr; 2005 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2006 return SDValue(E, 0); 2007 2008 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2009 CSEMap.InsertNode(N, IP); 2010 InsertNode(N); 2011 return SDValue(N, 0); 2012 } 2013 2014 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2015 MCSymbol *Label) { 2016 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2017 } 2018 2019 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2020 SDValue Root, MCSymbol *Label) { 2021 FoldingSetNodeID ID; 2022 SDValue Ops[] = { Root }; 2023 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2024 ID.AddPointer(Label); 2025 void *IP = nullptr; 2026 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2027 return SDValue(E, 0); 2028 2029 auto *N = 2030 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2031 createOperands(N, Ops); 2032 2033 CSEMap.InsertNode(N, IP); 2034 InsertNode(N); 2035 return SDValue(N, 0); 2036 } 2037 2038 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2039 int64_t Offset, bool isTarget, 2040 unsigned TargetFlags) { 2041 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2042 2043 FoldingSetNodeID ID; 2044 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2045 ID.AddPointer(BA); 2046 ID.AddInteger(Offset); 2047 ID.AddInteger(TargetFlags); 2048 void *IP = nullptr; 2049 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2050 return SDValue(E, 0); 2051 2052 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2053 CSEMap.InsertNode(N, IP); 2054 InsertNode(N); 2055 return SDValue(N, 0); 2056 } 2057 2058 SDValue SelectionDAG::getSrcValue(const Value *V) { 2059 FoldingSetNodeID ID; 2060 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2061 ID.AddPointer(V); 2062 2063 void *IP = nullptr; 2064 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2065 return SDValue(E, 0); 2066 2067 auto *N = newSDNode<SrcValueSDNode>(V); 2068 CSEMap.InsertNode(N, IP); 2069 InsertNode(N); 2070 return SDValue(N, 0); 2071 } 2072 2073 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2074 FoldingSetNodeID ID; 2075 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2076 ID.AddPointer(MD); 2077 2078 void *IP = nullptr; 2079 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2080 return SDValue(E, 0); 2081 2082 auto *N = newSDNode<MDNodeSDNode>(MD); 2083 CSEMap.InsertNode(N, IP); 2084 InsertNode(N); 2085 return SDValue(N, 0); 2086 } 2087 2088 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2089 if (VT == V.getValueType()) 2090 return V; 2091 2092 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2093 } 2094 2095 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2096 unsigned SrcAS, unsigned DestAS) { 2097 SDValue Ops[] = {Ptr}; 2098 FoldingSetNodeID ID; 2099 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2100 ID.AddInteger(SrcAS); 2101 ID.AddInteger(DestAS); 2102 2103 void *IP = nullptr; 2104 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2105 return SDValue(E, 0); 2106 2107 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2108 VT, SrcAS, DestAS); 2109 createOperands(N, Ops); 2110 2111 CSEMap.InsertNode(N, IP); 2112 InsertNode(N); 2113 return SDValue(N, 0); 2114 } 2115 2116 SDValue SelectionDAG::getFreeze(SDValue V) { 2117 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2118 } 2119 2120 /// getShiftAmountOperand - Return the specified value casted to 2121 /// the target's desired shift amount type. 2122 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2123 EVT OpTy = Op.getValueType(); 2124 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2125 if (OpTy == ShTy || OpTy.isVector()) return Op; 2126 2127 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2128 } 2129 2130 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2131 SDLoc dl(Node); 2132 const TargetLowering &TLI = getTargetLoweringInfo(); 2133 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2134 EVT VT = Node->getValueType(0); 2135 SDValue Tmp1 = Node->getOperand(0); 2136 SDValue Tmp2 = Node->getOperand(1); 2137 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2138 2139 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2140 Tmp2, MachinePointerInfo(V)); 2141 SDValue VAList = VAListLoad; 2142 2143 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2144 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2145 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2146 2147 VAList = 2148 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2149 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2150 } 2151 2152 // Increment the pointer, VAList, to the next vaarg 2153 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2154 getConstant(getDataLayout().getTypeAllocSize( 2155 VT.getTypeForEVT(*getContext())), 2156 dl, VAList.getValueType())); 2157 // Store the incremented VAList to the legalized pointer 2158 Tmp1 = 2159 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2160 // Load the actual argument out of the pointer VAList 2161 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2162 } 2163 2164 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2165 SDLoc dl(Node); 2166 const TargetLowering &TLI = getTargetLoweringInfo(); 2167 // This defaults to loading a pointer from the input and storing it to the 2168 // output, returning the chain. 2169 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2170 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2171 SDValue Tmp1 = 2172 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2173 Node->getOperand(2), MachinePointerInfo(VS)); 2174 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2175 MachinePointerInfo(VD)); 2176 } 2177 2178 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2179 const DataLayout &DL = getDataLayout(); 2180 Type *Ty = VT.getTypeForEVT(*getContext()); 2181 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2182 2183 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2184 return RedAlign; 2185 2186 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2187 const Align StackAlign = TFI->getStackAlign(); 2188 2189 // See if we can choose a smaller ABI alignment in cases where it's an 2190 // illegal vector type that will get broken down. 2191 if (RedAlign > StackAlign) { 2192 EVT IntermediateVT; 2193 MVT RegisterVT; 2194 unsigned NumIntermediates; 2195 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2196 NumIntermediates, RegisterVT); 2197 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2198 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2199 if (RedAlign2 < RedAlign) 2200 RedAlign = RedAlign2; 2201 } 2202 2203 return RedAlign; 2204 } 2205 2206 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2207 MachineFrameInfo &MFI = MF->getFrameInfo(); 2208 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2209 int StackID = 0; 2210 if (Bytes.isScalable()) 2211 StackID = TFI->getStackIDForScalableVectors(); 2212 // The stack id gives an indication of whether the object is scalable or 2213 // not, so it's safe to pass in the minimum size here. 2214 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2215 false, nullptr, StackID); 2216 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2217 } 2218 2219 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2220 Type *Ty = VT.getTypeForEVT(*getContext()); 2221 Align StackAlign = 2222 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2223 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2224 } 2225 2226 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2227 TypeSize VT1Size = VT1.getStoreSize(); 2228 TypeSize VT2Size = VT2.getStoreSize(); 2229 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2230 "Don't know how to choose the maximum size when creating a stack " 2231 "temporary"); 2232 TypeSize Bytes = 2233 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2234 2235 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2236 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2237 const DataLayout &DL = getDataLayout(); 2238 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2239 return CreateStackTemporary(Bytes, Align); 2240 } 2241 2242 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2243 ISD::CondCode Cond, const SDLoc &dl) { 2244 EVT OpVT = N1.getValueType(); 2245 2246 // These setcc operations always fold. 2247 switch (Cond) { 2248 default: break; 2249 case ISD::SETFALSE: 2250 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2251 case ISD::SETTRUE: 2252 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2253 2254 case ISD::SETOEQ: 2255 case ISD::SETOGT: 2256 case ISD::SETOGE: 2257 case ISD::SETOLT: 2258 case ISD::SETOLE: 2259 case ISD::SETONE: 2260 case ISD::SETO: 2261 case ISD::SETUO: 2262 case ISD::SETUEQ: 2263 case ISD::SETUNE: 2264 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2265 break; 2266 } 2267 2268 if (OpVT.isInteger()) { 2269 // For EQ and NE, we can always pick a value for the undef to make the 2270 // predicate pass or fail, so we can return undef. 2271 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2272 // icmp eq/ne X, undef -> undef. 2273 if ((N1.isUndef() || N2.isUndef()) && 2274 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2275 return getUNDEF(VT); 2276 2277 // If both operands are undef, we can return undef for int comparison. 2278 // icmp undef, undef -> undef. 2279 if (N1.isUndef() && N2.isUndef()) 2280 return getUNDEF(VT); 2281 2282 // icmp X, X -> true/false 2283 // icmp X, undef -> true/false because undef could be X. 2284 if (N1 == N2) 2285 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2286 } 2287 2288 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2289 const APInt &C2 = N2C->getAPIntValue(); 2290 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2291 const APInt &C1 = N1C->getAPIntValue(); 2292 2293 switch (Cond) { 2294 default: llvm_unreachable("Unknown integer setcc!"); 2295 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT); 2296 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT); 2297 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT); 2298 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT); 2299 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT); 2300 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT); 2301 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT); 2302 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT); 2303 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT); 2304 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT); 2305 } 2306 } 2307 } 2308 2309 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2310 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2311 2312 if (N1CFP && N2CFP) { 2313 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2314 switch (Cond) { 2315 default: break; 2316 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2317 return getUNDEF(VT); 2318 LLVM_FALLTHROUGH; 2319 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2320 OpVT); 2321 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2322 return getUNDEF(VT); 2323 LLVM_FALLTHROUGH; 2324 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2325 R==APFloat::cmpLessThan, dl, VT, 2326 OpVT); 2327 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2328 return getUNDEF(VT); 2329 LLVM_FALLTHROUGH; 2330 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2331 OpVT); 2332 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2333 return getUNDEF(VT); 2334 LLVM_FALLTHROUGH; 2335 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2336 VT, OpVT); 2337 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2338 return getUNDEF(VT); 2339 LLVM_FALLTHROUGH; 2340 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2341 R==APFloat::cmpEqual, dl, VT, 2342 OpVT); 2343 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2344 return getUNDEF(VT); 2345 LLVM_FALLTHROUGH; 2346 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2347 R==APFloat::cmpEqual, dl, VT, OpVT); 2348 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2349 OpVT); 2350 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2351 OpVT); 2352 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2353 R==APFloat::cmpEqual, dl, VT, 2354 OpVT); 2355 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2356 OpVT); 2357 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2358 R==APFloat::cmpLessThan, dl, VT, 2359 OpVT); 2360 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2361 R==APFloat::cmpUnordered, dl, VT, 2362 OpVT); 2363 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2364 VT, OpVT); 2365 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2366 OpVT); 2367 } 2368 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2369 // Ensure that the constant occurs on the RHS. 2370 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2371 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2372 return SDValue(); 2373 return getSetCC(dl, VT, N2, N1, SwappedCond); 2374 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2375 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2376 // If an operand is known to be a nan (or undef that could be a nan), we can 2377 // fold it. 2378 // Choosing NaN for the undef will always make unordered comparison succeed 2379 // and ordered comparison fails. 2380 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2381 switch (ISD::getUnorderedFlavor(Cond)) { 2382 default: 2383 llvm_unreachable("Unknown flavor!"); 2384 case 0: // Known false. 2385 return getBoolConstant(false, dl, VT, OpVT); 2386 case 1: // Known true. 2387 return getBoolConstant(true, dl, VT, OpVT); 2388 case 2: // Undefined. 2389 return getUNDEF(VT); 2390 } 2391 } 2392 2393 // Could not fold it. 2394 return SDValue(); 2395 } 2396 2397 /// See if the specified operand can be simplified with the knowledge that only 2398 /// the bits specified by DemandedBits are used. 2399 /// TODO: really we should be making this into the DAG equivalent of 2400 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2401 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2402 EVT VT = V.getValueType(); 2403 2404 if (VT.isScalableVector()) 2405 return SDValue(); 2406 2407 APInt DemandedElts = VT.isVector() 2408 ? APInt::getAllOnes(VT.getVectorNumElements()) 2409 : APInt(1, 1); 2410 return GetDemandedBits(V, DemandedBits, DemandedElts); 2411 } 2412 2413 /// See if the specified operand can be simplified with the knowledge that only 2414 /// the bits specified by DemandedBits are used in the elements specified by 2415 /// DemandedElts. 2416 /// TODO: really we should be making this into the DAG equivalent of 2417 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2418 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2419 const APInt &DemandedElts) { 2420 switch (V.getOpcode()) { 2421 default: 2422 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2423 *this, 0); 2424 case ISD::Constant: { 2425 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2426 APInt NewVal = CVal & DemandedBits; 2427 if (NewVal != CVal) 2428 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2429 break; 2430 } 2431 case ISD::SRL: 2432 // Only look at single-use SRLs. 2433 if (!V.getNode()->hasOneUse()) 2434 break; 2435 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2436 // See if we can recursively simplify the LHS. 2437 unsigned Amt = RHSC->getZExtValue(); 2438 2439 // Watch out for shift count overflow though. 2440 if (Amt >= DemandedBits.getBitWidth()) 2441 break; 2442 APInt SrcDemandedBits = DemandedBits << Amt; 2443 if (SDValue SimplifyLHS = 2444 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2445 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2446 V.getOperand(1)); 2447 } 2448 break; 2449 } 2450 return SDValue(); 2451 } 2452 2453 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2454 /// use this predicate to simplify operations downstream. 2455 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2456 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2457 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2458 } 2459 2460 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2461 /// this predicate to simplify operations downstream. Mask is known to be zero 2462 /// for bits that V cannot have. 2463 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2464 unsigned Depth) const { 2465 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2466 } 2467 2468 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2469 /// DemandedElts. We use this predicate to simplify operations downstream. 2470 /// Mask is known to be zero for bits that V cannot have. 2471 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2472 const APInt &DemandedElts, 2473 unsigned Depth) const { 2474 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2475 } 2476 2477 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2478 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2479 unsigned Depth) const { 2480 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2481 } 2482 2483 /// isSplatValue - Return true if the vector V has the same value 2484 /// across all DemandedElts. For scalable vectors it does not make 2485 /// sense to specify which elements are demanded or undefined, therefore 2486 /// they are simply ignored. 2487 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2488 APInt &UndefElts, unsigned Depth) { 2489 EVT VT = V.getValueType(); 2490 assert(VT.isVector() && "Vector type expected"); 2491 2492 if (!VT.isScalableVector() && !DemandedElts) 2493 return false; // No demanded elts, better to assume we don't know anything. 2494 2495 if (Depth >= MaxRecursionDepth) 2496 return false; // Limit search depth. 2497 2498 // Deal with some common cases here that work for both fixed and scalable 2499 // vector types. 2500 switch (V.getOpcode()) { 2501 case ISD::SPLAT_VECTOR: 2502 UndefElts = V.getOperand(0).isUndef() 2503 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2504 : APInt(DemandedElts.getBitWidth(), 0); 2505 return true; 2506 case ISD::ADD: 2507 case ISD::SUB: 2508 case ISD::AND: 2509 case ISD::XOR: 2510 case ISD::OR: { 2511 APInt UndefLHS, UndefRHS; 2512 SDValue LHS = V.getOperand(0); 2513 SDValue RHS = V.getOperand(1); 2514 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2515 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2516 UndefElts = UndefLHS | UndefRHS; 2517 return true; 2518 } 2519 return false; 2520 } 2521 case ISD::ABS: 2522 case ISD::TRUNCATE: 2523 case ISD::SIGN_EXTEND: 2524 case ISD::ZERO_EXTEND: 2525 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2526 } 2527 2528 // We don't support other cases than those above for scalable vectors at 2529 // the moment. 2530 if (VT.isScalableVector()) 2531 return false; 2532 2533 unsigned NumElts = VT.getVectorNumElements(); 2534 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2535 UndefElts = APInt::getZero(NumElts); 2536 2537 switch (V.getOpcode()) { 2538 case ISD::BUILD_VECTOR: { 2539 SDValue Scl; 2540 for (unsigned i = 0; i != NumElts; ++i) { 2541 SDValue Op = V.getOperand(i); 2542 if (Op.isUndef()) { 2543 UndefElts.setBit(i); 2544 continue; 2545 } 2546 if (!DemandedElts[i]) 2547 continue; 2548 if (Scl && Scl != Op) 2549 return false; 2550 Scl = Op; 2551 } 2552 return true; 2553 } 2554 case ISD::VECTOR_SHUFFLE: { 2555 // Check if this is a shuffle node doing a splat. 2556 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2557 int SplatIndex = -1; 2558 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2559 for (int i = 0; i != (int)NumElts; ++i) { 2560 int M = Mask[i]; 2561 if (M < 0) { 2562 UndefElts.setBit(i); 2563 continue; 2564 } 2565 if (!DemandedElts[i]) 2566 continue; 2567 if (0 <= SplatIndex && SplatIndex != M) 2568 return false; 2569 SplatIndex = M; 2570 } 2571 return true; 2572 } 2573 case ISD::EXTRACT_SUBVECTOR: { 2574 // Offset the demanded elts by the subvector index. 2575 SDValue Src = V.getOperand(0); 2576 // We don't support scalable vectors at the moment. 2577 if (Src.getValueType().isScalableVector()) 2578 return false; 2579 uint64_t Idx = V.getConstantOperandVal(1); 2580 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2581 APInt UndefSrcElts; 2582 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2583 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2584 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2585 return true; 2586 } 2587 break; 2588 } 2589 } 2590 2591 return false; 2592 } 2593 2594 /// Helper wrapper to main isSplatValue function. 2595 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) { 2596 EVT VT = V.getValueType(); 2597 assert(VT.isVector() && "Vector type expected"); 2598 2599 APInt UndefElts; 2600 APInt DemandedElts; 2601 2602 // For now we don't support this with scalable vectors. 2603 if (!VT.isScalableVector()) 2604 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2605 return isSplatValue(V, DemandedElts, UndefElts) && 2606 (AllowUndefs || !UndefElts); 2607 } 2608 2609 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2610 V = peekThroughExtractSubvectors(V); 2611 2612 EVT VT = V.getValueType(); 2613 unsigned Opcode = V.getOpcode(); 2614 switch (Opcode) { 2615 default: { 2616 APInt UndefElts; 2617 APInt DemandedElts; 2618 2619 if (!VT.isScalableVector()) 2620 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2621 2622 if (isSplatValue(V, DemandedElts, UndefElts)) { 2623 if (VT.isScalableVector()) { 2624 // DemandedElts and UndefElts are ignored for scalable vectors, since 2625 // the only supported cases are SPLAT_VECTOR nodes. 2626 SplatIdx = 0; 2627 } else { 2628 // Handle case where all demanded elements are UNDEF. 2629 if (DemandedElts.isSubsetOf(UndefElts)) { 2630 SplatIdx = 0; 2631 return getUNDEF(VT); 2632 } 2633 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2634 } 2635 return V; 2636 } 2637 break; 2638 } 2639 case ISD::SPLAT_VECTOR: 2640 SplatIdx = 0; 2641 return V; 2642 case ISD::VECTOR_SHUFFLE: { 2643 if (VT.isScalableVector()) 2644 return SDValue(); 2645 2646 // Check if this is a shuffle node doing a splat. 2647 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2648 // getTargetVShiftNode currently struggles without the splat source. 2649 auto *SVN = cast<ShuffleVectorSDNode>(V); 2650 if (!SVN->isSplat()) 2651 break; 2652 int Idx = SVN->getSplatIndex(); 2653 int NumElts = V.getValueType().getVectorNumElements(); 2654 SplatIdx = Idx % NumElts; 2655 return V.getOperand(Idx / NumElts); 2656 } 2657 } 2658 2659 return SDValue(); 2660 } 2661 2662 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2663 int SplatIdx; 2664 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2665 EVT SVT = SrcVector.getValueType().getScalarType(); 2666 EVT LegalSVT = SVT; 2667 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2668 if (!SVT.isInteger()) 2669 return SDValue(); 2670 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2671 if (LegalSVT.bitsLT(SVT)) 2672 return SDValue(); 2673 } 2674 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2675 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2676 } 2677 return SDValue(); 2678 } 2679 2680 const APInt * 2681 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2682 const APInt &DemandedElts) const { 2683 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2684 V.getOpcode() == ISD::SRA) && 2685 "Unknown shift node"); 2686 unsigned BitWidth = V.getScalarValueSizeInBits(); 2687 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2688 // Shifting more than the bitwidth is not valid. 2689 const APInt &ShAmt = SA->getAPIntValue(); 2690 if (ShAmt.ult(BitWidth)) 2691 return &ShAmt; 2692 } 2693 return nullptr; 2694 } 2695 2696 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2697 SDValue V, const APInt &DemandedElts) const { 2698 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2699 V.getOpcode() == ISD::SRA) && 2700 "Unknown shift node"); 2701 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2702 return ValidAmt; 2703 unsigned BitWidth = V.getScalarValueSizeInBits(); 2704 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2705 if (!BV) 2706 return nullptr; 2707 const APInt *MinShAmt = nullptr; 2708 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2709 if (!DemandedElts[i]) 2710 continue; 2711 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2712 if (!SA) 2713 return nullptr; 2714 // Shifting more than the bitwidth is not valid. 2715 const APInt &ShAmt = SA->getAPIntValue(); 2716 if (ShAmt.uge(BitWidth)) 2717 return nullptr; 2718 if (MinShAmt && MinShAmt->ule(ShAmt)) 2719 continue; 2720 MinShAmt = &ShAmt; 2721 } 2722 return MinShAmt; 2723 } 2724 2725 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2726 SDValue V, const APInt &DemandedElts) const { 2727 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2728 V.getOpcode() == ISD::SRA) && 2729 "Unknown shift node"); 2730 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2731 return ValidAmt; 2732 unsigned BitWidth = V.getScalarValueSizeInBits(); 2733 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2734 if (!BV) 2735 return nullptr; 2736 const APInt *MaxShAmt = nullptr; 2737 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2738 if (!DemandedElts[i]) 2739 continue; 2740 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2741 if (!SA) 2742 return nullptr; 2743 // Shifting more than the bitwidth is not valid. 2744 const APInt &ShAmt = SA->getAPIntValue(); 2745 if (ShAmt.uge(BitWidth)) 2746 return nullptr; 2747 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2748 continue; 2749 MaxShAmt = &ShAmt; 2750 } 2751 return MaxShAmt; 2752 } 2753 2754 /// Determine which bits of Op are known to be either zero or one and return 2755 /// them in Known. For vectors, the known bits are those that are shared by 2756 /// every vector element. 2757 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2758 EVT VT = Op.getValueType(); 2759 2760 // TOOD: Until we have a plan for how to represent demanded elements for 2761 // scalable vectors, we can just bail out for now. 2762 if (Op.getValueType().isScalableVector()) { 2763 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2764 return KnownBits(BitWidth); 2765 } 2766 2767 APInt DemandedElts = VT.isVector() 2768 ? APInt::getAllOnes(VT.getVectorNumElements()) 2769 : APInt(1, 1); 2770 return computeKnownBits(Op, DemandedElts, Depth); 2771 } 2772 2773 /// Determine which bits of Op are known to be either zero or one and return 2774 /// them in Known. The DemandedElts argument allows us to only collect the known 2775 /// bits that are shared by the requested vector elements. 2776 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2777 unsigned Depth) const { 2778 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2779 2780 KnownBits Known(BitWidth); // Don't know anything. 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 return Known; 2786 2787 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2788 // We know all of the bits for a constant! 2789 return KnownBits::makeConstant(C->getAPIntValue()); 2790 } 2791 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2792 // We know all of the bits for a constant fp! 2793 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2794 } 2795 2796 if (Depth >= MaxRecursionDepth) 2797 return Known; // Limit search depth. 2798 2799 KnownBits Known2; 2800 unsigned NumElts = DemandedElts.getBitWidth(); 2801 assert((!Op.getValueType().isVector() || 2802 NumElts == Op.getValueType().getVectorNumElements()) && 2803 "Unexpected vector size"); 2804 2805 if (!DemandedElts) 2806 return Known; // No demanded elts, better to assume we don't know anything. 2807 2808 unsigned Opcode = Op.getOpcode(); 2809 switch (Opcode) { 2810 case ISD::BUILD_VECTOR: 2811 // Collect the known bits that are shared by every demanded vector element. 2812 Known.Zero.setAllBits(); Known.One.setAllBits(); 2813 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2814 if (!DemandedElts[i]) 2815 continue; 2816 2817 SDValue SrcOp = Op.getOperand(i); 2818 Known2 = computeKnownBits(SrcOp, Depth + 1); 2819 2820 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2821 if (SrcOp.getValueSizeInBits() != BitWidth) { 2822 assert(SrcOp.getValueSizeInBits() > BitWidth && 2823 "Expected BUILD_VECTOR implicit truncation"); 2824 Known2 = Known2.trunc(BitWidth); 2825 } 2826 2827 // Known bits are the values that are shared by every demanded element. 2828 Known = KnownBits::commonBits(Known, Known2); 2829 2830 // If we don't know any bits, early out. 2831 if (Known.isUnknown()) 2832 break; 2833 } 2834 break; 2835 case ISD::VECTOR_SHUFFLE: { 2836 // Collect the known bits that are shared by every vector element referenced 2837 // by the shuffle. 2838 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2839 Known.Zero.setAllBits(); Known.One.setAllBits(); 2840 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2841 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2842 for (unsigned i = 0; i != NumElts; ++i) { 2843 if (!DemandedElts[i]) 2844 continue; 2845 2846 int M = SVN->getMaskElt(i); 2847 if (M < 0) { 2848 // For UNDEF elements, we don't know anything about the common state of 2849 // the shuffle result. 2850 Known.resetAll(); 2851 DemandedLHS.clearAllBits(); 2852 DemandedRHS.clearAllBits(); 2853 break; 2854 } 2855 2856 if ((unsigned)M < NumElts) 2857 DemandedLHS.setBit((unsigned)M % NumElts); 2858 else 2859 DemandedRHS.setBit((unsigned)M % NumElts); 2860 } 2861 // Known bits are the values that are shared by every demanded element. 2862 if (!!DemandedLHS) { 2863 SDValue LHS = Op.getOperand(0); 2864 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2865 Known = KnownBits::commonBits(Known, Known2); 2866 } 2867 // If we don't know any bits, early out. 2868 if (Known.isUnknown()) 2869 break; 2870 if (!!DemandedRHS) { 2871 SDValue RHS = Op.getOperand(1); 2872 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2873 Known = KnownBits::commonBits(Known, Known2); 2874 } 2875 break; 2876 } 2877 case ISD::CONCAT_VECTORS: { 2878 // Split DemandedElts and test each of the demanded subvectors. 2879 Known.Zero.setAllBits(); Known.One.setAllBits(); 2880 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2881 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2882 unsigned NumSubVectors = Op.getNumOperands(); 2883 for (unsigned i = 0; i != NumSubVectors; ++i) { 2884 APInt DemandedSub = 2885 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 2886 if (!!DemandedSub) { 2887 SDValue Sub = Op.getOperand(i); 2888 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2889 Known = KnownBits::commonBits(Known, Known2); 2890 } 2891 // If we don't know any bits, early out. 2892 if (Known.isUnknown()) 2893 break; 2894 } 2895 break; 2896 } 2897 case ISD::INSERT_SUBVECTOR: { 2898 // Demand any elements from the subvector and the remainder from the src its 2899 // inserted into. 2900 SDValue Src = Op.getOperand(0); 2901 SDValue Sub = Op.getOperand(1); 2902 uint64_t Idx = Op.getConstantOperandVal(2); 2903 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2904 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2905 APInt DemandedSrcElts = DemandedElts; 2906 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 2907 2908 Known.One.setAllBits(); 2909 Known.Zero.setAllBits(); 2910 if (!!DemandedSubElts) { 2911 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2912 if (Known.isUnknown()) 2913 break; // early-out. 2914 } 2915 if (!!DemandedSrcElts) { 2916 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2917 Known = KnownBits::commonBits(Known, Known2); 2918 } 2919 break; 2920 } 2921 case ISD::EXTRACT_SUBVECTOR: { 2922 // Offset the demanded elts by the subvector index. 2923 SDValue Src = Op.getOperand(0); 2924 // Bail until we can represent demanded elements for scalable vectors. 2925 if (Src.getValueType().isScalableVector()) 2926 break; 2927 uint64_t Idx = Op.getConstantOperandVal(1); 2928 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2929 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2930 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2931 break; 2932 } 2933 case ISD::SCALAR_TO_VECTOR: { 2934 // We know about scalar_to_vector as much as we know about it source, 2935 // which becomes the first element of otherwise unknown vector. 2936 if (DemandedElts != 1) 2937 break; 2938 2939 SDValue N0 = Op.getOperand(0); 2940 Known = computeKnownBits(N0, Depth + 1); 2941 if (N0.getValueSizeInBits() != BitWidth) 2942 Known = Known.trunc(BitWidth); 2943 2944 break; 2945 } 2946 case ISD::BITCAST: { 2947 SDValue N0 = Op.getOperand(0); 2948 EVT SubVT = N0.getValueType(); 2949 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 2950 2951 // Ignore bitcasts from unsupported types. 2952 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 2953 break; 2954 2955 // Fast handling of 'identity' bitcasts. 2956 if (BitWidth == SubBitWidth) { 2957 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 2958 break; 2959 } 2960 2961 bool IsLE = getDataLayout().isLittleEndian(); 2962 2963 // Bitcast 'small element' vector to 'large element' scalar/vector. 2964 if ((BitWidth % SubBitWidth) == 0) { 2965 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 2966 2967 // Collect known bits for the (larger) output by collecting the known 2968 // bits from each set of sub elements and shift these into place. 2969 // We need to separately call computeKnownBits for each set of 2970 // sub elements as the knownbits for each is likely to be different. 2971 unsigned SubScale = BitWidth / SubBitWidth; 2972 APInt SubDemandedElts(NumElts * SubScale, 0); 2973 for (unsigned i = 0; i != NumElts; ++i) 2974 if (DemandedElts[i]) 2975 SubDemandedElts.setBit(i * SubScale); 2976 2977 for (unsigned i = 0; i != SubScale; ++i) { 2978 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 2979 Depth + 1); 2980 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 2981 Known.insertBits(Known2, SubBitWidth * Shifts); 2982 } 2983 } 2984 2985 // Bitcast 'large element' scalar/vector to 'small element' vector. 2986 if ((SubBitWidth % BitWidth) == 0) { 2987 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 2988 2989 // Collect known bits for the (smaller) output by collecting the known 2990 // bits from the overlapping larger input elements and extracting the 2991 // sub sections we actually care about. 2992 unsigned SubScale = SubBitWidth / BitWidth; 2993 APInt SubDemandedElts = 2994 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 2995 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 2996 2997 Known.Zero.setAllBits(); Known.One.setAllBits(); 2998 for (unsigned i = 0; i != NumElts; ++i) 2999 if (DemandedElts[i]) { 3000 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3001 unsigned Offset = (Shifts % SubScale) * BitWidth; 3002 Known = KnownBits::commonBits(Known, 3003 Known2.extractBits(BitWidth, Offset)); 3004 // If we don't know any bits, early out. 3005 if (Known.isUnknown()) 3006 break; 3007 } 3008 } 3009 break; 3010 } 3011 case ISD::AND: 3012 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3013 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3014 3015 Known &= Known2; 3016 break; 3017 case ISD::OR: 3018 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3019 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3020 3021 Known |= Known2; 3022 break; 3023 case ISD::XOR: 3024 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3025 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3026 3027 Known ^= Known2; 3028 break; 3029 case ISD::MUL: { 3030 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3031 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3032 Known = KnownBits::mul(Known, Known2); 3033 break; 3034 } 3035 case ISD::MULHU: { 3036 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3037 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3038 Known = KnownBits::mulhu(Known, Known2); 3039 break; 3040 } 3041 case ISD::MULHS: { 3042 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3043 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3044 Known = KnownBits::mulhs(Known, Known2); 3045 break; 3046 } 3047 case ISD::UMUL_LOHI: { 3048 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3049 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3050 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3051 if (Op.getResNo() == 0) 3052 Known = KnownBits::mul(Known, Known2); 3053 else 3054 Known = KnownBits::mulhu(Known, Known2); 3055 break; 3056 } 3057 case ISD::SMUL_LOHI: { 3058 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3059 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3060 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3061 if (Op.getResNo() == 0) 3062 Known = KnownBits::mul(Known, Known2); 3063 else 3064 Known = KnownBits::mulhs(Known, Known2); 3065 break; 3066 } 3067 case ISD::UDIV: { 3068 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3069 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3070 Known = KnownBits::udiv(Known, Known2); 3071 break; 3072 } 3073 case ISD::SELECT: 3074 case ISD::VSELECT: 3075 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3076 // If we don't know any bits, early out. 3077 if (Known.isUnknown()) 3078 break; 3079 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3080 3081 // Only known if known in both the LHS and RHS. 3082 Known = KnownBits::commonBits(Known, Known2); 3083 break; 3084 case ISD::SELECT_CC: 3085 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3086 // If we don't know any bits, early out. 3087 if (Known.isUnknown()) 3088 break; 3089 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3090 3091 // Only known if known in both the LHS and RHS. 3092 Known = KnownBits::commonBits(Known, Known2); 3093 break; 3094 case ISD::SMULO: 3095 case ISD::UMULO: 3096 if (Op.getResNo() != 1) 3097 break; 3098 // The boolean result conforms to getBooleanContents. 3099 // If we know the result of a setcc has the top bits zero, use this info. 3100 // We know that we have an integer-based boolean since these operations 3101 // are only available for integer. 3102 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3103 TargetLowering::ZeroOrOneBooleanContent && 3104 BitWidth > 1) 3105 Known.Zero.setBitsFrom(1); 3106 break; 3107 case ISD::SETCC: 3108 case ISD::STRICT_FSETCC: 3109 case ISD::STRICT_FSETCCS: { 3110 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3111 // If we know the result of a setcc has the top bits zero, use this info. 3112 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3113 TargetLowering::ZeroOrOneBooleanContent && 3114 BitWidth > 1) 3115 Known.Zero.setBitsFrom(1); 3116 break; 3117 } 3118 case ISD::SHL: 3119 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3120 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3121 Known = KnownBits::shl(Known, Known2); 3122 3123 // Minimum shift low bits are known zero. 3124 if (const APInt *ShMinAmt = 3125 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3126 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3127 break; 3128 case ISD::SRL: 3129 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3130 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3131 Known = KnownBits::lshr(Known, Known2); 3132 3133 // Minimum shift high bits are known zero. 3134 if (const APInt *ShMinAmt = 3135 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3136 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3137 break; 3138 case ISD::SRA: 3139 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3140 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3141 Known = KnownBits::ashr(Known, Known2); 3142 // TODO: Add minimum shift high known sign bits. 3143 break; 3144 case ISD::FSHL: 3145 case ISD::FSHR: 3146 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3147 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3148 3149 // For fshl, 0-shift returns the 1st arg. 3150 // For fshr, 0-shift returns the 2nd arg. 3151 if (Amt == 0) { 3152 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3153 DemandedElts, Depth + 1); 3154 break; 3155 } 3156 3157 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3158 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3159 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3160 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3161 if (Opcode == ISD::FSHL) { 3162 Known.One <<= Amt; 3163 Known.Zero <<= Amt; 3164 Known2.One.lshrInPlace(BitWidth - Amt); 3165 Known2.Zero.lshrInPlace(BitWidth - Amt); 3166 } else { 3167 Known.One <<= BitWidth - Amt; 3168 Known.Zero <<= BitWidth - Amt; 3169 Known2.One.lshrInPlace(Amt); 3170 Known2.Zero.lshrInPlace(Amt); 3171 } 3172 Known.One |= Known2.One; 3173 Known.Zero |= Known2.Zero; 3174 } 3175 break; 3176 case ISD::SIGN_EXTEND_INREG: { 3177 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3178 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3179 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3180 break; 3181 } 3182 case ISD::CTTZ: 3183 case ISD::CTTZ_ZERO_UNDEF: { 3184 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3185 // If we have a known 1, its position is our upper bound. 3186 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3187 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3188 Known.Zero.setBitsFrom(LowBits); 3189 break; 3190 } 3191 case ISD::CTLZ: 3192 case ISD::CTLZ_ZERO_UNDEF: { 3193 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3194 // If we have a known 1, its position is our upper bound. 3195 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3196 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3197 Known.Zero.setBitsFrom(LowBits); 3198 break; 3199 } 3200 case ISD::CTPOP: { 3201 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3202 // If we know some of the bits are zero, they can't be one. 3203 unsigned PossibleOnes = Known2.countMaxPopulation(); 3204 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3205 break; 3206 } 3207 case ISD::PARITY: { 3208 // Parity returns 0 everywhere but the LSB. 3209 Known.Zero.setBitsFrom(1); 3210 break; 3211 } 3212 case ISD::LOAD: { 3213 LoadSDNode *LD = cast<LoadSDNode>(Op); 3214 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3215 if (ISD::isNON_EXTLoad(LD) && Cst) { 3216 // Determine any common known bits from the loaded constant pool value. 3217 Type *CstTy = Cst->getType(); 3218 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3219 // If its a vector splat, then we can (quickly) reuse the scalar path. 3220 // NOTE: We assume all elements match and none are UNDEF. 3221 if (CstTy->isVectorTy()) { 3222 if (const Constant *Splat = Cst->getSplatValue()) { 3223 Cst = Splat; 3224 CstTy = Cst->getType(); 3225 } 3226 } 3227 // TODO - do we need to handle different bitwidths? 3228 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3229 // Iterate across all vector elements finding common known bits. 3230 Known.One.setAllBits(); 3231 Known.Zero.setAllBits(); 3232 for (unsigned i = 0; i != NumElts; ++i) { 3233 if (!DemandedElts[i]) 3234 continue; 3235 if (Constant *Elt = Cst->getAggregateElement(i)) { 3236 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3237 const APInt &Value = CInt->getValue(); 3238 Known.One &= Value; 3239 Known.Zero &= ~Value; 3240 continue; 3241 } 3242 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3243 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3244 Known.One &= Value; 3245 Known.Zero &= ~Value; 3246 continue; 3247 } 3248 } 3249 Known.One.clearAllBits(); 3250 Known.Zero.clearAllBits(); 3251 break; 3252 } 3253 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3254 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3255 Known = KnownBits::makeConstant(CInt->getValue()); 3256 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3257 Known = 3258 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3259 } 3260 } 3261 } 3262 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3263 // If this is a ZEXTLoad and we are looking at the loaded value. 3264 EVT VT = LD->getMemoryVT(); 3265 unsigned MemBits = VT.getScalarSizeInBits(); 3266 Known.Zero.setBitsFrom(MemBits); 3267 } else if (const MDNode *Ranges = LD->getRanges()) { 3268 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3269 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3270 } 3271 break; 3272 } 3273 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3274 EVT InVT = Op.getOperand(0).getValueType(); 3275 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3276 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3277 Known = Known.zext(BitWidth); 3278 break; 3279 } 3280 case ISD::ZERO_EXTEND: { 3281 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3282 Known = Known.zext(BitWidth); 3283 break; 3284 } 3285 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3286 EVT InVT = Op.getOperand(0).getValueType(); 3287 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3288 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3289 // If the sign bit is known to be zero or one, then sext will extend 3290 // it to the top bits, else it will just zext. 3291 Known = Known.sext(BitWidth); 3292 break; 3293 } 3294 case ISD::SIGN_EXTEND: { 3295 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3296 // If the sign bit is known to be zero or one, then sext will extend 3297 // it to the top bits, else it will just zext. 3298 Known = Known.sext(BitWidth); 3299 break; 3300 } 3301 case ISD::ANY_EXTEND_VECTOR_INREG: { 3302 EVT InVT = Op.getOperand(0).getValueType(); 3303 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3304 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3305 Known = Known.anyext(BitWidth); 3306 break; 3307 } 3308 case ISD::ANY_EXTEND: { 3309 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3310 Known = Known.anyext(BitWidth); 3311 break; 3312 } 3313 case ISD::TRUNCATE: { 3314 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3315 Known = Known.trunc(BitWidth); 3316 break; 3317 } 3318 case ISD::AssertZext: { 3319 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3320 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3321 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3322 Known.Zero |= (~InMask); 3323 Known.One &= (~Known.Zero); 3324 break; 3325 } 3326 case ISD::AssertAlign: { 3327 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3328 assert(LogOfAlign != 0); 3329 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3330 // well as clearing one bits. 3331 Known.Zero.setLowBits(LogOfAlign); 3332 Known.One.clearLowBits(LogOfAlign); 3333 break; 3334 } 3335 case ISD::FGETSIGN: 3336 // All bits are zero except the low bit. 3337 Known.Zero.setBitsFrom(1); 3338 break; 3339 case ISD::USUBO: 3340 case ISD::SSUBO: 3341 if (Op.getResNo() == 1) { 3342 // If we know the result of a setcc has the top bits zero, use this info. 3343 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3344 TargetLowering::ZeroOrOneBooleanContent && 3345 BitWidth > 1) 3346 Known.Zero.setBitsFrom(1); 3347 break; 3348 } 3349 LLVM_FALLTHROUGH; 3350 case ISD::SUB: 3351 case ISD::SUBC: { 3352 assert(Op.getResNo() == 0 && 3353 "We only compute knownbits for the difference here."); 3354 3355 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3356 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3357 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3358 Known, Known2); 3359 break; 3360 } 3361 case ISD::UADDO: 3362 case ISD::SADDO: 3363 case ISD::ADDCARRY: 3364 if (Op.getResNo() == 1) { 3365 // If we know the result of a setcc has the top bits zero, use this info. 3366 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3367 TargetLowering::ZeroOrOneBooleanContent && 3368 BitWidth > 1) 3369 Known.Zero.setBitsFrom(1); 3370 break; 3371 } 3372 LLVM_FALLTHROUGH; 3373 case ISD::ADD: 3374 case ISD::ADDC: 3375 case ISD::ADDE: { 3376 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3377 3378 // With ADDE and ADDCARRY, a carry bit may be added in. 3379 KnownBits Carry(1); 3380 if (Opcode == ISD::ADDE) 3381 // Can't track carry from glue, set carry to unknown. 3382 Carry.resetAll(); 3383 else if (Opcode == ISD::ADDCARRY) 3384 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3385 // the trouble (how often will we find a known carry bit). And I haven't 3386 // tested this very much yet, but something like this might work: 3387 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3388 // Carry = Carry.zextOrTrunc(1, false); 3389 Carry.resetAll(); 3390 else 3391 Carry.setAllZero(); 3392 3393 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3394 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3395 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3396 break; 3397 } 3398 case ISD::SREM: { 3399 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3400 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3401 Known = KnownBits::srem(Known, Known2); 3402 break; 3403 } 3404 case ISD::UREM: { 3405 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3406 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3407 Known = KnownBits::urem(Known, Known2); 3408 break; 3409 } 3410 case ISD::EXTRACT_ELEMENT: { 3411 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3412 const unsigned Index = Op.getConstantOperandVal(1); 3413 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3414 3415 // Remove low part of known bits mask 3416 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3417 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3418 3419 // Remove high part of known bit mask 3420 Known = Known.trunc(EltBitWidth); 3421 break; 3422 } 3423 case ISD::EXTRACT_VECTOR_ELT: { 3424 SDValue InVec = Op.getOperand(0); 3425 SDValue EltNo = Op.getOperand(1); 3426 EVT VecVT = InVec.getValueType(); 3427 // computeKnownBits not yet implemented for scalable vectors. 3428 if (VecVT.isScalableVector()) 3429 break; 3430 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3431 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3432 3433 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3434 // anything about the extended bits. 3435 if (BitWidth > EltBitWidth) 3436 Known = Known.trunc(EltBitWidth); 3437 3438 // If we know the element index, just demand that vector element, else for 3439 // an unknown element index, ignore DemandedElts and demand them all. 3440 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3441 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3442 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3443 DemandedSrcElts = 3444 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3445 3446 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3447 if (BitWidth > EltBitWidth) 3448 Known = Known.anyext(BitWidth); 3449 break; 3450 } 3451 case ISD::INSERT_VECTOR_ELT: { 3452 // If we know the element index, split the demand between the 3453 // source vector and the inserted element, otherwise assume we need 3454 // the original demanded vector elements and the value. 3455 SDValue InVec = Op.getOperand(0); 3456 SDValue InVal = Op.getOperand(1); 3457 SDValue EltNo = Op.getOperand(2); 3458 bool DemandedVal = true; 3459 APInt DemandedVecElts = DemandedElts; 3460 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3461 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3462 unsigned EltIdx = CEltNo->getZExtValue(); 3463 DemandedVal = !!DemandedElts[EltIdx]; 3464 DemandedVecElts.clearBit(EltIdx); 3465 } 3466 Known.One.setAllBits(); 3467 Known.Zero.setAllBits(); 3468 if (DemandedVal) { 3469 Known2 = computeKnownBits(InVal, Depth + 1); 3470 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3471 } 3472 if (!!DemandedVecElts) { 3473 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3474 Known = KnownBits::commonBits(Known, Known2); 3475 } 3476 break; 3477 } 3478 case ISD::BITREVERSE: { 3479 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3480 Known = Known2.reverseBits(); 3481 break; 3482 } 3483 case ISD::BSWAP: { 3484 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3485 Known = Known2.byteSwap(); 3486 break; 3487 } 3488 case ISD::ABS: { 3489 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3490 Known = Known2.abs(); 3491 break; 3492 } 3493 case ISD::USUBSAT: { 3494 // The result of usubsat will never be larger than the LHS. 3495 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3496 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3497 break; 3498 } 3499 case ISD::UMIN: { 3500 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3501 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3502 Known = KnownBits::umin(Known, Known2); 3503 break; 3504 } 3505 case ISD::UMAX: { 3506 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3507 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3508 Known = KnownBits::umax(Known, Known2); 3509 break; 3510 } 3511 case ISD::SMIN: 3512 case ISD::SMAX: { 3513 // If we have a clamp pattern, we know that the number of sign bits will be 3514 // the minimum of the clamp min/max range. 3515 bool IsMax = (Opcode == ISD::SMAX); 3516 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3517 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3518 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3519 CstHigh = 3520 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3521 if (CstLow && CstHigh) { 3522 if (!IsMax) 3523 std::swap(CstLow, CstHigh); 3524 3525 const APInt &ValueLow = CstLow->getAPIntValue(); 3526 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3527 if (ValueLow.sle(ValueHigh)) { 3528 unsigned LowSignBits = ValueLow.getNumSignBits(); 3529 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3530 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3531 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3532 Known.One.setHighBits(MinSignBits); 3533 break; 3534 } 3535 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3536 Known.Zero.setHighBits(MinSignBits); 3537 break; 3538 } 3539 } 3540 } 3541 3542 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3543 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3544 if (IsMax) 3545 Known = KnownBits::smax(Known, Known2); 3546 else 3547 Known = KnownBits::smin(Known, Known2); 3548 break; 3549 } 3550 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3551 if (Op.getResNo() == 1) { 3552 // The boolean result conforms to getBooleanContents. 3553 // If we know the result of a setcc has the top bits zero, use this info. 3554 // We know that we have an integer-based boolean since these operations 3555 // are only available for integer. 3556 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3557 TargetLowering::ZeroOrOneBooleanContent && 3558 BitWidth > 1) 3559 Known.Zero.setBitsFrom(1); 3560 break; 3561 } 3562 LLVM_FALLTHROUGH; 3563 case ISD::ATOMIC_CMP_SWAP: 3564 case ISD::ATOMIC_SWAP: 3565 case ISD::ATOMIC_LOAD_ADD: 3566 case ISD::ATOMIC_LOAD_SUB: 3567 case ISD::ATOMIC_LOAD_AND: 3568 case ISD::ATOMIC_LOAD_CLR: 3569 case ISD::ATOMIC_LOAD_OR: 3570 case ISD::ATOMIC_LOAD_XOR: 3571 case ISD::ATOMIC_LOAD_NAND: 3572 case ISD::ATOMIC_LOAD_MIN: 3573 case ISD::ATOMIC_LOAD_MAX: 3574 case ISD::ATOMIC_LOAD_UMIN: 3575 case ISD::ATOMIC_LOAD_UMAX: 3576 case ISD::ATOMIC_LOAD: { 3577 unsigned MemBits = 3578 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3579 // If we are looking at the loaded value. 3580 if (Op.getResNo() == 0) { 3581 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3582 Known.Zero.setBitsFrom(MemBits); 3583 } 3584 break; 3585 } 3586 case ISD::FrameIndex: 3587 case ISD::TargetFrameIndex: 3588 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3589 Known, getMachineFunction()); 3590 break; 3591 3592 default: 3593 if (Opcode < ISD::BUILTIN_OP_END) 3594 break; 3595 LLVM_FALLTHROUGH; 3596 case ISD::INTRINSIC_WO_CHAIN: 3597 case ISD::INTRINSIC_W_CHAIN: 3598 case ISD::INTRINSIC_VOID: 3599 // Allow the target to implement this method for its nodes. 3600 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3601 break; 3602 } 3603 3604 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3605 return Known; 3606 } 3607 3608 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3609 SDValue N1) const { 3610 // X + 0 never overflow 3611 if (isNullConstant(N1)) 3612 return OFK_Never; 3613 3614 KnownBits N1Known = computeKnownBits(N1); 3615 if (N1Known.Zero.getBoolValue()) { 3616 KnownBits N0Known = computeKnownBits(N0); 3617 3618 bool overflow; 3619 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3620 if (!overflow) 3621 return OFK_Never; 3622 } 3623 3624 // mulhi + 1 never overflow 3625 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3626 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3627 return OFK_Never; 3628 3629 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3630 KnownBits N0Known = computeKnownBits(N0); 3631 3632 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3633 return OFK_Never; 3634 } 3635 3636 return OFK_Sometime; 3637 } 3638 3639 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3640 EVT OpVT = Val.getValueType(); 3641 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3642 3643 // Is the constant a known power of 2? 3644 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3645 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3646 3647 // A left-shift of a constant one will have exactly one bit set because 3648 // shifting the bit off the end is undefined. 3649 if (Val.getOpcode() == ISD::SHL) { 3650 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3651 if (C && C->getAPIntValue() == 1) 3652 return true; 3653 } 3654 3655 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3656 // one bit set. 3657 if (Val.getOpcode() == ISD::SRL) { 3658 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3659 if (C && C->getAPIntValue().isSignMask()) 3660 return true; 3661 } 3662 3663 // Are all operands of a build vector constant powers of two? 3664 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3665 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3666 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3667 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3668 return false; 3669 })) 3670 return true; 3671 3672 // Is the operand of a splat vector a constant power of two? 3673 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3674 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3675 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3676 return true; 3677 3678 // More could be done here, though the above checks are enough 3679 // to handle some common cases. 3680 3681 // Fall back to computeKnownBits to catch other known cases. 3682 KnownBits Known = computeKnownBits(Val); 3683 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3684 } 3685 3686 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3687 EVT VT = Op.getValueType(); 3688 3689 // TODO: Assume we don't know anything for now. 3690 if (VT.isScalableVector()) 3691 return 1; 3692 3693 APInt DemandedElts = VT.isVector() 3694 ? APInt::getAllOnes(VT.getVectorNumElements()) 3695 : APInt(1, 1); 3696 return ComputeNumSignBits(Op, DemandedElts, Depth); 3697 } 3698 3699 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3700 unsigned Depth) const { 3701 EVT VT = Op.getValueType(); 3702 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3703 unsigned VTBits = VT.getScalarSizeInBits(); 3704 unsigned NumElts = DemandedElts.getBitWidth(); 3705 unsigned Tmp, Tmp2; 3706 unsigned FirstAnswer = 1; 3707 3708 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3709 const APInt &Val = C->getAPIntValue(); 3710 return Val.getNumSignBits(); 3711 } 3712 3713 if (Depth >= MaxRecursionDepth) 3714 return 1; // Limit search depth. 3715 3716 if (!DemandedElts || VT.isScalableVector()) 3717 return 1; // No demanded elts, better to assume we don't know anything. 3718 3719 unsigned Opcode = Op.getOpcode(); 3720 switch (Opcode) { 3721 default: break; 3722 case ISD::AssertSext: 3723 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3724 return VTBits-Tmp+1; 3725 case ISD::AssertZext: 3726 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3727 return VTBits-Tmp; 3728 3729 case ISD::BUILD_VECTOR: 3730 Tmp = VTBits; 3731 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3732 if (!DemandedElts[i]) 3733 continue; 3734 3735 SDValue SrcOp = Op.getOperand(i); 3736 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3737 3738 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3739 if (SrcOp.getValueSizeInBits() != VTBits) { 3740 assert(SrcOp.getValueSizeInBits() > VTBits && 3741 "Expected BUILD_VECTOR implicit truncation"); 3742 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3743 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3744 } 3745 Tmp = std::min(Tmp, Tmp2); 3746 } 3747 return Tmp; 3748 3749 case ISD::VECTOR_SHUFFLE: { 3750 // Collect the minimum number of sign bits that are shared by every vector 3751 // element referenced by the shuffle. 3752 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3753 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3754 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3755 for (unsigned i = 0; i != NumElts; ++i) { 3756 int M = SVN->getMaskElt(i); 3757 if (!DemandedElts[i]) 3758 continue; 3759 // For UNDEF elements, we don't know anything about the common state of 3760 // the shuffle result. 3761 if (M < 0) 3762 return 1; 3763 if ((unsigned)M < NumElts) 3764 DemandedLHS.setBit((unsigned)M % NumElts); 3765 else 3766 DemandedRHS.setBit((unsigned)M % NumElts); 3767 } 3768 Tmp = std::numeric_limits<unsigned>::max(); 3769 if (!!DemandedLHS) 3770 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3771 if (!!DemandedRHS) { 3772 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3773 Tmp = std::min(Tmp, Tmp2); 3774 } 3775 // If we don't know anything, early out and try computeKnownBits fall-back. 3776 if (Tmp == 1) 3777 break; 3778 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3779 return Tmp; 3780 } 3781 3782 case ISD::BITCAST: { 3783 SDValue N0 = Op.getOperand(0); 3784 EVT SrcVT = N0.getValueType(); 3785 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3786 3787 // Ignore bitcasts from unsupported types.. 3788 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3789 break; 3790 3791 // Fast handling of 'identity' bitcasts. 3792 if (VTBits == SrcBits) 3793 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3794 3795 bool IsLE = getDataLayout().isLittleEndian(); 3796 3797 // Bitcast 'large element' scalar/vector to 'small element' vector. 3798 if ((SrcBits % VTBits) == 0) { 3799 assert(VT.isVector() && "Expected bitcast to vector"); 3800 3801 unsigned Scale = SrcBits / VTBits; 3802 APInt SrcDemandedElts = 3803 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3804 3805 // Fast case - sign splat can be simply split across the small elements. 3806 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3807 if (Tmp == SrcBits) 3808 return VTBits; 3809 3810 // Slow case - determine how far the sign extends into each sub-element. 3811 Tmp2 = VTBits; 3812 for (unsigned i = 0; i != NumElts; ++i) 3813 if (DemandedElts[i]) { 3814 unsigned SubOffset = i % Scale; 3815 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3816 SubOffset = SubOffset * VTBits; 3817 if (Tmp <= SubOffset) 3818 return 1; 3819 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3820 } 3821 return Tmp2; 3822 } 3823 break; 3824 } 3825 3826 case ISD::SIGN_EXTEND: 3827 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3828 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3829 case ISD::SIGN_EXTEND_INREG: 3830 // Max of the input and what this extends. 3831 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3832 Tmp = VTBits-Tmp+1; 3833 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3834 return std::max(Tmp, Tmp2); 3835 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3836 SDValue Src = Op.getOperand(0); 3837 EVT SrcVT = Src.getValueType(); 3838 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3839 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3840 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3841 } 3842 case ISD::SRA: 3843 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3844 // SRA X, C -> adds C sign bits. 3845 if (const APInt *ShAmt = 3846 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3847 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3848 return Tmp; 3849 case ISD::SHL: 3850 if (const APInt *ShAmt = 3851 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3852 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3853 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3854 if (ShAmt->ult(Tmp)) 3855 return Tmp - ShAmt->getZExtValue(); 3856 } 3857 break; 3858 case ISD::AND: 3859 case ISD::OR: 3860 case ISD::XOR: // NOT is handled here. 3861 // Logical binary ops preserve the number of sign bits at the worst. 3862 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3863 if (Tmp != 1) { 3864 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3865 FirstAnswer = std::min(Tmp, Tmp2); 3866 // We computed what we know about the sign bits as our first 3867 // answer. Now proceed to the generic code that uses 3868 // computeKnownBits, and pick whichever answer is better. 3869 } 3870 break; 3871 3872 case ISD::SELECT: 3873 case ISD::VSELECT: 3874 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3875 if (Tmp == 1) return 1; // Early out. 3876 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3877 return std::min(Tmp, Tmp2); 3878 case ISD::SELECT_CC: 3879 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3880 if (Tmp == 1) return 1; // Early out. 3881 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3882 return std::min(Tmp, Tmp2); 3883 3884 case ISD::SMIN: 3885 case ISD::SMAX: { 3886 // If we have a clamp pattern, we know that the number of sign bits will be 3887 // the minimum of the clamp min/max range. 3888 bool IsMax = (Opcode == ISD::SMAX); 3889 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3890 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3891 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3892 CstHigh = 3893 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3894 if (CstLow && CstHigh) { 3895 if (!IsMax) 3896 std::swap(CstLow, CstHigh); 3897 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3898 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3899 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3900 return std::min(Tmp, Tmp2); 3901 } 3902 } 3903 3904 // Fallback - just get the minimum number of sign bits of the operands. 3905 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3906 if (Tmp == 1) 3907 return 1; // Early out. 3908 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3909 return std::min(Tmp, Tmp2); 3910 } 3911 case ISD::UMIN: 3912 case ISD::UMAX: 3913 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3914 if (Tmp == 1) 3915 return 1; // Early out. 3916 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3917 return std::min(Tmp, Tmp2); 3918 case ISD::SADDO: 3919 case ISD::UADDO: 3920 case ISD::SSUBO: 3921 case ISD::USUBO: 3922 case ISD::SMULO: 3923 case ISD::UMULO: 3924 if (Op.getResNo() != 1) 3925 break; 3926 // The boolean result conforms to getBooleanContents. Fall through. 3927 // If setcc returns 0/-1, all bits are sign bits. 3928 // We know that we have an integer-based boolean since these operations 3929 // are only available for integer. 3930 if (TLI->getBooleanContents(VT.isVector(), false) == 3931 TargetLowering::ZeroOrNegativeOneBooleanContent) 3932 return VTBits; 3933 break; 3934 case ISD::SETCC: 3935 case ISD::STRICT_FSETCC: 3936 case ISD::STRICT_FSETCCS: { 3937 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3938 // If setcc returns 0/-1, all bits are sign bits. 3939 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3940 TargetLowering::ZeroOrNegativeOneBooleanContent) 3941 return VTBits; 3942 break; 3943 } 3944 case ISD::ROTL: 3945 case ISD::ROTR: 3946 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3947 3948 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 3949 if (Tmp == VTBits) 3950 return VTBits; 3951 3952 if (ConstantSDNode *C = 3953 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 3954 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 3955 3956 // Handle rotate right by N like a rotate left by 32-N. 3957 if (Opcode == ISD::ROTR) 3958 RotAmt = (VTBits - RotAmt) % VTBits; 3959 3960 // If we aren't rotating out all of the known-in sign bits, return the 3961 // number that are left. This handles rotl(sext(x), 1) for example. 3962 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 3963 } 3964 break; 3965 case ISD::ADD: 3966 case ISD::ADDC: 3967 // Add can have at most one carry bit. Thus we know that the output 3968 // is, at worst, one more bit than the inputs. 3969 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3970 if (Tmp == 1) return 1; // Early out. 3971 3972 // Special case decrementing a value (ADD X, -1): 3973 if (ConstantSDNode *CRHS = 3974 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 3975 if (CRHS->isAllOnes()) { 3976 KnownBits Known = 3977 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3978 3979 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3980 // sign bits set. 3981 if ((Known.Zero | 1).isAllOnes()) 3982 return VTBits; 3983 3984 // If we are subtracting one from a positive number, there is no carry 3985 // out of the result. 3986 if (Known.isNonNegative()) 3987 return Tmp; 3988 } 3989 3990 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3991 if (Tmp2 == 1) return 1; // Early out. 3992 return std::min(Tmp, Tmp2) - 1; 3993 case ISD::SUB: 3994 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3995 if (Tmp2 == 1) return 1; // Early out. 3996 3997 // Handle NEG. 3998 if (ConstantSDNode *CLHS = 3999 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4000 if (CLHS->isZero()) { 4001 KnownBits Known = 4002 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4003 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4004 // sign bits set. 4005 if ((Known.Zero | 1).isAllOnes()) 4006 return VTBits; 4007 4008 // If the input is known to be positive (the sign bit is known clear), 4009 // the output of the NEG has the same number of sign bits as the input. 4010 if (Known.isNonNegative()) 4011 return Tmp2; 4012 4013 // Otherwise, we treat this like a SUB. 4014 } 4015 4016 // Sub can have at most one carry bit. Thus we know that the output 4017 // is, at worst, one more bit than the inputs. 4018 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4019 if (Tmp == 1) return 1; // Early out. 4020 return std::min(Tmp, Tmp2) - 1; 4021 case ISD::MUL: { 4022 // The output of the Mul can be at most twice the valid bits in the inputs. 4023 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4024 if (SignBitsOp0 == 1) 4025 break; 4026 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4027 if (SignBitsOp1 == 1) 4028 break; 4029 unsigned OutValidBits = 4030 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4031 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4032 } 4033 case ISD::SREM: 4034 // The sign bit is the LHS's sign bit, except when the result of the 4035 // remainder is zero. The magnitude of the result should be less than or 4036 // equal to the magnitude of the LHS. Therefore, the result should have 4037 // at least as many sign bits as the left hand side. 4038 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4039 case ISD::TRUNCATE: { 4040 // Check if the sign bits of source go down as far as the truncated value. 4041 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4042 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4043 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4044 return NumSrcSignBits - (NumSrcBits - VTBits); 4045 break; 4046 } 4047 case ISD::EXTRACT_ELEMENT: { 4048 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4049 const int BitWidth = Op.getValueSizeInBits(); 4050 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4051 4052 // Get reverse index (starting from 1), Op1 value indexes elements from 4053 // little end. Sign starts at big end. 4054 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4055 4056 // If the sign portion ends in our element the subtraction gives correct 4057 // result. Otherwise it gives either negative or > bitwidth result 4058 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4059 } 4060 case ISD::INSERT_VECTOR_ELT: { 4061 // If we know the element index, split the demand between the 4062 // source vector and the inserted element, otherwise assume we need 4063 // the original demanded vector elements and the value. 4064 SDValue InVec = Op.getOperand(0); 4065 SDValue InVal = Op.getOperand(1); 4066 SDValue EltNo = Op.getOperand(2); 4067 bool DemandedVal = true; 4068 APInt DemandedVecElts = DemandedElts; 4069 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4070 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4071 unsigned EltIdx = CEltNo->getZExtValue(); 4072 DemandedVal = !!DemandedElts[EltIdx]; 4073 DemandedVecElts.clearBit(EltIdx); 4074 } 4075 Tmp = std::numeric_limits<unsigned>::max(); 4076 if (DemandedVal) { 4077 // TODO - handle implicit truncation of inserted elements. 4078 if (InVal.getScalarValueSizeInBits() != VTBits) 4079 break; 4080 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4081 Tmp = std::min(Tmp, Tmp2); 4082 } 4083 if (!!DemandedVecElts) { 4084 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4085 Tmp = std::min(Tmp, Tmp2); 4086 } 4087 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4088 return Tmp; 4089 } 4090 case ISD::EXTRACT_VECTOR_ELT: { 4091 SDValue InVec = Op.getOperand(0); 4092 SDValue EltNo = Op.getOperand(1); 4093 EVT VecVT = InVec.getValueType(); 4094 // ComputeNumSignBits not yet implemented for scalable vectors. 4095 if (VecVT.isScalableVector()) 4096 break; 4097 const unsigned BitWidth = Op.getValueSizeInBits(); 4098 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4099 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4100 4101 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4102 // anything about sign bits. But if the sizes match we can derive knowledge 4103 // about sign bits from the vector operand. 4104 if (BitWidth != EltBitWidth) 4105 break; 4106 4107 // If we know the element index, just demand that vector element, else for 4108 // an unknown element index, ignore DemandedElts and demand them all. 4109 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4110 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4111 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4112 DemandedSrcElts = 4113 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4114 4115 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4116 } 4117 case ISD::EXTRACT_SUBVECTOR: { 4118 // Offset the demanded elts by the subvector index. 4119 SDValue Src = Op.getOperand(0); 4120 // Bail until we can represent demanded elements for scalable vectors. 4121 if (Src.getValueType().isScalableVector()) 4122 break; 4123 uint64_t Idx = Op.getConstantOperandVal(1); 4124 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4125 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4126 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4127 } 4128 case ISD::CONCAT_VECTORS: { 4129 // Determine the minimum number of sign bits across all demanded 4130 // elts of the input vectors. Early out if the result is already 1. 4131 Tmp = std::numeric_limits<unsigned>::max(); 4132 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4133 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4134 unsigned NumSubVectors = Op.getNumOperands(); 4135 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4136 APInt DemandedSub = 4137 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4138 if (!DemandedSub) 4139 continue; 4140 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4141 Tmp = std::min(Tmp, Tmp2); 4142 } 4143 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4144 return Tmp; 4145 } 4146 case ISD::INSERT_SUBVECTOR: { 4147 // Demand any elements from the subvector and the remainder from the src its 4148 // inserted into. 4149 SDValue Src = Op.getOperand(0); 4150 SDValue Sub = Op.getOperand(1); 4151 uint64_t Idx = Op.getConstantOperandVal(2); 4152 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4153 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4154 APInt DemandedSrcElts = DemandedElts; 4155 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4156 4157 Tmp = std::numeric_limits<unsigned>::max(); 4158 if (!!DemandedSubElts) { 4159 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4160 if (Tmp == 1) 4161 return 1; // early-out 4162 } 4163 if (!!DemandedSrcElts) { 4164 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4165 Tmp = std::min(Tmp, Tmp2); 4166 } 4167 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4168 return Tmp; 4169 } 4170 case ISD::ATOMIC_CMP_SWAP: 4171 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4172 case ISD::ATOMIC_SWAP: 4173 case ISD::ATOMIC_LOAD_ADD: 4174 case ISD::ATOMIC_LOAD_SUB: 4175 case ISD::ATOMIC_LOAD_AND: 4176 case ISD::ATOMIC_LOAD_CLR: 4177 case ISD::ATOMIC_LOAD_OR: 4178 case ISD::ATOMIC_LOAD_XOR: 4179 case ISD::ATOMIC_LOAD_NAND: 4180 case ISD::ATOMIC_LOAD_MIN: 4181 case ISD::ATOMIC_LOAD_MAX: 4182 case ISD::ATOMIC_LOAD_UMIN: 4183 case ISD::ATOMIC_LOAD_UMAX: 4184 case ISD::ATOMIC_LOAD: { 4185 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4186 // If we are looking at the loaded value. 4187 if (Op.getResNo() == 0) { 4188 if (Tmp == VTBits) 4189 return 1; // early-out 4190 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4191 return VTBits - Tmp + 1; 4192 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4193 return VTBits - Tmp; 4194 } 4195 break; 4196 } 4197 } 4198 4199 // If we are looking at the loaded value of the SDNode. 4200 if (Op.getResNo() == 0) { 4201 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4202 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4203 unsigned ExtType = LD->getExtensionType(); 4204 switch (ExtType) { 4205 default: break; 4206 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4207 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4208 return VTBits - Tmp + 1; 4209 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4210 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4211 return VTBits - Tmp; 4212 case ISD::NON_EXTLOAD: 4213 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4214 // We only need to handle vectors - computeKnownBits should handle 4215 // scalar cases. 4216 Type *CstTy = Cst->getType(); 4217 if (CstTy->isVectorTy() && 4218 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) { 4219 Tmp = VTBits; 4220 for (unsigned i = 0; i != NumElts; ++i) { 4221 if (!DemandedElts[i]) 4222 continue; 4223 if (Constant *Elt = Cst->getAggregateElement(i)) { 4224 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4225 const APInt &Value = CInt->getValue(); 4226 Tmp = std::min(Tmp, Value.getNumSignBits()); 4227 continue; 4228 } 4229 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4230 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4231 Tmp = std::min(Tmp, Value.getNumSignBits()); 4232 continue; 4233 } 4234 } 4235 // Unknown type. Conservatively assume no bits match sign bit. 4236 return 1; 4237 } 4238 return Tmp; 4239 } 4240 } 4241 break; 4242 } 4243 } 4244 } 4245 4246 // Allow the target to implement this method for its nodes. 4247 if (Opcode >= ISD::BUILTIN_OP_END || 4248 Opcode == ISD::INTRINSIC_WO_CHAIN || 4249 Opcode == ISD::INTRINSIC_W_CHAIN || 4250 Opcode == ISD::INTRINSIC_VOID) { 4251 unsigned NumBits = 4252 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4253 if (NumBits > 1) 4254 FirstAnswer = std::max(FirstAnswer, NumBits); 4255 } 4256 4257 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4258 // use this information. 4259 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4260 4261 APInt Mask; 4262 if (Known.isNonNegative()) { // sign bit is 0 4263 Mask = Known.Zero; 4264 } else if (Known.isNegative()) { // sign bit is 1; 4265 Mask = Known.One; 4266 } else { 4267 // Nothing known. 4268 return FirstAnswer; 4269 } 4270 4271 // Okay, we know that the sign bit in Mask is set. Use CLO to determine 4272 // the number of identical bits in the top of the input value. 4273 Mask <<= Mask.getBitWidth()-VTBits; 4274 return std::max(FirstAnswer, Mask.countLeadingOnes()); 4275 } 4276 4277 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4278 unsigned Depth) const { 4279 // Early out for FREEZE. 4280 if (Op.getOpcode() == ISD::FREEZE) 4281 return true; 4282 4283 // TODO: Assume we don't know anything for now. 4284 EVT VT = Op.getValueType(); 4285 if (VT.isScalableVector()) 4286 return false; 4287 4288 APInt DemandedElts = VT.isVector() 4289 ? APInt::getAllOnes(VT.getVectorNumElements()) 4290 : APInt(1, 1); 4291 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4292 } 4293 4294 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4295 const APInt &DemandedElts, 4296 bool PoisonOnly, 4297 unsigned Depth) const { 4298 unsigned Opcode = Op.getOpcode(); 4299 4300 // Early out for FREEZE. 4301 if (Opcode == ISD::FREEZE) 4302 return true; 4303 4304 if (Depth >= MaxRecursionDepth) 4305 return false; // Limit search depth. 4306 4307 if (isIntOrFPConstant(Op)) 4308 return true; 4309 4310 switch (Opcode) { 4311 case ISD::UNDEF: 4312 return PoisonOnly; 4313 4314 case ISD::BUILD_VECTOR: 4315 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4316 // this shouldn't affect the result. 4317 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4318 if (!DemandedElts[i]) 4319 continue; 4320 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4321 Depth + 1)) 4322 return false; 4323 } 4324 return true; 4325 4326 // TODO: Search for noundef attributes from library functions. 4327 4328 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4329 4330 default: 4331 // Allow the target to implement this method for its nodes. 4332 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4333 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4334 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4335 Op, DemandedElts, *this, PoisonOnly, Depth); 4336 break; 4337 } 4338 4339 return false; 4340 } 4341 4342 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4343 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4344 !isa<ConstantSDNode>(Op.getOperand(1))) 4345 return false; 4346 4347 if (Op.getOpcode() == ISD::OR && 4348 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4349 return false; 4350 4351 return true; 4352 } 4353 4354 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4355 // If we're told that NaNs won't happen, assume they won't. 4356 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4357 return true; 4358 4359 if (Depth >= MaxRecursionDepth) 4360 return false; // Limit search depth. 4361 4362 // TODO: Handle vectors. 4363 // If the value is a constant, we can obviously see if it is a NaN or not. 4364 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4365 return !C->getValueAPF().isNaN() || 4366 (SNaN && !C->getValueAPF().isSignaling()); 4367 } 4368 4369 unsigned Opcode = Op.getOpcode(); 4370 switch (Opcode) { 4371 case ISD::FADD: 4372 case ISD::FSUB: 4373 case ISD::FMUL: 4374 case ISD::FDIV: 4375 case ISD::FREM: 4376 case ISD::FSIN: 4377 case ISD::FCOS: { 4378 if (SNaN) 4379 return true; 4380 // TODO: Need isKnownNeverInfinity 4381 return false; 4382 } 4383 case ISD::FCANONICALIZE: 4384 case ISD::FEXP: 4385 case ISD::FEXP2: 4386 case ISD::FTRUNC: 4387 case ISD::FFLOOR: 4388 case ISD::FCEIL: 4389 case ISD::FROUND: 4390 case ISD::FROUNDEVEN: 4391 case ISD::FRINT: 4392 case ISD::FNEARBYINT: { 4393 if (SNaN) 4394 return true; 4395 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4396 } 4397 case ISD::FABS: 4398 case ISD::FNEG: 4399 case ISD::FCOPYSIGN: { 4400 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4401 } 4402 case ISD::SELECT: 4403 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4404 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4405 case ISD::FP_EXTEND: 4406 case ISD::FP_ROUND: { 4407 if (SNaN) 4408 return true; 4409 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4410 } 4411 case ISD::SINT_TO_FP: 4412 case ISD::UINT_TO_FP: 4413 return true; 4414 case ISD::FMA: 4415 case ISD::FMAD: { 4416 if (SNaN) 4417 return true; 4418 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4419 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4420 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4421 } 4422 case ISD::FSQRT: // Need is known positive 4423 case ISD::FLOG: 4424 case ISD::FLOG2: 4425 case ISD::FLOG10: 4426 case ISD::FPOWI: 4427 case ISD::FPOW: { 4428 if (SNaN) 4429 return true; 4430 // TODO: Refine on operand 4431 return false; 4432 } 4433 case ISD::FMINNUM: 4434 case ISD::FMAXNUM: { 4435 // Only one needs to be known not-nan, since it will be returned if the 4436 // other ends up being one. 4437 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4438 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4439 } 4440 case ISD::FMINNUM_IEEE: 4441 case ISD::FMAXNUM_IEEE: { 4442 if (SNaN) 4443 return true; 4444 // This can return a NaN if either operand is an sNaN, or if both operands 4445 // are NaN. 4446 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4447 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4448 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4449 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4450 } 4451 case ISD::FMINIMUM: 4452 case ISD::FMAXIMUM: { 4453 // TODO: Does this quiet or return the origina NaN as-is? 4454 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4455 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4456 } 4457 case ISD::EXTRACT_VECTOR_ELT: { 4458 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4459 } 4460 default: 4461 if (Opcode >= ISD::BUILTIN_OP_END || 4462 Opcode == ISD::INTRINSIC_WO_CHAIN || 4463 Opcode == ISD::INTRINSIC_W_CHAIN || 4464 Opcode == ISD::INTRINSIC_VOID) { 4465 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4466 } 4467 4468 return false; 4469 } 4470 } 4471 4472 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4473 assert(Op.getValueType().isFloatingPoint() && 4474 "Floating point type expected"); 4475 4476 // If the value is a constant, we can obviously see if it is a zero or not. 4477 // TODO: Add BuildVector support. 4478 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4479 return !C->isZero(); 4480 return false; 4481 } 4482 4483 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4484 assert(!Op.getValueType().isFloatingPoint() && 4485 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4486 4487 // If the value is a constant, we can obviously see if it is a zero or not. 4488 if (ISD::matchUnaryPredicate(Op, 4489 [](ConstantSDNode *C) { return !C->isZero(); })) 4490 return true; 4491 4492 // TODO: Recognize more cases here. 4493 switch (Op.getOpcode()) { 4494 default: break; 4495 case ISD::OR: 4496 if (isKnownNeverZero(Op.getOperand(1)) || 4497 isKnownNeverZero(Op.getOperand(0))) 4498 return true; 4499 break; 4500 } 4501 4502 return false; 4503 } 4504 4505 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4506 // Check the obvious case. 4507 if (A == B) return true; 4508 4509 // For for negative and positive zero. 4510 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4511 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4512 if (CA->isZero() && CB->isZero()) return true; 4513 4514 // Otherwise they may not be equal. 4515 return false; 4516 } 4517 4518 // FIXME: unify with llvm::haveNoCommonBitsSet. 4519 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M) 4520 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4521 assert(A.getValueType() == B.getValueType() && 4522 "Values must have the same type"); 4523 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4524 computeKnownBits(B)); 4525 } 4526 4527 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4528 SelectionDAG &DAG) { 4529 if (cast<ConstantSDNode>(Step)->isZero()) 4530 return DAG.getConstant(0, DL, VT); 4531 4532 return SDValue(); 4533 } 4534 4535 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4536 ArrayRef<SDValue> Ops, 4537 SelectionDAG &DAG) { 4538 int NumOps = Ops.size(); 4539 assert(NumOps != 0 && "Can't build an empty vector!"); 4540 assert(!VT.isScalableVector() && 4541 "BUILD_VECTOR cannot be used with scalable types"); 4542 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4543 "Incorrect element count in BUILD_VECTOR!"); 4544 4545 // BUILD_VECTOR of UNDEFs is UNDEF. 4546 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4547 return DAG.getUNDEF(VT); 4548 4549 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4550 SDValue IdentitySrc; 4551 bool IsIdentity = true; 4552 for (int i = 0; i != NumOps; ++i) { 4553 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4554 Ops[i].getOperand(0).getValueType() != VT || 4555 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4556 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4557 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4558 IsIdentity = false; 4559 break; 4560 } 4561 IdentitySrc = Ops[i].getOperand(0); 4562 } 4563 if (IsIdentity) 4564 return IdentitySrc; 4565 4566 return SDValue(); 4567 } 4568 4569 /// Try to simplify vector concatenation to an input value, undef, or build 4570 /// vector. 4571 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4572 ArrayRef<SDValue> Ops, 4573 SelectionDAG &DAG) { 4574 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4575 assert(llvm::all_of(Ops, 4576 [Ops](SDValue Op) { 4577 return Ops[0].getValueType() == Op.getValueType(); 4578 }) && 4579 "Concatenation of vectors with inconsistent value types!"); 4580 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4581 VT.getVectorElementCount() && 4582 "Incorrect element count in vector concatenation!"); 4583 4584 if (Ops.size() == 1) 4585 return Ops[0]; 4586 4587 // Concat of UNDEFs is UNDEF. 4588 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4589 return DAG.getUNDEF(VT); 4590 4591 // Scan the operands and look for extract operations from a single source 4592 // that correspond to insertion at the same location via this concatenation: 4593 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4594 SDValue IdentitySrc; 4595 bool IsIdentity = true; 4596 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4597 SDValue Op = Ops[i]; 4598 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4599 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4600 Op.getOperand(0).getValueType() != VT || 4601 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4602 Op.getConstantOperandVal(1) != IdentityIndex) { 4603 IsIdentity = false; 4604 break; 4605 } 4606 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4607 "Unexpected identity source vector for concat of extracts"); 4608 IdentitySrc = Op.getOperand(0); 4609 } 4610 if (IsIdentity) { 4611 assert(IdentitySrc && "Failed to set source vector of extracts"); 4612 return IdentitySrc; 4613 } 4614 4615 // The code below this point is only designed to work for fixed width 4616 // vectors, so we bail out for now. 4617 if (VT.isScalableVector()) 4618 return SDValue(); 4619 4620 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4621 // simplified to one big BUILD_VECTOR. 4622 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4623 EVT SVT = VT.getScalarType(); 4624 SmallVector<SDValue, 16> Elts; 4625 for (SDValue Op : Ops) { 4626 EVT OpVT = Op.getValueType(); 4627 if (Op.isUndef()) 4628 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4629 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4630 Elts.append(Op->op_begin(), Op->op_end()); 4631 else 4632 return SDValue(); 4633 } 4634 4635 // BUILD_VECTOR requires all inputs to be of the same type, find the 4636 // maximum type and extend them all. 4637 for (SDValue Op : Elts) 4638 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4639 4640 if (SVT.bitsGT(VT.getScalarType())) { 4641 for (SDValue &Op : Elts) { 4642 if (Op.isUndef()) 4643 Op = DAG.getUNDEF(SVT); 4644 else 4645 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4646 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4647 : DAG.getSExtOrTrunc(Op, DL, SVT); 4648 } 4649 } 4650 4651 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4652 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4653 return V; 4654 } 4655 4656 /// Gets or creates the specified node. 4657 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4658 FoldingSetNodeID ID; 4659 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4660 void *IP = nullptr; 4661 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4662 return SDValue(E, 0); 4663 4664 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4665 getVTList(VT)); 4666 CSEMap.InsertNode(N, IP); 4667 4668 InsertNode(N); 4669 SDValue V = SDValue(N, 0); 4670 NewSDValueDbgMsg(V, "Creating new node: ", this); 4671 return V; 4672 } 4673 4674 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4675 SDValue Operand) { 4676 SDNodeFlags Flags; 4677 if (Inserter) 4678 Flags = Inserter->getFlags(); 4679 return getNode(Opcode, DL, VT, Operand, Flags); 4680 } 4681 4682 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4683 SDValue Operand, const SDNodeFlags Flags) { 4684 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4685 "Operand is DELETED_NODE!"); 4686 // Constant fold unary operations with an integer constant operand. Even 4687 // opaque constant will be folded, because the folding of unary operations 4688 // doesn't create new constants with different values. Nevertheless, the 4689 // opaque flag is preserved during folding to prevent future folding with 4690 // other constants. 4691 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4692 const APInt &Val = C->getAPIntValue(); 4693 switch (Opcode) { 4694 default: break; 4695 case ISD::SIGN_EXTEND: 4696 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4697 C->isTargetOpcode(), C->isOpaque()); 4698 case ISD::TRUNCATE: 4699 if (C->isOpaque()) 4700 break; 4701 LLVM_FALLTHROUGH; 4702 case ISD::ZERO_EXTEND: 4703 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4704 C->isTargetOpcode(), C->isOpaque()); 4705 case ISD::ANY_EXTEND: 4706 // Some targets like RISCV prefer to sign extend some types. 4707 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4708 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4709 C->isTargetOpcode(), C->isOpaque()); 4710 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4711 C->isTargetOpcode(), C->isOpaque()); 4712 case ISD::UINT_TO_FP: 4713 case ISD::SINT_TO_FP: { 4714 APFloat apf(EVTToAPFloatSemantics(VT), 4715 APInt::getZero(VT.getSizeInBits())); 4716 (void)apf.convertFromAPInt(Val, 4717 Opcode==ISD::SINT_TO_FP, 4718 APFloat::rmNearestTiesToEven); 4719 return getConstantFP(apf, DL, VT); 4720 } 4721 case ISD::BITCAST: 4722 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4723 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4724 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4725 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4726 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4727 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4728 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4729 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4730 break; 4731 case ISD::ABS: 4732 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4733 C->isOpaque()); 4734 case ISD::BITREVERSE: 4735 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4736 C->isOpaque()); 4737 case ISD::BSWAP: 4738 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4739 C->isOpaque()); 4740 case ISD::CTPOP: 4741 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4742 C->isOpaque()); 4743 case ISD::CTLZ: 4744 case ISD::CTLZ_ZERO_UNDEF: 4745 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4746 C->isOpaque()); 4747 case ISD::CTTZ: 4748 case ISD::CTTZ_ZERO_UNDEF: 4749 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4750 C->isOpaque()); 4751 case ISD::FP16_TO_FP: { 4752 bool Ignored; 4753 APFloat FPV(APFloat::IEEEhalf(), 4754 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4755 4756 // This can return overflow, underflow, or inexact; we don't care. 4757 // FIXME need to be more flexible about rounding mode. 4758 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4759 APFloat::rmNearestTiesToEven, &Ignored); 4760 return getConstantFP(FPV, DL, VT); 4761 } 4762 case ISD::STEP_VECTOR: { 4763 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4764 return V; 4765 break; 4766 } 4767 } 4768 } 4769 4770 // Constant fold unary operations with a floating point constant operand. 4771 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4772 APFloat V = C->getValueAPF(); // make copy 4773 switch (Opcode) { 4774 case ISD::FNEG: 4775 V.changeSign(); 4776 return getConstantFP(V, DL, VT); 4777 case ISD::FABS: 4778 V.clearSign(); 4779 return getConstantFP(V, DL, VT); 4780 case ISD::FCEIL: { 4781 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4782 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4783 return getConstantFP(V, DL, VT); 4784 break; 4785 } 4786 case ISD::FTRUNC: { 4787 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4788 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4789 return getConstantFP(V, DL, VT); 4790 break; 4791 } 4792 case ISD::FFLOOR: { 4793 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4794 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4795 return getConstantFP(V, DL, VT); 4796 break; 4797 } 4798 case ISD::FP_EXTEND: { 4799 bool ignored; 4800 // This can return overflow, underflow, or inexact; we don't care. 4801 // FIXME need to be more flexible about rounding mode. 4802 (void)V.convert(EVTToAPFloatSemantics(VT), 4803 APFloat::rmNearestTiesToEven, &ignored); 4804 return getConstantFP(V, DL, VT); 4805 } 4806 case ISD::FP_TO_SINT: 4807 case ISD::FP_TO_UINT: { 4808 bool ignored; 4809 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4810 // FIXME need to be more flexible about rounding mode. 4811 APFloat::opStatus s = 4812 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4813 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4814 break; 4815 return getConstant(IntVal, DL, VT); 4816 } 4817 case ISD::BITCAST: 4818 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4819 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4820 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4821 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4822 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4823 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4824 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4825 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4826 break; 4827 case ISD::FP_TO_FP16: { 4828 bool Ignored; 4829 // This can return overflow, underflow, or inexact; we don't care. 4830 // FIXME need to be more flexible about rounding mode. 4831 (void)V.convert(APFloat::IEEEhalf(), 4832 APFloat::rmNearestTiesToEven, &Ignored); 4833 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4834 } 4835 } 4836 } 4837 4838 // Constant fold unary operations with a vector integer or float operand. 4839 switch (Opcode) { 4840 default: 4841 // FIXME: Entirely reasonable to perform folding of other unary 4842 // operations here as the need arises. 4843 break; 4844 case ISD::FNEG: 4845 case ISD::FABS: 4846 case ISD::FCEIL: 4847 case ISD::FTRUNC: 4848 case ISD::FFLOOR: 4849 case ISD::FP_EXTEND: 4850 case ISD::FP_TO_SINT: 4851 case ISD::FP_TO_UINT: 4852 case ISD::TRUNCATE: 4853 case ISD::ANY_EXTEND: 4854 case ISD::ZERO_EXTEND: 4855 case ISD::SIGN_EXTEND: 4856 case ISD::UINT_TO_FP: 4857 case ISD::SINT_TO_FP: 4858 case ISD::ABS: 4859 case ISD::BITREVERSE: 4860 case ISD::BSWAP: 4861 case ISD::CTLZ: 4862 case ISD::CTLZ_ZERO_UNDEF: 4863 case ISD::CTTZ: 4864 case ISD::CTTZ_ZERO_UNDEF: 4865 case ISD::CTPOP: { 4866 SDValue Ops = {Operand}; 4867 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 4868 return Fold; 4869 } 4870 } 4871 4872 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4873 switch (Opcode) { 4874 case ISD::STEP_VECTOR: 4875 assert(VT.isScalableVector() && 4876 "STEP_VECTOR can only be used with scalable types"); 4877 assert(OpOpcode == ISD::TargetConstant && 4878 VT.getVectorElementType() == Operand.getValueType() && 4879 "Unexpected step operand"); 4880 break; 4881 case ISD::FREEZE: 4882 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4883 break; 4884 case ISD::TokenFactor: 4885 case ISD::MERGE_VALUES: 4886 case ISD::CONCAT_VECTORS: 4887 return Operand; // Factor, merge or concat of one node? No need. 4888 case ISD::BUILD_VECTOR: { 4889 // Attempt to simplify BUILD_VECTOR. 4890 SDValue Ops[] = {Operand}; 4891 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4892 return V; 4893 break; 4894 } 4895 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4896 case ISD::FP_EXTEND: 4897 assert(VT.isFloatingPoint() && 4898 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4899 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4900 assert((!VT.isVector() || 4901 VT.getVectorElementCount() == 4902 Operand.getValueType().getVectorElementCount()) && 4903 "Vector element count mismatch!"); 4904 assert(Operand.getValueType().bitsLT(VT) && 4905 "Invalid fpext node, dst < src!"); 4906 if (Operand.isUndef()) 4907 return getUNDEF(VT); 4908 break; 4909 case ISD::FP_TO_SINT: 4910 case ISD::FP_TO_UINT: 4911 if (Operand.isUndef()) 4912 return getUNDEF(VT); 4913 break; 4914 case ISD::SINT_TO_FP: 4915 case ISD::UINT_TO_FP: 4916 // [us]itofp(undef) = 0, because the result value is bounded. 4917 if (Operand.isUndef()) 4918 return getConstantFP(0.0, DL, VT); 4919 break; 4920 case ISD::SIGN_EXTEND: 4921 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4922 "Invalid SIGN_EXTEND!"); 4923 assert(VT.isVector() == Operand.getValueType().isVector() && 4924 "SIGN_EXTEND result type type should be vector iff the operand " 4925 "type is vector!"); 4926 if (Operand.getValueType() == VT) return Operand; // noop extension 4927 assert((!VT.isVector() || 4928 VT.getVectorElementCount() == 4929 Operand.getValueType().getVectorElementCount()) && 4930 "Vector element count mismatch!"); 4931 assert(Operand.getValueType().bitsLT(VT) && 4932 "Invalid sext node, dst < src!"); 4933 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 4934 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4935 if (OpOpcode == ISD::UNDEF) 4936 // sext(undef) = 0, because the top bits will all be the same. 4937 return getConstant(0, DL, VT); 4938 break; 4939 case ISD::ZERO_EXTEND: 4940 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4941 "Invalid ZERO_EXTEND!"); 4942 assert(VT.isVector() == Operand.getValueType().isVector() && 4943 "ZERO_EXTEND result type type should be vector iff the operand " 4944 "type is vector!"); 4945 if (Operand.getValueType() == VT) return Operand; // noop extension 4946 assert((!VT.isVector() || 4947 VT.getVectorElementCount() == 4948 Operand.getValueType().getVectorElementCount()) && 4949 "Vector element count mismatch!"); 4950 assert(Operand.getValueType().bitsLT(VT) && 4951 "Invalid zext node, dst < src!"); 4952 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 4953 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 4954 if (OpOpcode == ISD::UNDEF) 4955 // zext(undef) = 0, because the top bits will be zero. 4956 return getConstant(0, DL, VT); 4957 break; 4958 case ISD::ANY_EXTEND: 4959 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4960 "Invalid ANY_EXTEND!"); 4961 assert(VT.isVector() == Operand.getValueType().isVector() && 4962 "ANY_EXTEND result type type should be vector iff the operand " 4963 "type is vector!"); 4964 if (Operand.getValueType() == VT) return Operand; // noop extension 4965 assert((!VT.isVector() || 4966 VT.getVectorElementCount() == 4967 Operand.getValueType().getVectorElementCount()) && 4968 "Vector element count mismatch!"); 4969 assert(Operand.getValueType().bitsLT(VT) && 4970 "Invalid anyext node, dst < src!"); 4971 4972 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4973 OpOpcode == ISD::ANY_EXTEND) 4974 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 4975 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4976 if (OpOpcode == ISD::UNDEF) 4977 return getUNDEF(VT); 4978 4979 // (ext (trunc x)) -> x 4980 if (OpOpcode == ISD::TRUNCATE) { 4981 SDValue OpOp = Operand.getOperand(0); 4982 if (OpOp.getValueType() == VT) { 4983 transferDbgValues(Operand, OpOp); 4984 return OpOp; 4985 } 4986 } 4987 break; 4988 case ISD::TRUNCATE: 4989 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4990 "Invalid TRUNCATE!"); 4991 assert(VT.isVector() == Operand.getValueType().isVector() && 4992 "TRUNCATE result type type should be vector iff the operand " 4993 "type is vector!"); 4994 if (Operand.getValueType() == VT) return Operand; // noop truncate 4995 assert((!VT.isVector() || 4996 VT.getVectorElementCount() == 4997 Operand.getValueType().getVectorElementCount()) && 4998 "Vector element count mismatch!"); 4999 assert(Operand.getValueType().bitsGT(VT) && 5000 "Invalid truncate node, src < dst!"); 5001 if (OpOpcode == ISD::TRUNCATE) 5002 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5003 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5004 OpOpcode == ISD::ANY_EXTEND) { 5005 // If the source is smaller than the dest, we still need an extend. 5006 if (Operand.getOperand(0).getValueType().getScalarType() 5007 .bitsLT(VT.getScalarType())) 5008 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5009 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5010 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5011 return Operand.getOperand(0); 5012 } 5013 if (OpOpcode == ISD::UNDEF) 5014 return getUNDEF(VT); 5015 break; 5016 case ISD::ANY_EXTEND_VECTOR_INREG: 5017 case ISD::ZERO_EXTEND_VECTOR_INREG: 5018 case ISD::SIGN_EXTEND_VECTOR_INREG: 5019 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5020 assert(Operand.getValueType().bitsLE(VT) && 5021 "The input must be the same size or smaller than the result."); 5022 assert(VT.getVectorMinNumElements() < 5023 Operand.getValueType().getVectorMinNumElements() && 5024 "The destination vector type must have fewer lanes than the input."); 5025 break; 5026 case ISD::ABS: 5027 assert(VT.isInteger() && VT == Operand.getValueType() && 5028 "Invalid ABS!"); 5029 if (OpOpcode == ISD::UNDEF) 5030 return getUNDEF(VT); 5031 break; 5032 case ISD::BSWAP: 5033 assert(VT.isInteger() && VT == Operand.getValueType() && 5034 "Invalid BSWAP!"); 5035 assert((VT.getScalarSizeInBits() % 16 == 0) && 5036 "BSWAP types must be a multiple of 16 bits!"); 5037 if (OpOpcode == ISD::UNDEF) 5038 return getUNDEF(VT); 5039 break; 5040 case ISD::BITREVERSE: 5041 assert(VT.isInteger() && VT == Operand.getValueType() && 5042 "Invalid BITREVERSE!"); 5043 if (OpOpcode == ISD::UNDEF) 5044 return getUNDEF(VT); 5045 break; 5046 case ISD::BITCAST: 5047 // Basic sanity checking. 5048 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5049 "Cannot BITCAST between types of different sizes!"); 5050 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5051 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5052 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5053 if (OpOpcode == ISD::UNDEF) 5054 return getUNDEF(VT); 5055 break; 5056 case ISD::SCALAR_TO_VECTOR: 5057 assert(VT.isVector() && !Operand.getValueType().isVector() && 5058 (VT.getVectorElementType() == Operand.getValueType() || 5059 (VT.getVectorElementType().isInteger() && 5060 Operand.getValueType().isInteger() && 5061 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5062 "Illegal SCALAR_TO_VECTOR node!"); 5063 if (OpOpcode == ISD::UNDEF) 5064 return getUNDEF(VT); 5065 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5066 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5067 isa<ConstantSDNode>(Operand.getOperand(1)) && 5068 Operand.getConstantOperandVal(1) == 0 && 5069 Operand.getOperand(0).getValueType() == VT) 5070 return Operand.getOperand(0); 5071 break; 5072 case ISD::FNEG: 5073 // Negation of an unknown bag of bits is still completely undefined. 5074 if (OpOpcode == ISD::UNDEF) 5075 return getUNDEF(VT); 5076 5077 if (OpOpcode == ISD::FNEG) // --X -> X 5078 return Operand.getOperand(0); 5079 break; 5080 case ISD::FABS: 5081 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5082 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5083 break; 5084 case ISD::VSCALE: 5085 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5086 break; 5087 case ISD::CTPOP: 5088 if (Operand.getValueType().getScalarType() == MVT::i1) 5089 return Operand; 5090 break; 5091 case ISD::CTLZ: 5092 case ISD::CTTZ: 5093 if (Operand.getValueType().getScalarType() == MVT::i1) 5094 return getNOT(DL, Operand, Operand.getValueType()); 5095 break; 5096 case ISD::VECREDUCE_SMIN: 5097 case ISD::VECREDUCE_UMAX: 5098 if (Operand.getValueType().getScalarType() == MVT::i1) 5099 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5100 break; 5101 case ISD::VECREDUCE_SMAX: 5102 case ISD::VECREDUCE_UMIN: 5103 if (Operand.getValueType().getScalarType() == MVT::i1) 5104 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5105 break; 5106 } 5107 5108 SDNode *N; 5109 SDVTList VTs = getVTList(VT); 5110 SDValue Ops[] = {Operand}; 5111 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5112 FoldingSetNodeID ID; 5113 AddNodeIDNode(ID, Opcode, VTs, Ops); 5114 void *IP = nullptr; 5115 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5116 E->intersectFlagsWith(Flags); 5117 return SDValue(E, 0); 5118 } 5119 5120 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5121 N->setFlags(Flags); 5122 createOperands(N, Ops); 5123 CSEMap.InsertNode(N, IP); 5124 } else { 5125 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5126 createOperands(N, Ops); 5127 } 5128 5129 InsertNode(N); 5130 SDValue V = SDValue(N, 0); 5131 NewSDValueDbgMsg(V, "Creating new node: ", this); 5132 return V; 5133 } 5134 5135 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5136 const APInt &C2) { 5137 switch (Opcode) { 5138 case ISD::ADD: return C1 + C2; 5139 case ISD::SUB: return C1 - C2; 5140 case ISD::MUL: return C1 * C2; 5141 case ISD::AND: return C1 & C2; 5142 case ISD::OR: return C1 | C2; 5143 case ISD::XOR: return C1 ^ C2; 5144 case ISD::SHL: return C1 << C2; 5145 case ISD::SRL: return C1.lshr(C2); 5146 case ISD::SRA: return C1.ashr(C2); 5147 case ISD::ROTL: return C1.rotl(C2); 5148 case ISD::ROTR: return C1.rotr(C2); 5149 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5150 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5151 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5152 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5153 case ISD::SADDSAT: return C1.sadd_sat(C2); 5154 case ISD::UADDSAT: return C1.uadd_sat(C2); 5155 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5156 case ISD::USUBSAT: return C1.usub_sat(C2); 5157 case ISD::UDIV: 5158 if (!C2.getBoolValue()) 5159 break; 5160 return C1.udiv(C2); 5161 case ISD::UREM: 5162 if (!C2.getBoolValue()) 5163 break; 5164 return C1.urem(C2); 5165 case ISD::SDIV: 5166 if (!C2.getBoolValue()) 5167 break; 5168 return C1.sdiv(C2); 5169 case ISD::SREM: 5170 if (!C2.getBoolValue()) 5171 break; 5172 return C1.srem(C2); 5173 case ISD::MULHS: { 5174 unsigned FullWidth = C1.getBitWidth() * 2; 5175 APInt C1Ext = C1.sext(FullWidth); 5176 APInt C2Ext = C2.sext(FullWidth); 5177 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5178 } 5179 case ISD::MULHU: { 5180 unsigned FullWidth = C1.getBitWidth() * 2; 5181 APInt C1Ext = C1.zext(FullWidth); 5182 APInt C2Ext = C2.zext(FullWidth); 5183 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5184 } 5185 } 5186 return llvm::None; 5187 } 5188 5189 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5190 const GlobalAddressSDNode *GA, 5191 const SDNode *N2) { 5192 if (GA->getOpcode() != ISD::GlobalAddress) 5193 return SDValue(); 5194 if (!TLI->isOffsetFoldingLegal(GA)) 5195 return SDValue(); 5196 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5197 if (!C2) 5198 return SDValue(); 5199 int64_t Offset = C2->getSExtValue(); 5200 switch (Opcode) { 5201 case ISD::ADD: break; 5202 case ISD::SUB: Offset = -uint64_t(Offset); break; 5203 default: return SDValue(); 5204 } 5205 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5206 GA->getOffset() + uint64_t(Offset)); 5207 } 5208 5209 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5210 switch (Opcode) { 5211 case ISD::SDIV: 5212 case ISD::UDIV: 5213 case ISD::SREM: 5214 case ISD::UREM: { 5215 // If a divisor is zero/undef or any element of a divisor vector is 5216 // zero/undef, the whole op is undef. 5217 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5218 SDValue Divisor = Ops[1]; 5219 if (Divisor.isUndef() || isNullConstant(Divisor)) 5220 return true; 5221 5222 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5223 llvm::any_of(Divisor->op_values(), 5224 [](SDValue V) { return V.isUndef() || 5225 isNullConstant(V); }); 5226 // TODO: Handle signed overflow. 5227 } 5228 // TODO: Handle oversized shifts. 5229 default: 5230 return false; 5231 } 5232 } 5233 5234 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5235 EVT VT, ArrayRef<SDValue> Ops) { 5236 // If the opcode is a target-specific ISD node, there's nothing we can 5237 // do here and the operand rules may not line up with the below, so 5238 // bail early. 5239 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5240 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5241 // foldCONCAT_VECTORS in getNode before this is called. 5242 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5243 return SDValue(); 5244 5245 // For now, the array Ops should only contain two values. 5246 // This enforcement will be removed once this function is merged with 5247 // FoldConstantVectorArithmetic 5248 if (Ops.size() != 2) 5249 return SDValue(); 5250 5251 if (isUndef(Opcode, Ops)) 5252 return getUNDEF(VT); 5253 5254 SDNode *N1 = Ops[0].getNode(); 5255 SDNode *N2 = Ops[1].getNode(); 5256 5257 // Handle the case of two scalars. 5258 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) { 5259 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) { 5260 if (C1->isOpaque() || C2->isOpaque()) 5261 return SDValue(); 5262 5263 Optional<APInt> FoldAttempt = 5264 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5265 if (!FoldAttempt) 5266 return SDValue(); 5267 5268 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5269 assert((!Folded || !VT.isVector()) && 5270 "Can't fold vectors ops with scalar operands"); 5271 return Folded; 5272 } 5273 } 5274 5275 // fold (add Sym, c) -> Sym+c 5276 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1)) 5277 return FoldSymbolOffset(Opcode, VT, GA, N2); 5278 if (TLI->isCommutativeBinOp(Opcode)) 5279 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2)) 5280 return FoldSymbolOffset(Opcode, VT, GA, N1); 5281 5282 // For fixed width vectors, extract each constant element and fold them 5283 // individually. Either input may be an undef value. 5284 bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR || 5285 N1->getOpcode() == ISD::SPLAT_VECTOR; 5286 if (!IsBVOrSV1 && !N1->isUndef()) 5287 return SDValue(); 5288 bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR || 5289 N2->getOpcode() == ISD::SPLAT_VECTOR; 5290 if (!IsBVOrSV2 && !N2->isUndef()) 5291 return SDValue(); 5292 // If both operands are undef, that's handled the same way as scalars. 5293 if (!IsBVOrSV1 && !IsBVOrSV2) 5294 return SDValue(); 5295 5296 EVT SVT = VT.getScalarType(); 5297 EVT LegalSVT = SVT; 5298 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5299 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5300 if (LegalSVT.bitsLT(SVT)) 5301 return SDValue(); 5302 } 5303 5304 SmallVector<SDValue, 4> Outputs; 5305 unsigned NumOps = 0; 5306 if (IsBVOrSV1) 5307 NumOps = std::max(NumOps, N1->getNumOperands()); 5308 if (IsBVOrSV2) 5309 NumOps = std::max(NumOps, N2->getNumOperands()); 5310 assert(NumOps != 0 && "Expected non-zero operands"); 5311 // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need 5312 // one iteration for that. 5313 assert((!VT.isScalableVector() || NumOps == 1) && 5314 "Scalable vector should only have one scalar"); 5315 5316 for (unsigned I = 0; I != NumOps; ++I) { 5317 // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need 5318 // to use operand 0 of the SPLAT_VECTOR for each fixed element. 5319 SDValue V1; 5320 if (N1->getOpcode() == ISD::BUILD_VECTOR) 5321 V1 = N1->getOperand(I); 5322 else if (N1->getOpcode() == ISD::SPLAT_VECTOR) 5323 V1 = N1->getOperand(0); 5324 else 5325 V1 = getUNDEF(SVT); 5326 5327 SDValue V2; 5328 if (N2->getOpcode() == ISD::BUILD_VECTOR) 5329 V2 = N2->getOperand(I); 5330 else if (N2->getOpcode() == ISD::SPLAT_VECTOR) 5331 V2 = N2->getOperand(0); 5332 else 5333 V2 = getUNDEF(SVT); 5334 5335 if (SVT.isInteger()) { 5336 if (V1.getValueType().bitsGT(SVT)) 5337 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1); 5338 if (V2.getValueType().bitsGT(SVT)) 5339 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2); 5340 } 5341 5342 if (V1.getValueType() != SVT || V2.getValueType() != SVT) 5343 return SDValue(); 5344 5345 // Fold one vector element. 5346 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2); 5347 if (LegalSVT != SVT) 5348 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5349 5350 // Scalar folding only succeeded if the result is a constant or UNDEF. 5351 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5352 ScalarResult.getOpcode() != ISD::ConstantFP) 5353 return SDValue(); 5354 Outputs.push_back(ScalarResult); 5355 } 5356 5357 if (N1->getOpcode() == ISD::BUILD_VECTOR || 5358 N2->getOpcode() == ISD::BUILD_VECTOR) { 5359 assert(VT.getVectorNumElements() == Outputs.size() && 5360 "Vector size mismatch!"); 5361 5362 // Build a big vector out of the scalar elements we generated. 5363 return getBuildVector(VT, SDLoc(), Outputs); 5364 } 5365 5366 assert((N1->getOpcode() == ISD::SPLAT_VECTOR || 5367 N2->getOpcode() == ISD::SPLAT_VECTOR) && 5368 "One operand should be a splat vector"); 5369 5370 assert(Outputs.size() == 1 && "Vector size mismatch!"); 5371 return getSplatVector(VT, SDLoc(), Outputs[0]); 5372 } 5373 5374 // TODO: Merge with FoldConstantArithmetic 5375 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 5376 const SDLoc &DL, EVT VT, 5377 ArrayRef<SDValue> Ops, 5378 const SDNodeFlags Flags) { 5379 // If the opcode is a target-specific ISD node, there's nothing we can 5380 // do here and the operand rules may not line up with the below, so 5381 // bail early. 5382 if (Opcode >= ISD::BUILTIN_OP_END) 5383 return SDValue(); 5384 5385 if (isUndef(Opcode, Ops)) 5386 return getUNDEF(VT); 5387 5388 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 5389 if (!VT.isVector()) 5390 return SDValue(); 5391 5392 ElementCount NumElts = VT.getVectorElementCount(); 5393 5394 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5395 return !Op.getValueType().isVector() || 5396 Op.getValueType().getVectorElementCount() == NumElts; 5397 }; 5398 5399 auto IsConstantBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5400 APInt SplatVal; 5401 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 5402 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5403 (BV && BV->isConstant()) || 5404 (Op.getOpcode() == ISD::SPLAT_VECTOR && 5405 ISD::isConstantSplatVector(Op.getNode(), SplatVal)); 5406 }; 5407 5408 // All operands must be vector types with the same number of elements as 5409 // the result type and must be either UNDEF or a build vector of constant 5410 // or UNDEF scalars. 5411 if (!llvm::all_of(Ops, IsConstantBuildVectorSplatVectorOrUndef) || 5412 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5413 return SDValue(); 5414 5415 // If we are comparing vectors, then the result needs to be a i1 boolean 5416 // that is then sign-extended back to the legal result type. 5417 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5418 5419 // Find legal integer scalar type for constant promotion and 5420 // ensure that its scalar size is at least as large as source. 5421 EVT LegalSVT = VT.getScalarType(); 5422 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5423 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5424 if (LegalSVT.bitsLT(VT.getScalarType())) 5425 return SDValue(); 5426 } 5427 5428 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5429 // only have one operand to check. For fixed-length vector types we may have 5430 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5431 unsigned NumOperands = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5432 5433 // Constant fold each scalar lane separately. 5434 SmallVector<SDValue, 4> ScalarResults; 5435 for (unsigned I = 0; I != NumOperands; I++) { 5436 SmallVector<SDValue, 4> ScalarOps; 5437 for (SDValue Op : Ops) { 5438 EVT InSVT = Op.getValueType().getScalarType(); 5439 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5440 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5441 // We've checked that this is UNDEF or a constant of some kind. 5442 if (Op.isUndef()) 5443 ScalarOps.push_back(getUNDEF(InSVT)); 5444 else 5445 ScalarOps.push_back(Op); 5446 continue; 5447 } 5448 5449 SDValue ScalarOp = 5450 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5451 EVT ScalarVT = ScalarOp.getValueType(); 5452 5453 // Build vector (integer) scalar operands may need implicit 5454 // truncation - do this before constant folding. 5455 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5456 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5457 5458 ScalarOps.push_back(ScalarOp); 5459 } 5460 5461 // Constant fold the scalar operands. 5462 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 5463 5464 // Legalize the (integer) scalar constant if necessary. 5465 if (LegalSVT != SVT) 5466 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5467 5468 // Scalar folding only succeeded if the result is a constant or UNDEF. 5469 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5470 ScalarResult.getOpcode() != ISD::ConstantFP) 5471 return SDValue(); 5472 ScalarResults.push_back(ScalarResult); 5473 } 5474 5475 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5476 : getBuildVector(VT, DL, ScalarResults); 5477 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5478 return V; 5479 } 5480 5481 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5482 EVT VT, SDValue N1, SDValue N2) { 5483 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5484 // should. That will require dealing with a potentially non-default 5485 // rounding mode, checking the "opStatus" return value from the APFloat 5486 // math calculations, and possibly other variations. 5487 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 5488 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 5489 if (N1CFP && N2CFP) { 5490 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF(); 5491 switch (Opcode) { 5492 case ISD::FADD: 5493 C1.add(C2, APFloat::rmNearestTiesToEven); 5494 return getConstantFP(C1, DL, VT); 5495 case ISD::FSUB: 5496 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5497 return getConstantFP(C1, DL, VT); 5498 case ISD::FMUL: 5499 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5500 return getConstantFP(C1, DL, VT); 5501 case ISD::FDIV: 5502 C1.divide(C2, APFloat::rmNearestTiesToEven); 5503 return getConstantFP(C1, DL, VT); 5504 case ISD::FREM: 5505 C1.mod(C2); 5506 return getConstantFP(C1, DL, VT); 5507 case ISD::FCOPYSIGN: 5508 C1.copySign(C2); 5509 return getConstantFP(C1, DL, VT); 5510 default: break; 5511 } 5512 } 5513 if (N1CFP && Opcode == ISD::FP_ROUND) { 5514 APFloat C1 = N1CFP->getValueAPF(); // make copy 5515 bool Unused; 5516 // This can return overflow, underflow, or inexact; we don't care. 5517 // FIXME need to be more flexible about rounding mode. 5518 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5519 &Unused); 5520 return getConstantFP(C1, DL, VT); 5521 } 5522 5523 switch (Opcode) { 5524 case ISD::FSUB: 5525 // -0.0 - undef --> undef (consistent with "fneg undef") 5526 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef()) 5527 return getUNDEF(VT); 5528 LLVM_FALLTHROUGH; 5529 5530 case ISD::FADD: 5531 case ISD::FMUL: 5532 case ISD::FDIV: 5533 case ISD::FREM: 5534 // If both operands are undef, the result is undef. If 1 operand is undef, 5535 // the result is NaN. This should match the behavior of the IR optimizer. 5536 if (N1.isUndef() && N2.isUndef()) 5537 return getUNDEF(VT); 5538 if (N1.isUndef() || N2.isUndef()) 5539 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5540 } 5541 return SDValue(); 5542 } 5543 5544 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5545 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5546 5547 // There's no need to assert on a byte-aligned pointer. All pointers are at 5548 // least byte aligned. 5549 if (A == Align(1)) 5550 return Val; 5551 5552 FoldingSetNodeID ID; 5553 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5554 ID.AddInteger(A.value()); 5555 5556 void *IP = nullptr; 5557 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5558 return SDValue(E, 0); 5559 5560 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5561 Val.getValueType(), A); 5562 createOperands(N, {Val}); 5563 5564 CSEMap.InsertNode(N, IP); 5565 InsertNode(N); 5566 5567 SDValue V(N, 0); 5568 NewSDValueDbgMsg(V, "Creating new node: ", this); 5569 return V; 5570 } 5571 5572 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5573 SDValue N1, SDValue N2) { 5574 SDNodeFlags Flags; 5575 if (Inserter) 5576 Flags = Inserter->getFlags(); 5577 return getNode(Opcode, DL, VT, N1, N2, Flags); 5578 } 5579 5580 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5581 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5582 assert(N1.getOpcode() != ISD::DELETED_NODE && 5583 N2.getOpcode() != ISD::DELETED_NODE && 5584 "Operand is DELETED_NODE!"); 5585 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5586 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5587 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5588 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5589 5590 // Canonicalize constant to RHS if commutative. 5591 if (TLI->isCommutativeBinOp(Opcode)) { 5592 if (N1C && !N2C) { 5593 std::swap(N1C, N2C); 5594 std::swap(N1, N2); 5595 } else if (N1CFP && !N2CFP) { 5596 std::swap(N1CFP, N2CFP); 5597 std::swap(N1, N2); 5598 } 5599 } 5600 5601 switch (Opcode) { 5602 default: break; 5603 case ISD::TokenFactor: 5604 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5605 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5606 // Fold trivial token factors. 5607 if (N1.getOpcode() == ISD::EntryToken) return N2; 5608 if (N2.getOpcode() == ISD::EntryToken) return N1; 5609 if (N1 == N2) return N1; 5610 break; 5611 case ISD::BUILD_VECTOR: { 5612 // Attempt to simplify BUILD_VECTOR. 5613 SDValue Ops[] = {N1, N2}; 5614 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5615 return V; 5616 break; 5617 } 5618 case ISD::CONCAT_VECTORS: { 5619 SDValue Ops[] = {N1, N2}; 5620 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5621 return V; 5622 break; 5623 } 5624 case ISD::AND: 5625 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5626 assert(N1.getValueType() == N2.getValueType() && 5627 N1.getValueType() == VT && "Binary operator types must match!"); 5628 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5629 // worth handling here. 5630 if (N2C && N2C->isZero()) 5631 return N2; 5632 if (N2C && N2C->isAllOnes()) // X & -1 -> X 5633 return N1; 5634 break; 5635 case ISD::OR: 5636 case ISD::XOR: 5637 case ISD::ADD: 5638 case ISD::SUB: 5639 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5640 assert(N1.getValueType() == N2.getValueType() && 5641 N1.getValueType() == VT && "Binary operator types must match!"); 5642 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5643 // it's worth handling here. 5644 if (N2C && N2C->isZero()) 5645 return N1; 5646 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5647 VT.getVectorElementType() == MVT::i1) 5648 return getNode(ISD::XOR, DL, VT, N1, N2); 5649 break; 5650 case ISD::MUL: 5651 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5652 assert(N1.getValueType() == N2.getValueType() && 5653 N1.getValueType() == VT && "Binary operator types must match!"); 5654 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5655 return getNode(ISD::AND, DL, VT, N1, N2); 5656 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5657 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5658 const APInt &N2CImm = N2C->getAPIntValue(); 5659 return getVScale(DL, VT, MulImm * N2CImm); 5660 } 5661 break; 5662 case ISD::UDIV: 5663 case ISD::UREM: 5664 case ISD::MULHU: 5665 case ISD::MULHS: 5666 case ISD::SDIV: 5667 case ISD::SREM: 5668 case ISD::SADDSAT: 5669 case ISD::SSUBSAT: 5670 case ISD::UADDSAT: 5671 case ISD::USUBSAT: 5672 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5673 assert(N1.getValueType() == N2.getValueType() && 5674 N1.getValueType() == VT && "Binary operator types must match!"); 5675 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5676 // fold (add_sat x, y) -> (or x, y) for bool types. 5677 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5678 return getNode(ISD::OR, DL, VT, N1, N2); 5679 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5680 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5681 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5682 } 5683 break; 5684 case ISD::SMIN: 5685 case ISD::UMAX: 5686 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5687 assert(N1.getValueType() == N2.getValueType() && 5688 N1.getValueType() == VT && "Binary operator types must match!"); 5689 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5690 return getNode(ISD::OR, DL, VT, N1, N2); 5691 break; 5692 case ISD::SMAX: 5693 case ISD::UMIN: 5694 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5695 assert(N1.getValueType() == N2.getValueType() && 5696 N1.getValueType() == VT && "Binary operator types must match!"); 5697 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5698 return getNode(ISD::AND, DL, VT, N1, N2); 5699 break; 5700 case ISD::FADD: 5701 case ISD::FSUB: 5702 case ISD::FMUL: 5703 case ISD::FDIV: 5704 case ISD::FREM: 5705 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5706 assert(N1.getValueType() == N2.getValueType() && 5707 N1.getValueType() == VT && "Binary operator types must match!"); 5708 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5709 return V; 5710 break; 5711 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5712 assert(N1.getValueType() == VT && 5713 N1.getValueType().isFloatingPoint() && 5714 N2.getValueType().isFloatingPoint() && 5715 "Invalid FCOPYSIGN!"); 5716 break; 5717 case ISD::SHL: 5718 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5719 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5720 const APInt &ShiftImm = N2C->getAPIntValue(); 5721 return getVScale(DL, VT, MulImm << ShiftImm); 5722 } 5723 LLVM_FALLTHROUGH; 5724 case ISD::SRA: 5725 case ISD::SRL: 5726 if (SDValue V = simplifyShift(N1, N2)) 5727 return V; 5728 LLVM_FALLTHROUGH; 5729 case ISD::ROTL: 5730 case ISD::ROTR: 5731 assert(VT == N1.getValueType() && 5732 "Shift operators return type must be the same as their first arg"); 5733 assert(VT.isInteger() && N2.getValueType().isInteger() && 5734 "Shifts only work on integers"); 5735 assert((!VT.isVector() || VT == N2.getValueType()) && 5736 "Vector shift amounts must be in the same as their first arg"); 5737 // Verify that the shift amount VT is big enough to hold valid shift 5738 // amounts. This catches things like trying to shift an i1024 value by an 5739 // i8, which is easy to fall into in generic code that uses 5740 // TLI.getShiftAmount(). 5741 assert(N2.getValueType().getScalarSizeInBits() >= 5742 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5743 "Invalid use of small shift amount with oversized value!"); 5744 5745 // Always fold shifts of i1 values so the code generator doesn't need to 5746 // handle them. Since we know the size of the shift has to be less than the 5747 // size of the value, the shift/rotate count is guaranteed to be zero. 5748 if (VT == MVT::i1) 5749 return N1; 5750 if (N2C && N2C->isZero()) 5751 return N1; 5752 break; 5753 case ISD::FP_ROUND: 5754 assert(VT.isFloatingPoint() && 5755 N1.getValueType().isFloatingPoint() && 5756 VT.bitsLE(N1.getValueType()) && 5757 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5758 "Invalid FP_ROUND!"); 5759 if (N1.getValueType() == VT) return N1; // noop conversion. 5760 break; 5761 case ISD::AssertSext: 5762 case ISD::AssertZext: { 5763 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5764 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5765 assert(VT.isInteger() && EVT.isInteger() && 5766 "Cannot *_EXTEND_INREG FP types"); 5767 assert(!EVT.isVector() && 5768 "AssertSExt/AssertZExt type should be the vector element type " 5769 "rather than the vector type!"); 5770 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5771 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5772 break; 5773 } 5774 case ISD::SIGN_EXTEND_INREG: { 5775 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5776 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5777 assert(VT.isInteger() && EVT.isInteger() && 5778 "Cannot *_EXTEND_INREG FP types"); 5779 assert(EVT.isVector() == VT.isVector() && 5780 "SIGN_EXTEND_INREG type should be vector iff the operand " 5781 "type is vector!"); 5782 assert((!EVT.isVector() || 5783 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5784 "Vector element counts must match in SIGN_EXTEND_INREG"); 5785 assert(EVT.bitsLE(VT) && "Not extending!"); 5786 if (EVT == VT) return N1; // Not actually extending 5787 5788 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5789 unsigned FromBits = EVT.getScalarSizeInBits(); 5790 Val <<= Val.getBitWidth() - FromBits; 5791 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5792 return getConstant(Val, DL, ConstantVT); 5793 }; 5794 5795 if (N1C) { 5796 const APInt &Val = N1C->getAPIntValue(); 5797 return SignExtendInReg(Val, VT); 5798 } 5799 5800 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5801 SmallVector<SDValue, 8> Ops; 5802 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5803 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5804 SDValue Op = N1.getOperand(i); 5805 if (Op.isUndef()) { 5806 Ops.push_back(getUNDEF(OpVT)); 5807 continue; 5808 } 5809 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5810 APInt Val = C->getAPIntValue(); 5811 Ops.push_back(SignExtendInReg(Val, OpVT)); 5812 } 5813 return getBuildVector(VT, DL, Ops); 5814 } 5815 break; 5816 } 5817 case ISD::FP_TO_SINT_SAT: 5818 case ISD::FP_TO_UINT_SAT: { 5819 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 5820 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 5821 assert(N1.getValueType().isVector() == VT.isVector() && 5822 "FP_TO_*INT_SAT type should be vector iff the operand type is " 5823 "vector!"); 5824 assert((!VT.isVector() || VT.getVectorNumElements() == 5825 N1.getValueType().getVectorNumElements()) && 5826 "Vector element counts must match in FP_TO_*INT_SAT"); 5827 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 5828 "Type to saturate to must be a scalar."); 5829 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 5830 "Not extending!"); 5831 break; 5832 } 5833 case ISD::EXTRACT_VECTOR_ELT: 5834 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5835 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5836 element type of the vector."); 5837 5838 // Extract from an undefined value or using an undefined index is undefined. 5839 if (N1.isUndef() || N2.isUndef()) 5840 return getUNDEF(VT); 5841 5842 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5843 // vectors. For scalable vectors we will provide appropriate support for 5844 // dealing with arbitrary indices. 5845 if (N2C && N1.getValueType().isFixedLengthVector() && 5846 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5847 return getUNDEF(VT); 5848 5849 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5850 // expanding copies of large vectors from registers. This only works for 5851 // fixed length vectors, since we need to know the exact number of 5852 // elements. 5853 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5854 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5855 unsigned Factor = 5856 N1.getOperand(0).getValueType().getVectorNumElements(); 5857 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5858 N1.getOperand(N2C->getZExtValue() / Factor), 5859 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5860 } 5861 5862 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5863 // lowering is expanding large vector constants. 5864 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5865 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5866 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5867 N1.getValueType().isFixedLengthVector()) && 5868 "BUILD_VECTOR used for scalable vectors"); 5869 unsigned Index = 5870 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5871 SDValue Elt = N1.getOperand(Index); 5872 5873 if (VT != Elt.getValueType()) 5874 // If the vector element type is not legal, the BUILD_VECTOR operands 5875 // are promoted and implicitly truncated, and the result implicitly 5876 // extended. Make that explicit here. 5877 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5878 5879 return Elt; 5880 } 5881 5882 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5883 // operations are lowered to scalars. 5884 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5885 // If the indices are the same, return the inserted element else 5886 // if the indices are known different, extract the element from 5887 // the original vector. 5888 SDValue N1Op2 = N1.getOperand(2); 5889 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5890 5891 if (N1Op2C && N2C) { 5892 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5893 if (VT == N1.getOperand(1).getValueType()) 5894 return N1.getOperand(1); 5895 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5896 } 5897 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5898 } 5899 } 5900 5901 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5902 // when vector types are scalarized and v1iX is legal. 5903 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5904 // Here we are completely ignoring the extract element index (N2), 5905 // which is fine for fixed width vectors, since any index other than 0 5906 // is undefined anyway. However, this cannot be ignored for scalable 5907 // vectors - in theory we could support this, but we don't want to do this 5908 // without a profitability check. 5909 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5910 N1.getValueType().isFixedLengthVector() && 5911 N1.getValueType().getVectorNumElements() == 1) { 5912 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5913 N1.getOperand(1)); 5914 } 5915 break; 5916 case ISD::EXTRACT_ELEMENT: 5917 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5918 assert(!N1.getValueType().isVector() && !VT.isVector() && 5919 (N1.getValueType().isInteger() == VT.isInteger()) && 5920 N1.getValueType() != VT && 5921 "Wrong types for EXTRACT_ELEMENT!"); 5922 5923 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5924 // 64-bit integers into 32-bit parts. Instead of building the extract of 5925 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5926 if (N1.getOpcode() == ISD::BUILD_PAIR) 5927 return N1.getOperand(N2C->getZExtValue()); 5928 5929 // EXTRACT_ELEMENT of a constant int is also very common. 5930 if (N1C) { 5931 unsigned ElementSize = VT.getSizeInBits(); 5932 unsigned Shift = ElementSize * N2C->getZExtValue(); 5933 const APInt &Val = N1C->getAPIntValue(); 5934 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 5935 } 5936 break; 5937 case ISD::EXTRACT_SUBVECTOR: { 5938 EVT N1VT = N1.getValueType(); 5939 assert(VT.isVector() && N1VT.isVector() && 5940 "Extract subvector VTs must be vectors!"); 5941 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5942 "Extract subvector VTs must have the same element type!"); 5943 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5944 "Cannot extract a scalable vector from a fixed length vector!"); 5945 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5946 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5947 "Extract subvector must be from larger vector to smaller vector!"); 5948 assert(N2C && "Extract subvector index must be a constant"); 5949 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5950 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5951 N1VT.getVectorMinNumElements()) && 5952 "Extract subvector overflow!"); 5953 assert(N2C->getAPIntValue().getBitWidth() == 5954 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5955 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 5956 5957 // Trivial extraction. 5958 if (VT == N1VT) 5959 return N1; 5960 5961 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 5962 if (N1.isUndef()) 5963 return getUNDEF(VT); 5964 5965 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 5966 // the concat have the same type as the extract. 5967 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 5968 VT == N1.getOperand(0).getValueType()) { 5969 unsigned Factor = VT.getVectorMinNumElements(); 5970 return N1.getOperand(N2C->getZExtValue() / Factor); 5971 } 5972 5973 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 5974 // during shuffle legalization. 5975 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 5976 VT == N1.getOperand(1).getValueType()) 5977 return N1.getOperand(1); 5978 break; 5979 } 5980 } 5981 5982 // Perform trivial constant folding. 5983 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 5984 return SV; 5985 5986 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2)) 5987 return V; 5988 5989 // Canonicalize an UNDEF to the RHS, even over a constant. 5990 if (N1.isUndef()) { 5991 if (TLI->isCommutativeBinOp(Opcode)) { 5992 std::swap(N1, N2); 5993 } else { 5994 switch (Opcode) { 5995 case ISD::SIGN_EXTEND_INREG: 5996 case ISD::SUB: 5997 return getUNDEF(VT); // fold op(undef, arg2) -> undef 5998 case ISD::UDIV: 5999 case ISD::SDIV: 6000 case ISD::UREM: 6001 case ISD::SREM: 6002 case ISD::SSUBSAT: 6003 case ISD::USUBSAT: 6004 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6005 } 6006 } 6007 } 6008 6009 // Fold a bunch of operators when the RHS is undef. 6010 if (N2.isUndef()) { 6011 switch (Opcode) { 6012 case ISD::XOR: 6013 if (N1.isUndef()) 6014 // Handle undef ^ undef -> 0 special case. This is a common 6015 // idiom (misuse). 6016 return getConstant(0, DL, VT); 6017 LLVM_FALLTHROUGH; 6018 case ISD::ADD: 6019 case ISD::SUB: 6020 case ISD::UDIV: 6021 case ISD::SDIV: 6022 case ISD::UREM: 6023 case ISD::SREM: 6024 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6025 case ISD::MUL: 6026 case ISD::AND: 6027 case ISD::SSUBSAT: 6028 case ISD::USUBSAT: 6029 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6030 case ISD::OR: 6031 case ISD::SADDSAT: 6032 case ISD::UADDSAT: 6033 return getAllOnesConstant(DL, VT); 6034 } 6035 } 6036 6037 // Memoize this node if possible. 6038 SDNode *N; 6039 SDVTList VTs = getVTList(VT); 6040 SDValue Ops[] = {N1, N2}; 6041 if (VT != MVT::Glue) { 6042 FoldingSetNodeID ID; 6043 AddNodeIDNode(ID, Opcode, VTs, Ops); 6044 void *IP = nullptr; 6045 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6046 E->intersectFlagsWith(Flags); 6047 return SDValue(E, 0); 6048 } 6049 6050 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6051 N->setFlags(Flags); 6052 createOperands(N, Ops); 6053 CSEMap.InsertNode(N, IP); 6054 } else { 6055 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6056 createOperands(N, Ops); 6057 } 6058 6059 InsertNode(N); 6060 SDValue V = SDValue(N, 0); 6061 NewSDValueDbgMsg(V, "Creating new node: ", this); 6062 return V; 6063 } 6064 6065 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6066 SDValue N1, SDValue N2, SDValue N3) { 6067 SDNodeFlags Flags; 6068 if (Inserter) 6069 Flags = Inserter->getFlags(); 6070 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6071 } 6072 6073 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6074 SDValue N1, SDValue N2, SDValue N3, 6075 const SDNodeFlags Flags) { 6076 assert(N1.getOpcode() != ISD::DELETED_NODE && 6077 N2.getOpcode() != ISD::DELETED_NODE && 6078 N3.getOpcode() != ISD::DELETED_NODE && 6079 "Operand is DELETED_NODE!"); 6080 // Perform various simplifications. 6081 switch (Opcode) { 6082 case ISD::FMA: { 6083 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6084 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6085 N3.getValueType() == VT && "FMA types must match!"); 6086 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6087 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6088 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6089 if (N1CFP && N2CFP && N3CFP) { 6090 APFloat V1 = N1CFP->getValueAPF(); 6091 const APFloat &V2 = N2CFP->getValueAPF(); 6092 const APFloat &V3 = N3CFP->getValueAPF(); 6093 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6094 return getConstantFP(V1, DL, VT); 6095 } 6096 break; 6097 } 6098 case ISD::BUILD_VECTOR: { 6099 // Attempt to simplify BUILD_VECTOR. 6100 SDValue Ops[] = {N1, N2, N3}; 6101 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6102 return V; 6103 break; 6104 } 6105 case ISD::CONCAT_VECTORS: { 6106 SDValue Ops[] = {N1, N2, N3}; 6107 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6108 return V; 6109 break; 6110 } 6111 case ISD::SETCC: { 6112 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6113 assert(N1.getValueType() == N2.getValueType() && 6114 "SETCC operands must have the same type!"); 6115 assert(VT.isVector() == N1.getValueType().isVector() && 6116 "SETCC type should be vector iff the operand type is vector!"); 6117 assert((!VT.isVector() || VT.getVectorElementCount() == 6118 N1.getValueType().getVectorElementCount()) && 6119 "SETCC vector element counts must match!"); 6120 // Use FoldSetCC to simplify SETCC's. 6121 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6122 return V; 6123 // Vector constant folding. 6124 SDValue Ops[] = {N1, N2, N3}; 6125 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) { 6126 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6127 return V; 6128 } 6129 break; 6130 } 6131 case ISD::SELECT: 6132 case ISD::VSELECT: 6133 if (SDValue V = simplifySelect(N1, N2, N3)) 6134 return V; 6135 break; 6136 case ISD::VECTOR_SHUFFLE: 6137 llvm_unreachable("should use getVectorShuffle constructor!"); 6138 case ISD::INSERT_VECTOR_ELT: { 6139 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6140 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6141 // for scalable vectors where we will generate appropriate code to 6142 // deal with out-of-bounds cases correctly. 6143 if (N3C && N1.getValueType().isFixedLengthVector() && 6144 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6145 return getUNDEF(VT); 6146 6147 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6148 if (N3.isUndef()) 6149 return getUNDEF(VT); 6150 6151 // If the inserted element is an UNDEF, just use the input vector. 6152 if (N2.isUndef()) 6153 return N1; 6154 6155 break; 6156 } 6157 case ISD::INSERT_SUBVECTOR: { 6158 // Inserting undef into undef is still undef. 6159 if (N1.isUndef() && N2.isUndef()) 6160 return getUNDEF(VT); 6161 6162 EVT N2VT = N2.getValueType(); 6163 assert(VT == N1.getValueType() && 6164 "Dest and insert subvector source types must match!"); 6165 assert(VT.isVector() && N2VT.isVector() && 6166 "Insert subvector VTs must be vectors!"); 6167 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6168 "Cannot insert a scalable vector into a fixed length vector!"); 6169 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6170 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6171 "Insert subvector must be from smaller vector to larger vector!"); 6172 assert(isa<ConstantSDNode>(N3) && 6173 "Insert subvector index must be constant"); 6174 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6175 (N2VT.getVectorMinNumElements() + 6176 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6177 VT.getVectorMinNumElements()) && 6178 "Insert subvector overflow!"); 6179 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6180 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6181 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6182 6183 // Trivial insertion. 6184 if (VT == N2VT) 6185 return N2; 6186 6187 // If this is an insert of an extracted vector into an undef vector, we 6188 // can just use the input to the extract. 6189 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6190 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6191 return N2.getOperand(0); 6192 break; 6193 } 6194 case ISD::BITCAST: 6195 // Fold bit_convert nodes from a type to themselves. 6196 if (N1.getValueType() == VT) 6197 return N1; 6198 break; 6199 } 6200 6201 // Memoize node if it doesn't produce a flag. 6202 SDNode *N; 6203 SDVTList VTs = getVTList(VT); 6204 SDValue Ops[] = {N1, N2, N3}; 6205 if (VT != MVT::Glue) { 6206 FoldingSetNodeID ID; 6207 AddNodeIDNode(ID, Opcode, VTs, Ops); 6208 void *IP = nullptr; 6209 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6210 E->intersectFlagsWith(Flags); 6211 return SDValue(E, 0); 6212 } 6213 6214 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6215 N->setFlags(Flags); 6216 createOperands(N, Ops); 6217 CSEMap.InsertNode(N, IP); 6218 } else { 6219 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6220 createOperands(N, Ops); 6221 } 6222 6223 InsertNode(N); 6224 SDValue V = SDValue(N, 0); 6225 NewSDValueDbgMsg(V, "Creating new node: ", this); 6226 return V; 6227 } 6228 6229 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6230 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6231 SDValue Ops[] = { N1, N2, N3, N4 }; 6232 return getNode(Opcode, DL, VT, Ops); 6233 } 6234 6235 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6236 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6237 SDValue N5) { 6238 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6239 return getNode(Opcode, DL, VT, Ops); 6240 } 6241 6242 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6243 /// the incoming stack arguments to be loaded from the stack. 6244 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6245 SmallVector<SDValue, 8> ArgChains; 6246 6247 // Include the original chain at the beginning of the list. When this is 6248 // used by target LowerCall hooks, this helps legalize find the 6249 // CALLSEQ_BEGIN node. 6250 ArgChains.push_back(Chain); 6251 6252 // Add a chain value for each stack argument. 6253 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 6254 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 6255 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 6256 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6257 if (FI->getIndex() < 0) 6258 ArgChains.push_back(SDValue(L, 1)); 6259 6260 // Build a tokenfactor for all the chains. 6261 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6262 } 6263 6264 /// getMemsetValue - Vectorized representation of the memset value 6265 /// operand. 6266 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6267 const SDLoc &dl) { 6268 assert(!Value.isUndef()); 6269 6270 unsigned NumBits = VT.getScalarSizeInBits(); 6271 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6272 assert(C->getAPIntValue().getBitWidth() == 8); 6273 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6274 if (VT.isInteger()) { 6275 bool IsOpaque = VT.getSizeInBits() > 64 || 6276 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6277 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6278 } 6279 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6280 VT); 6281 } 6282 6283 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6284 EVT IntVT = VT.getScalarType(); 6285 if (!IntVT.isInteger()) 6286 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6287 6288 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6289 if (NumBits > 8) { 6290 // Use a multiplication with 0x010101... to extend the input to the 6291 // required length. 6292 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6293 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6294 DAG.getConstant(Magic, dl, IntVT)); 6295 } 6296 6297 if (VT != Value.getValueType() && !VT.isInteger()) 6298 Value = DAG.getBitcast(VT.getScalarType(), Value); 6299 if (VT != Value.getValueType()) 6300 Value = DAG.getSplatBuildVector(VT, dl, Value); 6301 6302 return Value; 6303 } 6304 6305 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6306 /// used when a memcpy is turned into a memset when the source is a constant 6307 /// string ptr. 6308 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6309 const TargetLowering &TLI, 6310 const ConstantDataArraySlice &Slice) { 6311 // Handle vector with all elements zero. 6312 if (Slice.Array == nullptr) { 6313 if (VT.isInteger()) 6314 return DAG.getConstant(0, dl, VT); 6315 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6316 return DAG.getConstantFP(0.0, dl, VT); 6317 if (VT.isVector()) { 6318 unsigned NumElts = VT.getVectorNumElements(); 6319 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6320 return DAG.getNode(ISD::BITCAST, dl, VT, 6321 DAG.getConstant(0, dl, 6322 EVT::getVectorVT(*DAG.getContext(), 6323 EltVT, NumElts))); 6324 } 6325 llvm_unreachable("Expected type!"); 6326 } 6327 6328 assert(!VT.isVector() && "Can't handle vector type here!"); 6329 unsigned NumVTBits = VT.getSizeInBits(); 6330 unsigned NumVTBytes = NumVTBits / 8; 6331 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6332 6333 APInt Val(NumVTBits, 0); 6334 if (DAG.getDataLayout().isLittleEndian()) { 6335 for (unsigned i = 0; i != NumBytes; ++i) 6336 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6337 } else { 6338 for (unsigned i = 0; i != NumBytes; ++i) 6339 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6340 } 6341 6342 // If the "cost" of materializing the integer immediate is less than the cost 6343 // of a load, then it is cost effective to turn the load into the immediate. 6344 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6345 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6346 return DAG.getConstant(Val, dl, VT); 6347 return SDValue(nullptr, 0); 6348 } 6349 6350 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6351 const SDLoc &DL, 6352 const SDNodeFlags Flags) { 6353 EVT VT = Base.getValueType(); 6354 SDValue Index; 6355 6356 if (Offset.isScalable()) 6357 Index = getVScale(DL, Base.getValueType(), 6358 APInt(Base.getValueSizeInBits().getFixedSize(), 6359 Offset.getKnownMinSize())); 6360 else 6361 Index = getConstant(Offset.getFixedSize(), DL, VT); 6362 6363 return getMemBasePlusOffset(Base, Index, DL, Flags); 6364 } 6365 6366 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6367 const SDLoc &DL, 6368 const SDNodeFlags Flags) { 6369 assert(Offset.getValueType().isInteger()); 6370 EVT BasePtrVT = Ptr.getValueType(); 6371 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6372 } 6373 6374 /// Returns true if memcpy source is constant data. 6375 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6376 uint64_t SrcDelta = 0; 6377 GlobalAddressSDNode *G = nullptr; 6378 if (Src.getOpcode() == ISD::GlobalAddress) 6379 G = cast<GlobalAddressSDNode>(Src); 6380 else if (Src.getOpcode() == ISD::ADD && 6381 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6382 Src.getOperand(1).getOpcode() == ISD::Constant) { 6383 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6384 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6385 } 6386 if (!G) 6387 return false; 6388 6389 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6390 SrcDelta + G->getOffset()); 6391 } 6392 6393 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6394 SelectionDAG &DAG) { 6395 // On Darwin, -Os means optimize for size without hurting performance, so 6396 // only really optimize for size when -Oz (MinSize) is used. 6397 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6398 return MF.getFunction().hasMinSize(); 6399 return DAG.shouldOptForSize(); 6400 } 6401 6402 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6403 SmallVector<SDValue, 32> &OutChains, unsigned From, 6404 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6405 SmallVector<SDValue, 16> &OutStoreChains) { 6406 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6407 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6408 SmallVector<SDValue, 16> GluedLoadChains; 6409 for (unsigned i = From; i < To; ++i) { 6410 OutChains.push_back(OutLoadChains[i]); 6411 GluedLoadChains.push_back(OutLoadChains[i]); 6412 } 6413 6414 // Chain for all loads. 6415 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6416 GluedLoadChains); 6417 6418 for (unsigned i = From; i < To; ++i) { 6419 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6420 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6421 ST->getBasePtr(), ST->getMemoryVT(), 6422 ST->getMemOperand()); 6423 OutChains.push_back(NewStore); 6424 } 6425 } 6426 6427 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6428 SDValue Chain, SDValue Dst, SDValue Src, 6429 uint64_t Size, Align Alignment, 6430 bool isVol, bool AlwaysInline, 6431 MachinePointerInfo DstPtrInfo, 6432 MachinePointerInfo SrcPtrInfo, 6433 const AAMDNodes &AAInfo) { 6434 // Turn a memcpy of undef to nop. 6435 // FIXME: We need to honor volatile even is Src is undef. 6436 if (Src.isUndef()) 6437 return Chain; 6438 6439 // Expand memcpy to a series of load and store ops if the size operand falls 6440 // below a certain threshold. 6441 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6442 // rather than maybe a humongous number of loads and stores. 6443 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6444 const DataLayout &DL = DAG.getDataLayout(); 6445 LLVMContext &C = *DAG.getContext(); 6446 std::vector<EVT> MemOps; 6447 bool DstAlignCanChange = false; 6448 MachineFunction &MF = DAG.getMachineFunction(); 6449 MachineFrameInfo &MFI = MF.getFrameInfo(); 6450 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6451 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6452 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6453 DstAlignCanChange = true; 6454 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6455 if (!SrcAlign || Alignment > *SrcAlign) 6456 SrcAlign = Alignment; 6457 assert(SrcAlign && "SrcAlign must be set"); 6458 ConstantDataArraySlice Slice; 6459 // If marked as volatile, perform a copy even when marked as constant. 6460 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6461 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6462 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6463 const MemOp Op = isZeroConstant 6464 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6465 /*IsZeroMemset*/ true, isVol) 6466 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6467 *SrcAlign, isVol, CopyFromConstant); 6468 if (!TLI.findOptimalMemOpLowering( 6469 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6470 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6471 return SDValue(); 6472 6473 if (DstAlignCanChange) { 6474 Type *Ty = MemOps[0].getTypeForEVT(C); 6475 Align NewAlign = DL.getABITypeAlign(Ty); 6476 6477 // Don't promote to an alignment that would require dynamic stack 6478 // realignment. 6479 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6480 if (!TRI->hasStackRealignment(MF)) 6481 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6482 NewAlign = NewAlign / 2; 6483 6484 if (NewAlign > Alignment) { 6485 // Give the stack frame object a larger alignment if needed. 6486 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6487 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6488 Alignment = NewAlign; 6489 } 6490 } 6491 6492 // Prepare AAInfo for loads/stores after lowering this memcpy. 6493 AAMDNodes NewAAInfo = AAInfo; 6494 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6495 6496 MachineMemOperand::Flags MMOFlags = 6497 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6498 SmallVector<SDValue, 16> OutLoadChains; 6499 SmallVector<SDValue, 16> OutStoreChains; 6500 SmallVector<SDValue, 32> OutChains; 6501 unsigned NumMemOps = MemOps.size(); 6502 uint64_t SrcOff = 0, DstOff = 0; 6503 for (unsigned i = 0; i != NumMemOps; ++i) { 6504 EVT VT = MemOps[i]; 6505 unsigned VTSize = VT.getSizeInBits() / 8; 6506 SDValue Value, Store; 6507 6508 if (VTSize > Size) { 6509 // Issuing an unaligned load / store pair that overlaps with the previous 6510 // pair. Adjust the offset accordingly. 6511 assert(i == NumMemOps-1 && i != 0); 6512 SrcOff -= VTSize - Size; 6513 DstOff -= VTSize - Size; 6514 } 6515 6516 if (CopyFromConstant && 6517 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6518 // It's unlikely a store of a vector immediate can be done in a single 6519 // instruction. It would require a load from a constantpool first. 6520 // We only handle zero vectors here. 6521 // FIXME: Handle other cases where store of vector immediate is done in 6522 // a single instruction. 6523 ConstantDataArraySlice SubSlice; 6524 if (SrcOff < Slice.Length) { 6525 SubSlice = Slice; 6526 SubSlice.move(SrcOff); 6527 } else { 6528 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6529 SubSlice.Array = nullptr; 6530 SubSlice.Offset = 0; 6531 SubSlice.Length = VTSize; 6532 } 6533 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6534 if (Value.getNode()) { 6535 Store = DAG.getStore( 6536 Chain, dl, Value, 6537 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6538 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6539 OutChains.push_back(Store); 6540 } 6541 } 6542 6543 if (!Store.getNode()) { 6544 // The type might not be legal for the target. This should only happen 6545 // if the type is smaller than a legal type, as on PPC, so the right 6546 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6547 // to Load/Store if NVT==VT. 6548 // FIXME does the case above also need this? 6549 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6550 assert(NVT.bitsGE(VT)); 6551 6552 bool isDereferenceable = 6553 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6554 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6555 if (isDereferenceable) 6556 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6557 6558 Value = DAG.getExtLoad( 6559 ISD::EXTLOAD, dl, NVT, Chain, 6560 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6561 SrcPtrInfo.getWithOffset(SrcOff), VT, 6562 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6563 OutLoadChains.push_back(Value.getValue(1)); 6564 6565 Store = DAG.getTruncStore( 6566 Chain, dl, Value, 6567 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6568 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6569 OutStoreChains.push_back(Store); 6570 } 6571 SrcOff += VTSize; 6572 DstOff += VTSize; 6573 Size -= VTSize; 6574 } 6575 6576 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6577 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6578 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6579 6580 if (NumLdStInMemcpy) { 6581 // It may be that memcpy might be converted to memset if it's memcpy 6582 // of constants. In such a case, we won't have loads and stores, but 6583 // just stores. In the absence of loads, there is nothing to gang up. 6584 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6585 // If target does not care, just leave as it. 6586 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6587 OutChains.push_back(OutLoadChains[i]); 6588 OutChains.push_back(OutStoreChains[i]); 6589 } 6590 } else { 6591 // Ld/St less than/equal limit set by target. 6592 if (NumLdStInMemcpy <= GluedLdStLimit) { 6593 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6594 NumLdStInMemcpy, OutLoadChains, 6595 OutStoreChains); 6596 } else { 6597 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6598 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6599 unsigned GlueIter = 0; 6600 6601 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6602 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6603 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6604 6605 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6606 OutLoadChains, OutStoreChains); 6607 GlueIter += GluedLdStLimit; 6608 } 6609 6610 // Residual ld/st. 6611 if (RemainingLdStInMemcpy) { 6612 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6613 RemainingLdStInMemcpy, OutLoadChains, 6614 OutStoreChains); 6615 } 6616 } 6617 } 6618 } 6619 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6620 } 6621 6622 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6623 SDValue Chain, SDValue Dst, SDValue Src, 6624 uint64_t Size, Align Alignment, 6625 bool isVol, bool AlwaysInline, 6626 MachinePointerInfo DstPtrInfo, 6627 MachinePointerInfo SrcPtrInfo, 6628 const AAMDNodes &AAInfo) { 6629 // Turn a memmove of undef to nop. 6630 // FIXME: We need to honor volatile even is Src is undef. 6631 if (Src.isUndef()) 6632 return Chain; 6633 6634 // Expand memmove to a series of load and store ops if the size operand falls 6635 // below a certain threshold. 6636 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6637 const DataLayout &DL = DAG.getDataLayout(); 6638 LLVMContext &C = *DAG.getContext(); 6639 std::vector<EVT> MemOps; 6640 bool DstAlignCanChange = false; 6641 MachineFunction &MF = DAG.getMachineFunction(); 6642 MachineFrameInfo &MFI = MF.getFrameInfo(); 6643 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6644 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6645 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6646 DstAlignCanChange = true; 6647 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6648 if (!SrcAlign || Alignment > *SrcAlign) 6649 SrcAlign = Alignment; 6650 assert(SrcAlign && "SrcAlign must be set"); 6651 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6652 if (!TLI.findOptimalMemOpLowering( 6653 MemOps, Limit, 6654 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6655 /*IsVolatile*/ true), 6656 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6657 MF.getFunction().getAttributes())) 6658 return SDValue(); 6659 6660 if (DstAlignCanChange) { 6661 Type *Ty = MemOps[0].getTypeForEVT(C); 6662 Align NewAlign = DL.getABITypeAlign(Ty); 6663 if (NewAlign > Alignment) { 6664 // Give the stack frame object a larger alignment if needed. 6665 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6666 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6667 Alignment = NewAlign; 6668 } 6669 } 6670 6671 // Prepare AAInfo for loads/stores after lowering this memmove. 6672 AAMDNodes NewAAInfo = AAInfo; 6673 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6674 6675 MachineMemOperand::Flags MMOFlags = 6676 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6677 uint64_t SrcOff = 0, DstOff = 0; 6678 SmallVector<SDValue, 8> LoadValues; 6679 SmallVector<SDValue, 8> LoadChains; 6680 SmallVector<SDValue, 8> OutChains; 6681 unsigned NumMemOps = MemOps.size(); 6682 for (unsigned i = 0; i < NumMemOps; i++) { 6683 EVT VT = MemOps[i]; 6684 unsigned VTSize = VT.getSizeInBits() / 8; 6685 SDValue Value; 6686 6687 bool isDereferenceable = 6688 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6689 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6690 if (isDereferenceable) 6691 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6692 6693 Value = DAG.getLoad( 6694 VT, dl, Chain, 6695 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6696 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6697 LoadValues.push_back(Value); 6698 LoadChains.push_back(Value.getValue(1)); 6699 SrcOff += VTSize; 6700 } 6701 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6702 OutChains.clear(); 6703 for (unsigned i = 0; i < NumMemOps; i++) { 6704 EVT VT = MemOps[i]; 6705 unsigned VTSize = VT.getSizeInBits() / 8; 6706 SDValue Store; 6707 6708 Store = DAG.getStore( 6709 Chain, dl, LoadValues[i], 6710 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6711 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6712 OutChains.push_back(Store); 6713 DstOff += VTSize; 6714 } 6715 6716 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6717 } 6718 6719 /// Lower the call to 'memset' intrinsic function into a series of store 6720 /// operations. 6721 /// 6722 /// \param DAG Selection DAG where lowered code is placed. 6723 /// \param dl Link to corresponding IR location. 6724 /// \param Chain Control flow dependency. 6725 /// \param Dst Pointer to destination memory location. 6726 /// \param Src Value of byte to write into the memory. 6727 /// \param Size Number of bytes to write. 6728 /// \param Alignment Alignment of the destination in bytes. 6729 /// \param isVol True if destination is volatile. 6730 /// \param DstPtrInfo IR information on the memory pointer. 6731 /// \returns New head in the control flow, if lowering was successful, empty 6732 /// SDValue otherwise. 6733 /// 6734 /// The function tries to replace 'llvm.memset' intrinsic with several store 6735 /// operations and value calculation code. This is usually profitable for small 6736 /// memory size. 6737 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6738 SDValue Chain, SDValue Dst, SDValue Src, 6739 uint64_t Size, Align Alignment, bool isVol, 6740 MachinePointerInfo DstPtrInfo, 6741 const AAMDNodes &AAInfo) { 6742 // Turn a memset of undef to nop. 6743 // FIXME: We need to honor volatile even is Src is undef. 6744 if (Src.isUndef()) 6745 return Chain; 6746 6747 // Expand memset to a series of load/store ops if the size operand 6748 // falls below a certain threshold. 6749 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6750 std::vector<EVT> MemOps; 6751 bool DstAlignCanChange = false; 6752 MachineFunction &MF = DAG.getMachineFunction(); 6753 MachineFrameInfo &MFI = MF.getFrameInfo(); 6754 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6755 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6756 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6757 DstAlignCanChange = true; 6758 bool IsZeroVal = 6759 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6760 if (!TLI.findOptimalMemOpLowering( 6761 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6762 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6763 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6764 return SDValue(); 6765 6766 if (DstAlignCanChange) { 6767 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6768 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6769 if (NewAlign > Alignment) { 6770 // Give the stack frame object a larger alignment if needed. 6771 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6772 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6773 Alignment = NewAlign; 6774 } 6775 } 6776 6777 SmallVector<SDValue, 8> OutChains; 6778 uint64_t DstOff = 0; 6779 unsigned NumMemOps = MemOps.size(); 6780 6781 // Find the largest store and generate the bit pattern for it. 6782 EVT LargestVT = MemOps[0]; 6783 for (unsigned i = 1; i < NumMemOps; i++) 6784 if (MemOps[i].bitsGT(LargestVT)) 6785 LargestVT = MemOps[i]; 6786 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6787 6788 // Prepare AAInfo for loads/stores after lowering this memset. 6789 AAMDNodes NewAAInfo = AAInfo; 6790 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6791 6792 for (unsigned i = 0; i < NumMemOps; i++) { 6793 EVT VT = MemOps[i]; 6794 unsigned VTSize = VT.getSizeInBits() / 8; 6795 if (VTSize > Size) { 6796 // Issuing an unaligned load / store pair that overlaps with the previous 6797 // pair. Adjust the offset accordingly. 6798 assert(i == NumMemOps-1 && i != 0); 6799 DstOff -= VTSize - Size; 6800 } 6801 6802 // If this store is smaller than the largest store see whether we can get 6803 // the smaller value for free with a truncate. 6804 SDValue Value = MemSetValue; 6805 if (VT.bitsLT(LargestVT)) { 6806 if (!LargestVT.isVector() && !VT.isVector() && 6807 TLI.isTruncateFree(LargestVT, VT)) 6808 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6809 else 6810 Value = getMemsetValue(Src, VT, DAG, dl); 6811 } 6812 assert(Value.getValueType() == VT && "Value with wrong type."); 6813 SDValue Store = DAG.getStore( 6814 Chain, dl, Value, 6815 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6816 DstPtrInfo.getWithOffset(DstOff), Alignment, 6817 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 6818 NewAAInfo); 6819 OutChains.push_back(Store); 6820 DstOff += VT.getSizeInBits() / 8; 6821 Size -= VTSize; 6822 } 6823 6824 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6825 } 6826 6827 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6828 unsigned AS) { 6829 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6830 // pointer operands can be losslessly bitcasted to pointers of address space 0 6831 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6832 report_fatal_error("cannot lower memory intrinsic in address space " + 6833 Twine(AS)); 6834 } 6835 } 6836 6837 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6838 SDValue Src, SDValue Size, Align Alignment, 6839 bool isVol, bool AlwaysInline, bool isTailCall, 6840 MachinePointerInfo DstPtrInfo, 6841 MachinePointerInfo SrcPtrInfo, 6842 const AAMDNodes &AAInfo) { 6843 // Check to see if we should lower the memcpy to loads and stores first. 6844 // For cases within the target-specified limits, this is the best choice. 6845 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6846 if (ConstantSize) { 6847 // Memcpy with size zero? Just return the original chain. 6848 if (ConstantSize->isZero()) 6849 return Chain; 6850 6851 SDValue Result = getMemcpyLoadsAndStores( 6852 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6853 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6854 if (Result.getNode()) 6855 return Result; 6856 } 6857 6858 // Then check to see if we should lower the memcpy with target-specific 6859 // code. If the target chooses to do this, this is the next best. 6860 if (TSI) { 6861 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6862 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6863 DstPtrInfo, SrcPtrInfo); 6864 if (Result.getNode()) 6865 return Result; 6866 } 6867 6868 // If we really need inline code and the target declined to provide it, 6869 // use a (potentially long) sequence of loads and stores. 6870 if (AlwaysInline) { 6871 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6872 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6873 ConstantSize->getZExtValue(), Alignment, 6874 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 6875 } 6876 6877 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6878 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6879 6880 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6881 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6882 // respect volatile, so they may do things like read or write memory 6883 // beyond the given memory regions. But fixing this isn't easy, and most 6884 // people don't care. 6885 6886 // Emit a library call. 6887 TargetLowering::ArgListTy Args; 6888 TargetLowering::ArgListEntry Entry; 6889 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6890 Entry.Node = Dst; Args.push_back(Entry); 6891 Entry.Node = Src; Args.push_back(Entry); 6892 6893 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6894 Entry.Node = Size; Args.push_back(Entry); 6895 // FIXME: pass in SDLoc 6896 TargetLowering::CallLoweringInfo CLI(*this); 6897 CLI.setDebugLoc(dl) 6898 .setChain(Chain) 6899 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6900 Dst.getValueType().getTypeForEVT(*getContext()), 6901 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6902 TLI->getPointerTy(getDataLayout())), 6903 std::move(Args)) 6904 .setDiscardResult() 6905 .setTailCall(isTailCall); 6906 6907 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6908 return CallResult.second; 6909 } 6910 6911 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6912 SDValue Dst, unsigned DstAlign, 6913 SDValue Src, unsigned SrcAlign, 6914 SDValue Size, Type *SizeTy, 6915 unsigned ElemSz, bool isTailCall, 6916 MachinePointerInfo DstPtrInfo, 6917 MachinePointerInfo SrcPtrInfo) { 6918 // Emit a library call. 6919 TargetLowering::ArgListTy Args; 6920 TargetLowering::ArgListEntry Entry; 6921 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6922 Entry.Node = Dst; 6923 Args.push_back(Entry); 6924 6925 Entry.Node = Src; 6926 Args.push_back(Entry); 6927 6928 Entry.Ty = SizeTy; 6929 Entry.Node = Size; 6930 Args.push_back(Entry); 6931 6932 RTLIB::Libcall LibraryCall = 6933 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6934 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6935 report_fatal_error("Unsupported element size"); 6936 6937 TargetLowering::CallLoweringInfo CLI(*this); 6938 CLI.setDebugLoc(dl) 6939 .setChain(Chain) 6940 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6941 Type::getVoidTy(*getContext()), 6942 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6943 TLI->getPointerTy(getDataLayout())), 6944 std::move(Args)) 6945 .setDiscardResult() 6946 .setTailCall(isTailCall); 6947 6948 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6949 return CallResult.second; 6950 } 6951 6952 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6953 SDValue Src, SDValue Size, Align Alignment, 6954 bool isVol, bool isTailCall, 6955 MachinePointerInfo DstPtrInfo, 6956 MachinePointerInfo SrcPtrInfo, 6957 const AAMDNodes &AAInfo) { 6958 // Check to see if we should lower the memmove to loads and stores first. 6959 // For cases within the target-specified limits, this is the best choice. 6960 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6961 if (ConstantSize) { 6962 // Memmove with size zero? Just return the original chain. 6963 if (ConstantSize->isZero()) 6964 return Chain; 6965 6966 SDValue Result = getMemmoveLoadsAndStores( 6967 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6968 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6969 if (Result.getNode()) 6970 return Result; 6971 } 6972 6973 // Then check to see if we should lower the memmove with target-specific 6974 // code. If the target chooses to do this, this is the next best. 6975 if (TSI) { 6976 SDValue Result = 6977 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 6978 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 6979 if (Result.getNode()) 6980 return Result; 6981 } 6982 6983 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6984 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6985 6986 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 6987 // not be safe. See memcpy above for more details. 6988 6989 // Emit a library call. 6990 TargetLowering::ArgListTy Args; 6991 TargetLowering::ArgListEntry Entry; 6992 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6993 Entry.Node = Dst; Args.push_back(Entry); 6994 Entry.Node = Src; Args.push_back(Entry); 6995 6996 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6997 Entry.Node = Size; Args.push_back(Entry); 6998 // FIXME: pass in SDLoc 6999 TargetLowering::CallLoweringInfo CLI(*this); 7000 CLI.setDebugLoc(dl) 7001 .setChain(Chain) 7002 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7003 Dst.getValueType().getTypeForEVT(*getContext()), 7004 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7005 TLI->getPointerTy(getDataLayout())), 7006 std::move(Args)) 7007 .setDiscardResult() 7008 .setTailCall(isTailCall); 7009 7010 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7011 return CallResult.second; 7012 } 7013 7014 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7015 SDValue Dst, unsigned DstAlign, 7016 SDValue Src, unsigned SrcAlign, 7017 SDValue Size, Type *SizeTy, 7018 unsigned ElemSz, bool isTailCall, 7019 MachinePointerInfo DstPtrInfo, 7020 MachinePointerInfo SrcPtrInfo) { 7021 // Emit a library call. 7022 TargetLowering::ArgListTy Args; 7023 TargetLowering::ArgListEntry Entry; 7024 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7025 Entry.Node = Dst; 7026 Args.push_back(Entry); 7027 7028 Entry.Node = Src; 7029 Args.push_back(Entry); 7030 7031 Entry.Ty = SizeTy; 7032 Entry.Node = Size; 7033 Args.push_back(Entry); 7034 7035 RTLIB::Libcall LibraryCall = 7036 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7037 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7038 report_fatal_error("Unsupported element size"); 7039 7040 TargetLowering::CallLoweringInfo CLI(*this); 7041 CLI.setDebugLoc(dl) 7042 .setChain(Chain) 7043 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7044 Type::getVoidTy(*getContext()), 7045 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7046 TLI->getPointerTy(getDataLayout())), 7047 std::move(Args)) 7048 .setDiscardResult() 7049 .setTailCall(isTailCall); 7050 7051 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7052 return CallResult.second; 7053 } 7054 7055 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7056 SDValue Src, SDValue Size, Align Alignment, 7057 bool isVol, bool isTailCall, 7058 MachinePointerInfo DstPtrInfo, 7059 const AAMDNodes &AAInfo) { 7060 // Check to see if we should lower the memset to stores first. 7061 // For cases within the target-specified limits, this is the best choice. 7062 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7063 if (ConstantSize) { 7064 // Memset with size zero? Just return the original chain. 7065 if (ConstantSize->isZero()) 7066 return Chain; 7067 7068 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7069 ConstantSize->getZExtValue(), Alignment, 7070 isVol, DstPtrInfo, AAInfo); 7071 7072 if (Result.getNode()) 7073 return Result; 7074 } 7075 7076 // Then check to see if we should lower the memset with target-specific 7077 // code. If the target chooses to do this, this is the next best. 7078 if (TSI) { 7079 SDValue Result = TSI->EmitTargetCodeForMemset( 7080 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7081 if (Result.getNode()) 7082 return Result; 7083 } 7084 7085 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7086 7087 // Emit a library call. 7088 TargetLowering::ArgListTy Args; 7089 TargetLowering::ArgListEntry Entry; 7090 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7091 Args.push_back(Entry); 7092 Entry.Node = Src; 7093 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7094 Args.push_back(Entry); 7095 Entry.Node = Size; 7096 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7097 Args.push_back(Entry); 7098 7099 // FIXME: pass in SDLoc 7100 TargetLowering::CallLoweringInfo CLI(*this); 7101 CLI.setDebugLoc(dl) 7102 .setChain(Chain) 7103 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7104 Dst.getValueType().getTypeForEVT(*getContext()), 7105 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7106 TLI->getPointerTy(getDataLayout())), 7107 std::move(Args)) 7108 .setDiscardResult() 7109 .setTailCall(isTailCall); 7110 7111 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7112 return CallResult.second; 7113 } 7114 7115 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7116 SDValue Dst, unsigned DstAlign, 7117 SDValue Value, SDValue Size, Type *SizeTy, 7118 unsigned ElemSz, bool isTailCall, 7119 MachinePointerInfo DstPtrInfo) { 7120 // Emit a library call. 7121 TargetLowering::ArgListTy Args; 7122 TargetLowering::ArgListEntry Entry; 7123 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7124 Entry.Node = Dst; 7125 Args.push_back(Entry); 7126 7127 Entry.Ty = Type::getInt8Ty(*getContext()); 7128 Entry.Node = Value; 7129 Args.push_back(Entry); 7130 7131 Entry.Ty = SizeTy; 7132 Entry.Node = Size; 7133 Args.push_back(Entry); 7134 7135 RTLIB::Libcall LibraryCall = 7136 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7137 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7138 report_fatal_error("Unsupported element size"); 7139 7140 TargetLowering::CallLoweringInfo CLI(*this); 7141 CLI.setDebugLoc(dl) 7142 .setChain(Chain) 7143 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7144 Type::getVoidTy(*getContext()), 7145 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7146 TLI->getPointerTy(getDataLayout())), 7147 std::move(Args)) 7148 .setDiscardResult() 7149 .setTailCall(isTailCall); 7150 7151 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7152 return CallResult.second; 7153 } 7154 7155 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7156 SDVTList VTList, ArrayRef<SDValue> Ops, 7157 MachineMemOperand *MMO) { 7158 FoldingSetNodeID ID; 7159 ID.AddInteger(MemVT.getRawBits()); 7160 AddNodeIDNode(ID, Opcode, VTList, Ops); 7161 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7162 void* IP = nullptr; 7163 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7164 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7165 return SDValue(E, 0); 7166 } 7167 7168 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7169 VTList, MemVT, MMO); 7170 createOperands(N, Ops); 7171 7172 CSEMap.InsertNode(N, IP); 7173 InsertNode(N); 7174 return SDValue(N, 0); 7175 } 7176 7177 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7178 EVT MemVT, SDVTList VTs, SDValue Chain, 7179 SDValue Ptr, SDValue Cmp, SDValue Swp, 7180 MachineMemOperand *MMO) { 7181 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7182 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7183 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7184 7185 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7186 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7187 } 7188 7189 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7190 SDValue Chain, SDValue Ptr, SDValue Val, 7191 MachineMemOperand *MMO) { 7192 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7193 Opcode == ISD::ATOMIC_LOAD_SUB || 7194 Opcode == ISD::ATOMIC_LOAD_AND || 7195 Opcode == ISD::ATOMIC_LOAD_CLR || 7196 Opcode == ISD::ATOMIC_LOAD_OR || 7197 Opcode == ISD::ATOMIC_LOAD_XOR || 7198 Opcode == ISD::ATOMIC_LOAD_NAND || 7199 Opcode == ISD::ATOMIC_LOAD_MIN || 7200 Opcode == ISD::ATOMIC_LOAD_MAX || 7201 Opcode == ISD::ATOMIC_LOAD_UMIN || 7202 Opcode == ISD::ATOMIC_LOAD_UMAX || 7203 Opcode == ISD::ATOMIC_LOAD_FADD || 7204 Opcode == ISD::ATOMIC_LOAD_FSUB || 7205 Opcode == ISD::ATOMIC_SWAP || 7206 Opcode == ISD::ATOMIC_STORE) && 7207 "Invalid Atomic Op"); 7208 7209 EVT VT = Val.getValueType(); 7210 7211 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7212 getVTList(VT, MVT::Other); 7213 SDValue Ops[] = {Chain, Ptr, Val}; 7214 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7215 } 7216 7217 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7218 EVT VT, SDValue Chain, SDValue Ptr, 7219 MachineMemOperand *MMO) { 7220 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7221 7222 SDVTList VTs = getVTList(VT, MVT::Other); 7223 SDValue Ops[] = {Chain, Ptr}; 7224 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7225 } 7226 7227 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7228 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7229 if (Ops.size() == 1) 7230 return Ops[0]; 7231 7232 SmallVector<EVT, 4> VTs; 7233 VTs.reserve(Ops.size()); 7234 for (const SDValue &Op : Ops) 7235 VTs.push_back(Op.getValueType()); 7236 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7237 } 7238 7239 SDValue SelectionDAG::getMemIntrinsicNode( 7240 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7241 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7242 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7243 if (!Size && MemVT.isScalableVector()) 7244 Size = MemoryLocation::UnknownSize; 7245 else if (!Size) 7246 Size = MemVT.getStoreSize(); 7247 7248 MachineFunction &MF = getMachineFunction(); 7249 MachineMemOperand *MMO = 7250 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7251 7252 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7253 } 7254 7255 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7256 SDVTList VTList, 7257 ArrayRef<SDValue> Ops, EVT MemVT, 7258 MachineMemOperand *MMO) { 7259 assert((Opcode == ISD::INTRINSIC_VOID || 7260 Opcode == ISD::INTRINSIC_W_CHAIN || 7261 Opcode == ISD::PREFETCH || 7262 ((int)Opcode <= std::numeric_limits<int>::max() && 7263 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7264 "Opcode is not a memory-accessing opcode!"); 7265 7266 // Memoize the node unless it returns a flag. 7267 MemIntrinsicSDNode *N; 7268 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7269 FoldingSetNodeID ID; 7270 AddNodeIDNode(ID, Opcode, VTList, Ops); 7271 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7272 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7273 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7274 void *IP = nullptr; 7275 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7276 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7277 return SDValue(E, 0); 7278 } 7279 7280 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7281 VTList, MemVT, MMO); 7282 createOperands(N, Ops); 7283 7284 CSEMap.InsertNode(N, IP); 7285 } else { 7286 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7287 VTList, MemVT, MMO); 7288 createOperands(N, Ops); 7289 } 7290 InsertNode(N); 7291 SDValue V(N, 0); 7292 NewSDValueDbgMsg(V, "Creating new node: ", this); 7293 return V; 7294 } 7295 7296 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7297 SDValue Chain, int FrameIndex, 7298 int64_t Size, int64_t Offset) { 7299 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7300 const auto VTs = getVTList(MVT::Other); 7301 SDValue Ops[2] = { 7302 Chain, 7303 getFrameIndex(FrameIndex, 7304 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7305 true)}; 7306 7307 FoldingSetNodeID ID; 7308 AddNodeIDNode(ID, Opcode, VTs, Ops); 7309 ID.AddInteger(FrameIndex); 7310 ID.AddInteger(Size); 7311 ID.AddInteger(Offset); 7312 void *IP = nullptr; 7313 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7314 return SDValue(E, 0); 7315 7316 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7317 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7318 createOperands(N, Ops); 7319 CSEMap.InsertNode(N, IP); 7320 InsertNode(N); 7321 SDValue V(N, 0); 7322 NewSDValueDbgMsg(V, "Creating new node: ", this); 7323 return V; 7324 } 7325 7326 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7327 uint64_t Guid, uint64_t Index, 7328 uint32_t Attr) { 7329 const unsigned Opcode = ISD::PSEUDO_PROBE; 7330 const auto VTs = getVTList(MVT::Other); 7331 SDValue Ops[] = {Chain}; 7332 FoldingSetNodeID ID; 7333 AddNodeIDNode(ID, Opcode, VTs, Ops); 7334 ID.AddInteger(Guid); 7335 ID.AddInteger(Index); 7336 void *IP = nullptr; 7337 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7338 return SDValue(E, 0); 7339 7340 auto *N = newSDNode<PseudoProbeSDNode>( 7341 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7342 createOperands(N, Ops); 7343 CSEMap.InsertNode(N, IP); 7344 InsertNode(N); 7345 SDValue V(N, 0); 7346 NewSDValueDbgMsg(V, "Creating new node: ", this); 7347 return V; 7348 } 7349 7350 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7351 /// MachinePointerInfo record from it. This is particularly useful because the 7352 /// code generator has many cases where it doesn't bother passing in a 7353 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7354 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7355 SelectionDAG &DAG, SDValue Ptr, 7356 int64_t Offset = 0) { 7357 // If this is FI+Offset, we can model it. 7358 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7359 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7360 FI->getIndex(), Offset); 7361 7362 // If this is (FI+Offset1)+Offset2, we can model it. 7363 if (Ptr.getOpcode() != ISD::ADD || 7364 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7365 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7366 return Info; 7367 7368 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7369 return MachinePointerInfo::getFixedStack( 7370 DAG.getMachineFunction(), FI, 7371 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7372 } 7373 7374 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7375 /// MachinePointerInfo record from it. This is particularly useful because the 7376 /// code generator has many cases where it doesn't bother passing in a 7377 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7378 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7379 SelectionDAG &DAG, SDValue Ptr, 7380 SDValue OffsetOp) { 7381 // If the 'Offset' value isn't a constant, we can't handle this. 7382 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7383 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7384 if (OffsetOp.isUndef()) 7385 return InferPointerInfo(Info, DAG, Ptr); 7386 return Info; 7387 } 7388 7389 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7390 EVT VT, const SDLoc &dl, SDValue Chain, 7391 SDValue Ptr, SDValue Offset, 7392 MachinePointerInfo PtrInfo, EVT MemVT, 7393 Align Alignment, 7394 MachineMemOperand::Flags MMOFlags, 7395 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7396 assert(Chain.getValueType() == MVT::Other && 7397 "Invalid chain type"); 7398 7399 MMOFlags |= MachineMemOperand::MOLoad; 7400 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7401 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7402 // clients. 7403 if (PtrInfo.V.isNull()) 7404 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7405 7406 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7407 MachineFunction &MF = getMachineFunction(); 7408 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7409 Alignment, AAInfo, Ranges); 7410 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7411 } 7412 7413 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7414 EVT VT, const SDLoc &dl, SDValue Chain, 7415 SDValue Ptr, SDValue Offset, EVT MemVT, 7416 MachineMemOperand *MMO) { 7417 if (VT == MemVT) { 7418 ExtType = ISD::NON_EXTLOAD; 7419 } else if (ExtType == ISD::NON_EXTLOAD) { 7420 assert(VT == MemVT && "Non-extending load from different memory type!"); 7421 } else { 7422 // Extending load. 7423 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7424 "Should only be an extending load, not truncating!"); 7425 assert(VT.isInteger() == MemVT.isInteger() && 7426 "Cannot convert from FP to Int or Int -> FP!"); 7427 assert(VT.isVector() == MemVT.isVector() && 7428 "Cannot use an ext load to convert to or from a vector!"); 7429 assert((!VT.isVector() || 7430 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7431 "Cannot use an ext load to change the number of vector elements!"); 7432 } 7433 7434 bool Indexed = AM != ISD::UNINDEXED; 7435 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7436 7437 SDVTList VTs = Indexed ? 7438 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7439 SDValue Ops[] = { Chain, Ptr, Offset }; 7440 FoldingSetNodeID ID; 7441 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7442 ID.AddInteger(MemVT.getRawBits()); 7443 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7444 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7445 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7446 void *IP = nullptr; 7447 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7448 cast<LoadSDNode>(E)->refineAlignment(MMO); 7449 return SDValue(E, 0); 7450 } 7451 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7452 ExtType, MemVT, MMO); 7453 createOperands(N, Ops); 7454 7455 CSEMap.InsertNode(N, IP); 7456 InsertNode(N); 7457 SDValue V(N, 0); 7458 NewSDValueDbgMsg(V, "Creating new node: ", this); 7459 return V; 7460 } 7461 7462 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7463 SDValue Ptr, MachinePointerInfo PtrInfo, 7464 MaybeAlign Alignment, 7465 MachineMemOperand::Flags MMOFlags, 7466 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7467 SDValue Undef = getUNDEF(Ptr.getValueType()); 7468 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7469 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7470 } 7471 7472 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7473 SDValue Ptr, MachineMemOperand *MMO) { 7474 SDValue Undef = getUNDEF(Ptr.getValueType()); 7475 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7476 VT, MMO); 7477 } 7478 7479 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7480 EVT VT, SDValue Chain, SDValue Ptr, 7481 MachinePointerInfo PtrInfo, EVT MemVT, 7482 MaybeAlign Alignment, 7483 MachineMemOperand::Flags MMOFlags, 7484 const AAMDNodes &AAInfo) { 7485 SDValue Undef = getUNDEF(Ptr.getValueType()); 7486 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7487 MemVT, Alignment, MMOFlags, AAInfo); 7488 } 7489 7490 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7491 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7492 MachineMemOperand *MMO) { 7493 SDValue Undef = getUNDEF(Ptr.getValueType()); 7494 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7495 MemVT, MMO); 7496 } 7497 7498 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7499 SDValue Base, SDValue Offset, 7500 ISD::MemIndexedMode AM) { 7501 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7502 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7503 // Don't propagate the invariant or dereferenceable flags. 7504 auto MMOFlags = 7505 LD->getMemOperand()->getFlags() & 7506 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7507 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7508 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7509 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7510 } 7511 7512 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7513 SDValue Ptr, MachinePointerInfo PtrInfo, 7514 Align Alignment, 7515 MachineMemOperand::Flags MMOFlags, 7516 const AAMDNodes &AAInfo) { 7517 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7518 7519 MMOFlags |= MachineMemOperand::MOStore; 7520 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7521 7522 if (PtrInfo.V.isNull()) 7523 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7524 7525 MachineFunction &MF = getMachineFunction(); 7526 uint64_t Size = 7527 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7528 MachineMemOperand *MMO = 7529 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7530 return getStore(Chain, dl, Val, Ptr, MMO); 7531 } 7532 7533 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7534 SDValue Ptr, MachineMemOperand *MMO) { 7535 assert(Chain.getValueType() == MVT::Other && 7536 "Invalid chain type"); 7537 EVT VT = Val.getValueType(); 7538 SDVTList VTs = getVTList(MVT::Other); 7539 SDValue Undef = getUNDEF(Ptr.getValueType()); 7540 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7541 FoldingSetNodeID ID; 7542 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7543 ID.AddInteger(VT.getRawBits()); 7544 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7545 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7546 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7547 void *IP = nullptr; 7548 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7549 cast<StoreSDNode>(E)->refineAlignment(MMO); 7550 return SDValue(E, 0); 7551 } 7552 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7553 ISD::UNINDEXED, false, VT, MMO); 7554 createOperands(N, Ops); 7555 7556 CSEMap.InsertNode(N, IP); 7557 InsertNode(N); 7558 SDValue V(N, 0); 7559 NewSDValueDbgMsg(V, "Creating new node: ", this); 7560 return V; 7561 } 7562 7563 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7564 SDValue Ptr, MachinePointerInfo PtrInfo, 7565 EVT SVT, Align Alignment, 7566 MachineMemOperand::Flags MMOFlags, 7567 const AAMDNodes &AAInfo) { 7568 assert(Chain.getValueType() == MVT::Other && 7569 "Invalid chain type"); 7570 7571 MMOFlags |= MachineMemOperand::MOStore; 7572 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7573 7574 if (PtrInfo.V.isNull()) 7575 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7576 7577 MachineFunction &MF = getMachineFunction(); 7578 MachineMemOperand *MMO = MF.getMachineMemOperand( 7579 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7580 Alignment, AAInfo); 7581 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7582 } 7583 7584 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7585 SDValue Ptr, EVT SVT, 7586 MachineMemOperand *MMO) { 7587 EVT VT = Val.getValueType(); 7588 7589 assert(Chain.getValueType() == MVT::Other && 7590 "Invalid chain type"); 7591 if (VT == SVT) 7592 return getStore(Chain, dl, Val, Ptr, MMO); 7593 7594 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7595 "Should only be a truncating store, not extending!"); 7596 assert(VT.isInteger() == SVT.isInteger() && 7597 "Can't do FP-INT conversion!"); 7598 assert(VT.isVector() == SVT.isVector() && 7599 "Cannot use trunc store to convert to or from a vector!"); 7600 assert((!VT.isVector() || 7601 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7602 "Cannot use trunc store to change the number of vector elements!"); 7603 7604 SDVTList VTs = getVTList(MVT::Other); 7605 SDValue Undef = getUNDEF(Ptr.getValueType()); 7606 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7607 FoldingSetNodeID ID; 7608 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7609 ID.AddInteger(SVT.getRawBits()); 7610 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7611 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7612 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7613 void *IP = nullptr; 7614 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7615 cast<StoreSDNode>(E)->refineAlignment(MMO); 7616 return SDValue(E, 0); 7617 } 7618 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7619 ISD::UNINDEXED, true, SVT, MMO); 7620 createOperands(N, Ops); 7621 7622 CSEMap.InsertNode(N, IP); 7623 InsertNode(N); 7624 SDValue V(N, 0); 7625 NewSDValueDbgMsg(V, "Creating new node: ", this); 7626 return V; 7627 } 7628 7629 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7630 SDValue Base, SDValue Offset, 7631 ISD::MemIndexedMode AM) { 7632 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7633 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7634 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7635 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7636 FoldingSetNodeID ID; 7637 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7638 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7639 ID.AddInteger(ST->getRawSubclassData()); 7640 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7641 void *IP = nullptr; 7642 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7643 return SDValue(E, 0); 7644 7645 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7646 ST->isTruncatingStore(), ST->getMemoryVT(), 7647 ST->getMemOperand()); 7648 createOperands(N, Ops); 7649 7650 CSEMap.InsertNode(N, IP); 7651 InsertNode(N); 7652 SDValue V(N, 0); 7653 NewSDValueDbgMsg(V, "Creating new node: ", this); 7654 return V; 7655 } 7656 7657 SDValue SelectionDAG::getLoadVP( 7658 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7659 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7660 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7661 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7662 const MDNode *Ranges, bool IsExpanding) { 7663 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7664 7665 MMOFlags |= MachineMemOperand::MOLoad; 7666 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7667 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7668 // clients. 7669 if (PtrInfo.V.isNull()) 7670 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7671 7672 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7673 MachineFunction &MF = getMachineFunction(); 7674 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7675 Alignment, AAInfo, Ranges); 7676 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7677 MMO, IsExpanding); 7678 } 7679 7680 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7681 ISD::LoadExtType ExtType, EVT VT, 7682 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7683 SDValue Offset, SDValue Mask, SDValue EVL, 7684 EVT MemVT, MachineMemOperand *MMO, 7685 bool IsExpanding) { 7686 if (VT == MemVT) { 7687 ExtType = ISD::NON_EXTLOAD; 7688 } else if (ExtType == ISD::NON_EXTLOAD) { 7689 assert(VT == MemVT && "Non-extending load from different memory type!"); 7690 } else { 7691 // Extending load. 7692 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7693 "Should only be an extending load, not truncating!"); 7694 assert(VT.isInteger() == MemVT.isInteger() && 7695 "Cannot convert from FP to Int or Int -> FP!"); 7696 assert(VT.isVector() == MemVT.isVector() && 7697 "Cannot use an ext load to convert to or from a vector!"); 7698 assert((!VT.isVector() || 7699 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7700 "Cannot use an ext load to change the number of vector elements!"); 7701 } 7702 7703 bool Indexed = AM != ISD::UNINDEXED; 7704 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7705 7706 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7707 : getVTList(VT, MVT::Other); 7708 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7709 FoldingSetNodeID ID; 7710 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7711 ID.AddInteger(VT.getRawBits()); 7712 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7713 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7714 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7715 void *IP = nullptr; 7716 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7717 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7718 return SDValue(E, 0); 7719 } 7720 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7721 ExtType, IsExpanding, MemVT, MMO); 7722 createOperands(N, Ops); 7723 7724 CSEMap.InsertNode(N, IP); 7725 InsertNode(N); 7726 SDValue V(N, 0); 7727 NewSDValueDbgMsg(V, "Creating new node: ", this); 7728 return V; 7729 } 7730 7731 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7732 SDValue Ptr, SDValue Mask, SDValue EVL, 7733 MachinePointerInfo PtrInfo, 7734 MaybeAlign Alignment, 7735 MachineMemOperand::Flags MMOFlags, 7736 const AAMDNodes &AAInfo, const MDNode *Ranges, 7737 bool IsExpanding) { 7738 SDValue Undef = getUNDEF(Ptr.getValueType()); 7739 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7740 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7741 IsExpanding); 7742 } 7743 7744 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7745 SDValue Ptr, SDValue Mask, SDValue EVL, 7746 MachineMemOperand *MMO, bool IsExpanding) { 7747 SDValue Undef = getUNDEF(Ptr.getValueType()); 7748 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7749 Mask, EVL, VT, MMO, IsExpanding); 7750 } 7751 7752 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7753 EVT VT, SDValue Chain, SDValue Ptr, 7754 SDValue Mask, SDValue EVL, 7755 MachinePointerInfo PtrInfo, EVT MemVT, 7756 MaybeAlign Alignment, 7757 MachineMemOperand::Flags MMOFlags, 7758 const AAMDNodes &AAInfo, bool IsExpanding) { 7759 SDValue Undef = getUNDEF(Ptr.getValueType()); 7760 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7761 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7762 IsExpanding); 7763 } 7764 7765 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7766 EVT VT, SDValue Chain, SDValue Ptr, 7767 SDValue Mask, SDValue EVL, EVT MemVT, 7768 MachineMemOperand *MMO, bool IsExpanding) { 7769 SDValue Undef = getUNDEF(Ptr.getValueType()); 7770 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7771 EVL, MemVT, MMO, IsExpanding); 7772 } 7773 7774 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7775 SDValue Base, SDValue Offset, 7776 ISD::MemIndexedMode AM) { 7777 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7778 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7779 // Don't propagate the invariant or dereferenceable flags. 7780 auto MMOFlags = 7781 LD->getMemOperand()->getFlags() & 7782 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7783 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7784 LD->getChain(), Base, Offset, LD->getMask(), 7785 LD->getVectorLength(), LD->getPointerInfo(), 7786 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7787 nullptr, LD->isExpandingLoad()); 7788 } 7789 7790 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7791 SDValue Ptr, SDValue Mask, SDValue EVL, 7792 MachinePointerInfo PtrInfo, Align Alignment, 7793 MachineMemOperand::Flags MMOFlags, 7794 const AAMDNodes &AAInfo, bool IsCompressing) { 7795 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7796 7797 MMOFlags |= MachineMemOperand::MOStore; 7798 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7799 7800 if (PtrInfo.V.isNull()) 7801 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7802 7803 MachineFunction &MF = getMachineFunction(); 7804 uint64_t Size = 7805 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7806 MachineMemOperand *MMO = 7807 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7808 return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing); 7809 } 7810 7811 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7812 SDValue Ptr, SDValue Mask, SDValue EVL, 7813 MachineMemOperand *MMO, bool IsCompressing) { 7814 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7815 EVT VT = Val.getValueType(); 7816 SDVTList VTs = getVTList(MVT::Other); 7817 SDValue Undef = getUNDEF(Ptr.getValueType()); 7818 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 7819 FoldingSetNodeID ID; 7820 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7821 ID.AddInteger(VT.getRawBits()); 7822 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7823 dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO)); 7824 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7825 void *IP = nullptr; 7826 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7827 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7828 return SDValue(E, 0); 7829 } 7830 auto *N = 7831 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7832 ISD::UNINDEXED, false, IsCompressing, VT, MMO); 7833 createOperands(N, Ops); 7834 7835 CSEMap.InsertNode(N, IP); 7836 InsertNode(N); 7837 SDValue V(N, 0); 7838 NewSDValueDbgMsg(V, "Creating new node: ", this); 7839 return V; 7840 } 7841 7842 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7843 SDValue Val, SDValue Ptr, SDValue Mask, 7844 SDValue EVL, MachinePointerInfo PtrInfo, 7845 EVT SVT, Align Alignment, 7846 MachineMemOperand::Flags MMOFlags, 7847 const AAMDNodes &AAInfo, 7848 bool IsCompressing) { 7849 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7850 7851 MMOFlags |= MachineMemOperand::MOStore; 7852 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7853 7854 if (PtrInfo.V.isNull()) 7855 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7856 7857 MachineFunction &MF = getMachineFunction(); 7858 MachineMemOperand *MMO = MF.getMachineMemOperand( 7859 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7860 Alignment, AAInfo); 7861 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 7862 IsCompressing); 7863 } 7864 7865 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7866 SDValue Val, SDValue Ptr, SDValue Mask, 7867 SDValue EVL, EVT SVT, 7868 MachineMemOperand *MMO, 7869 bool IsCompressing) { 7870 EVT VT = Val.getValueType(); 7871 7872 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7873 if (VT == SVT) 7874 return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing); 7875 7876 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7877 "Should only be a truncating store, not extending!"); 7878 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 7879 assert(VT.isVector() == SVT.isVector() && 7880 "Cannot use trunc store to convert to or from a vector!"); 7881 assert((!VT.isVector() || 7882 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7883 "Cannot use trunc store to change the number of vector elements!"); 7884 7885 SDVTList VTs = getVTList(MVT::Other); 7886 SDValue Undef = getUNDEF(Ptr.getValueType()); 7887 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 7888 FoldingSetNodeID ID; 7889 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7890 ID.AddInteger(SVT.getRawBits()); 7891 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7892 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 7893 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7894 void *IP = nullptr; 7895 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7896 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7897 return SDValue(E, 0); 7898 } 7899 auto *N = 7900 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7901 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 7902 createOperands(N, Ops); 7903 7904 CSEMap.InsertNode(N, IP); 7905 InsertNode(N); 7906 SDValue V(N, 0); 7907 NewSDValueDbgMsg(V, "Creating new node: ", this); 7908 return V; 7909 } 7910 7911 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 7912 SDValue Base, SDValue Offset, 7913 ISD::MemIndexedMode AM) { 7914 auto *ST = cast<VPStoreSDNode>(OrigStore); 7915 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 7916 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7917 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 7918 Offset, ST->getMask(), ST->getVectorLength()}; 7919 FoldingSetNodeID ID; 7920 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7921 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7922 ID.AddInteger(ST->getRawSubclassData()); 7923 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7924 void *IP = nullptr; 7925 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7926 return SDValue(E, 0); 7927 7928 auto *N = newSDNode<VPStoreSDNode>( 7929 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 7930 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 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::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 7941 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 7942 ISD::MemIndexType IndexType) { 7943 assert(Ops.size() == 6 && "Incompatible number of operands"); 7944 7945 FoldingSetNodeID ID; 7946 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 7947 ID.AddInteger(VT.getRawBits()); 7948 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 7949 dl.getIROrder(), VTs, VT, MMO, IndexType)); 7950 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7951 void *IP = nullptr; 7952 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7953 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 7954 return SDValue(E, 0); 7955 } 7956 7957 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7958 VT, MMO, IndexType); 7959 createOperands(N, Ops); 7960 7961 assert(N->getMask().getValueType().getVectorElementCount() == 7962 N->getValueType(0).getVectorElementCount() && 7963 "Vector width mismatch between mask and data"); 7964 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7965 N->getValueType(0).getVectorElementCount().isScalable() && 7966 "Scalable flags of index and data do not match"); 7967 assert(ElementCount::isKnownGE( 7968 N->getIndex().getValueType().getVectorElementCount(), 7969 N->getValueType(0).getVectorElementCount()) && 7970 "Vector width mismatch between index and data"); 7971 assert(isa<ConstantSDNode>(N->getScale()) && 7972 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7973 "Scale should be a constant power of 2"); 7974 7975 CSEMap.InsertNode(N, IP); 7976 InsertNode(N); 7977 SDValue V(N, 0); 7978 NewSDValueDbgMsg(V, "Creating new node: ", this); 7979 return V; 7980 } 7981 7982 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 7983 ArrayRef<SDValue> Ops, 7984 MachineMemOperand *MMO, 7985 ISD::MemIndexType IndexType) { 7986 assert(Ops.size() == 7 && "Incompatible number of operands"); 7987 7988 FoldingSetNodeID ID; 7989 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 7990 ID.AddInteger(VT.getRawBits()); 7991 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 7992 dl.getIROrder(), VTs, VT, MMO, IndexType)); 7993 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7994 void *IP = nullptr; 7995 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7996 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 7997 return SDValue(E, 0); 7998 } 7999 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8000 VT, MMO, IndexType); 8001 createOperands(N, Ops); 8002 8003 assert(N->getMask().getValueType().getVectorElementCount() == 8004 N->getValue().getValueType().getVectorElementCount() && 8005 "Vector width mismatch between mask and data"); 8006 assert( 8007 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8008 N->getValue().getValueType().getVectorElementCount().isScalable() && 8009 "Scalable flags of index and data do not match"); 8010 assert(ElementCount::isKnownGE( 8011 N->getIndex().getValueType().getVectorElementCount(), 8012 N->getValue().getValueType().getVectorElementCount()) && 8013 "Vector width mismatch between index and data"); 8014 assert(isa<ConstantSDNode>(N->getScale()) && 8015 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8016 "Scale should be a constant power of 2"); 8017 8018 CSEMap.InsertNode(N, IP); 8019 InsertNode(N); 8020 SDValue V(N, 0); 8021 NewSDValueDbgMsg(V, "Creating new node: ", this); 8022 return V; 8023 } 8024 8025 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8026 SDValue Base, SDValue Offset, SDValue Mask, 8027 SDValue PassThru, EVT MemVT, 8028 MachineMemOperand *MMO, 8029 ISD::MemIndexedMode AM, 8030 ISD::LoadExtType ExtTy, bool isExpanding) { 8031 bool Indexed = AM != ISD::UNINDEXED; 8032 assert((Indexed || Offset.isUndef()) && 8033 "Unindexed masked load with an offset!"); 8034 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8035 : getVTList(VT, MVT::Other); 8036 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8037 FoldingSetNodeID ID; 8038 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8039 ID.AddInteger(MemVT.getRawBits()); 8040 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8041 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8042 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8043 void *IP = nullptr; 8044 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8045 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8046 return SDValue(E, 0); 8047 } 8048 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8049 AM, ExtTy, isExpanding, MemVT, MMO); 8050 createOperands(N, Ops); 8051 8052 CSEMap.InsertNode(N, IP); 8053 InsertNode(N); 8054 SDValue V(N, 0); 8055 NewSDValueDbgMsg(V, "Creating new node: ", this); 8056 return V; 8057 } 8058 8059 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8060 SDValue Base, SDValue Offset, 8061 ISD::MemIndexedMode AM) { 8062 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8063 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8064 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8065 Offset, LD->getMask(), LD->getPassThru(), 8066 LD->getMemoryVT(), LD->getMemOperand(), AM, 8067 LD->getExtensionType(), LD->isExpandingLoad()); 8068 } 8069 8070 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8071 SDValue Val, SDValue Base, SDValue Offset, 8072 SDValue Mask, EVT MemVT, 8073 MachineMemOperand *MMO, 8074 ISD::MemIndexedMode AM, bool IsTruncating, 8075 bool IsCompressing) { 8076 assert(Chain.getValueType() == MVT::Other && 8077 "Invalid chain type"); 8078 bool Indexed = AM != ISD::UNINDEXED; 8079 assert((Indexed || Offset.isUndef()) && 8080 "Unindexed masked store with an offset!"); 8081 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8082 : getVTList(MVT::Other); 8083 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8084 FoldingSetNodeID ID; 8085 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8086 ID.AddInteger(MemVT.getRawBits()); 8087 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8088 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8089 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8090 void *IP = nullptr; 8091 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8092 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8093 return SDValue(E, 0); 8094 } 8095 auto *N = 8096 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8097 IsTruncating, IsCompressing, MemVT, MMO); 8098 createOperands(N, Ops); 8099 8100 CSEMap.InsertNode(N, IP); 8101 InsertNode(N); 8102 SDValue V(N, 0); 8103 NewSDValueDbgMsg(V, "Creating new node: ", this); 8104 return V; 8105 } 8106 8107 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8108 SDValue Base, SDValue Offset, 8109 ISD::MemIndexedMode AM) { 8110 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8111 assert(ST->getOffset().isUndef() && 8112 "Masked store is already a indexed store!"); 8113 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8114 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8115 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8116 } 8117 8118 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8119 ArrayRef<SDValue> Ops, 8120 MachineMemOperand *MMO, 8121 ISD::MemIndexType IndexType, 8122 ISD::LoadExtType ExtTy) { 8123 assert(Ops.size() == 6 && "Incompatible number of operands"); 8124 8125 FoldingSetNodeID ID; 8126 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8127 ID.AddInteger(MemVT.getRawBits()); 8128 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8129 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8130 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8131 void *IP = nullptr; 8132 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8133 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8134 return SDValue(E, 0); 8135 } 8136 8137 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8138 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8139 VTs, MemVT, MMO, IndexType, ExtTy); 8140 createOperands(N, Ops); 8141 8142 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8143 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8144 assert(N->getMask().getValueType().getVectorElementCount() == 8145 N->getValueType(0).getVectorElementCount() && 8146 "Vector width mismatch between mask and data"); 8147 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8148 N->getValueType(0).getVectorElementCount().isScalable() && 8149 "Scalable flags of index and data do not match"); 8150 assert(ElementCount::isKnownGE( 8151 N->getIndex().getValueType().getVectorElementCount(), 8152 N->getValueType(0).getVectorElementCount()) && 8153 "Vector width mismatch between index and data"); 8154 assert(isa<ConstantSDNode>(N->getScale()) && 8155 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8156 "Scale should be a constant power of 2"); 8157 8158 CSEMap.InsertNode(N, IP); 8159 InsertNode(N); 8160 SDValue V(N, 0); 8161 NewSDValueDbgMsg(V, "Creating new node: ", this); 8162 return V; 8163 } 8164 8165 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8166 ArrayRef<SDValue> Ops, 8167 MachineMemOperand *MMO, 8168 ISD::MemIndexType IndexType, 8169 bool IsTrunc) { 8170 assert(Ops.size() == 6 && "Incompatible number of operands"); 8171 8172 FoldingSetNodeID ID; 8173 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8174 ID.AddInteger(MemVT.getRawBits()); 8175 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8176 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8177 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8178 void *IP = nullptr; 8179 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8180 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8181 return SDValue(E, 0); 8182 } 8183 8184 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8185 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8186 VTs, MemVT, MMO, IndexType, IsTrunc); 8187 createOperands(N, Ops); 8188 8189 assert(N->getMask().getValueType().getVectorElementCount() == 8190 N->getValue().getValueType().getVectorElementCount() && 8191 "Vector width mismatch between mask and data"); 8192 assert( 8193 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8194 N->getValue().getValueType().getVectorElementCount().isScalable() && 8195 "Scalable flags of index and data do not match"); 8196 assert(ElementCount::isKnownGE( 8197 N->getIndex().getValueType().getVectorElementCount(), 8198 N->getValue().getValueType().getVectorElementCount()) && 8199 "Vector width mismatch between index and data"); 8200 assert(isa<ConstantSDNode>(N->getScale()) && 8201 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8202 "Scale should be a constant power of 2"); 8203 8204 CSEMap.InsertNode(N, IP); 8205 InsertNode(N); 8206 SDValue V(N, 0); 8207 NewSDValueDbgMsg(V, "Creating new node: ", this); 8208 return V; 8209 } 8210 8211 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8212 // select undef, T, F --> T (if T is a constant), otherwise F 8213 // select, ?, undef, F --> F 8214 // select, ?, T, undef --> T 8215 if (Cond.isUndef()) 8216 return isConstantValueOfAnyType(T) ? T : F; 8217 if (T.isUndef()) 8218 return F; 8219 if (F.isUndef()) 8220 return T; 8221 8222 // select true, T, F --> T 8223 // select false, T, F --> F 8224 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8225 return CondC->isZero() ? F : T; 8226 8227 // TODO: This should simplify VSELECT with constant condition using something 8228 // like this (but check boolean contents to be complete?): 8229 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8230 // return T; 8231 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8232 // return F; 8233 8234 // select ?, T, T --> T 8235 if (T == F) 8236 return T; 8237 8238 return SDValue(); 8239 } 8240 8241 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8242 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8243 if (X.isUndef()) 8244 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8245 // shift X, undef --> undef (because it may shift by the bitwidth) 8246 if (Y.isUndef()) 8247 return getUNDEF(X.getValueType()); 8248 8249 // shift 0, Y --> 0 8250 // shift X, 0 --> X 8251 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8252 return X; 8253 8254 // shift X, C >= bitwidth(X) --> undef 8255 // All vector elements must be too big (or undef) to avoid partial undefs. 8256 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8257 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8258 }; 8259 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8260 return getUNDEF(X.getValueType()); 8261 8262 return SDValue(); 8263 } 8264 8265 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8266 SDNodeFlags Flags) { 8267 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8268 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8269 // operation is poison. That result can be relaxed to undef. 8270 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8271 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8272 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8273 (YC && YC->getValueAPF().isNaN()); 8274 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8275 (YC && YC->getValueAPF().isInfinity()); 8276 8277 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8278 return getUNDEF(X.getValueType()); 8279 8280 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8281 return getUNDEF(X.getValueType()); 8282 8283 if (!YC) 8284 return SDValue(); 8285 8286 // X + -0.0 --> X 8287 if (Opcode == ISD::FADD) 8288 if (YC->getValueAPF().isNegZero()) 8289 return X; 8290 8291 // X - +0.0 --> X 8292 if (Opcode == ISD::FSUB) 8293 if (YC->getValueAPF().isPosZero()) 8294 return X; 8295 8296 // X * 1.0 --> X 8297 // X / 1.0 --> X 8298 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8299 if (YC->getValueAPF().isExactlyValue(1.0)) 8300 return X; 8301 8302 // X * 0.0 --> 0.0 8303 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8304 if (YC->getValueAPF().isZero()) 8305 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8306 8307 return SDValue(); 8308 } 8309 8310 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8311 SDValue Ptr, SDValue SV, unsigned Align) { 8312 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8313 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8314 } 8315 8316 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8317 ArrayRef<SDUse> Ops) { 8318 switch (Ops.size()) { 8319 case 0: return getNode(Opcode, DL, VT); 8320 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8321 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8322 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8323 default: break; 8324 } 8325 8326 // Copy from an SDUse array into an SDValue array for use with 8327 // the regular getNode logic. 8328 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8329 return getNode(Opcode, DL, VT, NewOps); 8330 } 8331 8332 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8333 ArrayRef<SDValue> Ops) { 8334 SDNodeFlags Flags; 8335 if (Inserter) 8336 Flags = Inserter->getFlags(); 8337 return getNode(Opcode, DL, VT, Ops, Flags); 8338 } 8339 8340 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8341 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8342 unsigned NumOps = Ops.size(); 8343 switch (NumOps) { 8344 case 0: return getNode(Opcode, DL, VT); 8345 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8346 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8347 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8348 default: break; 8349 } 8350 8351 #ifndef NDEBUG 8352 for (auto &Op : Ops) 8353 assert(Op.getOpcode() != ISD::DELETED_NODE && 8354 "Operand is DELETED_NODE!"); 8355 #endif 8356 8357 switch (Opcode) { 8358 default: break; 8359 case ISD::BUILD_VECTOR: 8360 // Attempt to simplify BUILD_VECTOR. 8361 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8362 return V; 8363 break; 8364 case ISD::CONCAT_VECTORS: 8365 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8366 return V; 8367 break; 8368 case ISD::SELECT_CC: 8369 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8370 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8371 "LHS and RHS of condition must have same type!"); 8372 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8373 "True and False arms of SelectCC must have same type!"); 8374 assert(Ops[2].getValueType() == VT && 8375 "select_cc node must be of same type as true and false value!"); 8376 break; 8377 case ISD::BR_CC: 8378 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8379 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8380 "LHS/RHS of comparison should match types!"); 8381 break; 8382 } 8383 8384 // Memoize nodes. 8385 SDNode *N; 8386 SDVTList VTs = getVTList(VT); 8387 8388 if (VT != MVT::Glue) { 8389 FoldingSetNodeID ID; 8390 AddNodeIDNode(ID, Opcode, VTs, Ops); 8391 void *IP = nullptr; 8392 8393 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8394 return SDValue(E, 0); 8395 8396 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8397 createOperands(N, Ops); 8398 8399 CSEMap.InsertNode(N, IP); 8400 } else { 8401 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8402 createOperands(N, Ops); 8403 } 8404 8405 N->setFlags(Flags); 8406 InsertNode(N); 8407 SDValue V(N, 0); 8408 NewSDValueDbgMsg(V, "Creating new node: ", this); 8409 return V; 8410 } 8411 8412 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8413 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8414 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8415 } 8416 8417 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8418 ArrayRef<SDValue> Ops) { 8419 SDNodeFlags Flags; 8420 if (Inserter) 8421 Flags = Inserter->getFlags(); 8422 return getNode(Opcode, DL, VTList, Ops, Flags); 8423 } 8424 8425 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8426 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8427 if (VTList.NumVTs == 1) 8428 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8429 8430 #ifndef NDEBUG 8431 for (auto &Op : Ops) 8432 assert(Op.getOpcode() != ISD::DELETED_NODE && 8433 "Operand is DELETED_NODE!"); 8434 #endif 8435 8436 switch (Opcode) { 8437 case ISD::STRICT_FP_EXTEND: 8438 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8439 "Invalid STRICT_FP_EXTEND!"); 8440 assert(VTList.VTs[0].isFloatingPoint() && 8441 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8442 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8443 "STRICT_FP_EXTEND result type should be vector iff the operand " 8444 "type is vector!"); 8445 assert((!VTList.VTs[0].isVector() || 8446 VTList.VTs[0].getVectorNumElements() == 8447 Ops[1].getValueType().getVectorNumElements()) && 8448 "Vector element count mismatch!"); 8449 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8450 "Invalid fpext node, dst <= src!"); 8451 break; 8452 case ISD::STRICT_FP_ROUND: 8453 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8454 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8455 "STRICT_FP_ROUND result type should be vector iff the operand " 8456 "type is vector!"); 8457 assert((!VTList.VTs[0].isVector() || 8458 VTList.VTs[0].getVectorNumElements() == 8459 Ops[1].getValueType().getVectorNumElements()) && 8460 "Vector element count mismatch!"); 8461 assert(VTList.VTs[0].isFloatingPoint() && 8462 Ops[1].getValueType().isFloatingPoint() && 8463 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8464 isa<ConstantSDNode>(Ops[2]) && 8465 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8466 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8467 "Invalid STRICT_FP_ROUND!"); 8468 break; 8469 #if 0 8470 // FIXME: figure out how to safely handle things like 8471 // int foo(int x) { return 1 << (x & 255); } 8472 // int bar() { return foo(256); } 8473 case ISD::SRA_PARTS: 8474 case ISD::SRL_PARTS: 8475 case ISD::SHL_PARTS: 8476 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8477 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8478 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8479 else if (N3.getOpcode() == ISD::AND) 8480 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8481 // If the and is only masking out bits that cannot effect the shift, 8482 // eliminate the and. 8483 unsigned NumBits = VT.getScalarSizeInBits()*2; 8484 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8485 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8486 } 8487 break; 8488 #endif 8489 } 8490 8491 // Memoize the node unless it returns a flag. 8492 SDNode *N; 8493 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8494 FoldingSetNodeID ID; 8495 AddNodeIDNode(ID, Opcode, VTList, Ops); 8496 void *IP = nullptr; 8497 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8498 return SDValue(E, 0); 8499 8500 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8501 createOperands(N, Ops); 8502 CSEMap.InsertNode(N, IP); 8503 } else { 8504 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8505 createOperands(N, Ops); 8506 } 8507 8508 N->setFlags(Flags); 8509 InsertNode(N); 8510 SDValue V(N, 0); 8511 NewSDValueDbgMsg(V, "Creating new node: ", this); 8512 return V; 8513 } 8514 8515 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8516 SDVTList VTList) { 8517 return getNode(Opcode, DL, VTList, None); 8518 } 8519 8520 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8521 SDValue N1) { 8522 SDValue Ops[] = { N1 }; 8523 return getNode(Opcode, DL, VTList, Ops); 8524 } 8525 8526 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8527 SDValue N1, SDValue N2) { 8528 SDValue Ops[] = { N1, N2 }; 8529 return getNode(Opcode, DL, VTList, Ops); 8530 } 8531 8532 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8533 SDValue N1, SDValue N2, SDValue N3) { 8534 SDValue Ops[] = { N1, N2, N3 }; 8535 return getNode(Opcode, DL, VTList, Ops); 8536 } 8537 8538 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8539 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8540 SDValue Ops[] = { N1, N2, N3, N4 }; 8541 return getNode(Opcode, DL, VTList, Ops); 8542 } 8543 8544 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8545 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8546 SDValue N5) { 8547 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8548 return getNode(Opcode, DL, VTList, Ops); 8549 } 8550 8551 SDVTList SelectionDAG::getVTList(EVT VT) { 8552 return makeVTList(SDNode::getValueTypeList(VT), 1); 8553 } 8554 8555 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8556 FoldingSetNodeID ID; 8557 ID.AddInteger(2U); 8558 ID.AddInteger(VT1.getRawBits()); 8559 ID.AddInteger(VT2.getRawBits()); 8560 8561 void *IP = nullptr; 8562 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8563 if (!Result) { 8564 EVT *Array = Allocator.Allocate<EVT>(2); 8565 Array[0] = VT1; 8566 Array[1] = VT2; 8567 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8568 VTListMap.InsertNode(Result, IP); 8569 } 8570 return Result->getSDVTList(); 8571 } 8572 8573 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 8574 FoldingSetNodeID ID; 8575 ID.AddInteger(3U); 8576 ID.AddInteger(VT1.getRawBits()); 8577 ID.AddInteger(VT2.getRawBits()); 8578 ID.AddInteger(VT3.getRawBits()); 8579 8580 void *IP = nullptr; 8581 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8582 if (!Result) { 8583 EVT *Array = Allocator.Allocate<EVT>(3); 8584 Array[0] = VT1; 8585 Array[1] = VT2; 8586 Array[2] = VT3; 8587 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 8588 VTListMap.InsertNode(Result, IP); 8589 } 8590 return Result->getSDVTList(); 8591 } 8592 8593 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 8594 FoldingSetNodeID ID; 8595 ID.AddInteger(4U); 8596 ID.AddInteger(VT1.getRawBits()); 8597 ID.AddInteger(VT2.getRawBits()); 8598 ID.AddInteger(VT3.getRawBits()); 8599 ID.AddInteger(VT4.getRawBits()); 8600 8601 void *IP = nullptr; 8602 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8603 if (!Result) { 8604 EVT *Array = Allocator.Allocate<EVT>(4); 8605 Array[0] = VT1; 8606 Array[1] = VT2; 8607 Array[2] = VT3; 8608 Array[3] = VT4; 8609 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 8610 VTListMap.InsertNode(Result, IP); 8611 } 8612 return Result->getSDVTList(); 8613 } 8614 8615 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 8616 unsigned NumVTs = VTs.size(); 8617 FoldingSetNodeID ID; 8618 ID.AddInteger(NumVTs); 8619 for (unsigned index = 0; index < NumVTs; index++) { 8620 ID.AddInteger(VTs[index].getRawBits()); 8621 } 8622 8623 void *IP = nullptr; 8624 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8625 if (!Result) { 8626 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 8627 llvm::copy(VTs, Array); 8628 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 8629 VTListMap.InsertNode(Result, IP); 8630 } 8631 return Result->getSDVTList(); 8632 } 8633 8634 8635 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 8636 /// specified operands. If the resultant node already exists in the DAG, 8637 /// this does not modify the specified node, instead it returns the node that 8638 /// already exists. If the resultant node does not exist in the DAG, the 8639 /// input node is returned. As a degenerate case, if you specify the same 8640 /// input operands as the node already has, the input node is returned. 8641 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 8642 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 8643 8644 // Check to see if there is no change. 8645 if (Op == N->getOperand(0)) return N; 8646 8647 // See if the modified node already exists. 8648 void *InsertPos = nullptr; 8649 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 8650 return Existing; 8651 8652 // Nope it doesn't. Remove the node from its current place in the maps. 8653 if (InsertPos) 8654 if (!RemoveNodeFromCSEMaps(N)) 8655 InsertPos = nullptr; 8656 8657 // Now we update the operands. 8658 N->OperandList[0].set(Op); 8659 8660 updateDivergence(N); 8661 // If this gets put into a CSE map, add it. 8662 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8663 return N; 8664 } 8665 8666 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 8667 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 8668 8669 // Check to see if there is no change. 8670 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 8671 return N; // No operands changed, just return the input node. 8672 8673 // See if the modified node already exists. 8674 void *InsertPos = nullptr; 8675 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 8676 return Existing; 8677 8678 // Nope it doesn't. Remove the node from its current place in the maps. 8679 if (InsertPos) 8680 if (!RemoveNodeFromCSEMaps(N)) 8681 InsertPos = nullptr; 8682 8683 // Now we update the operands. 8684 if (N->OperandList[0] != Op1) 8685 N->OperandList[0].set(Op1); 8686 if (N->OperandList[1] != Op2) 8687 N->OperandList[1].set(Op2); 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:: 8696 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 8697 SDValue Ops[] = { Op1, Op2, Op3 }; 8698 return UpdateNodeOperands(N, Ops); 8699 } 8700 8701 SDNode *SelectionDAG:: 8702 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8703 SDValue Op3, SDValue Op4) { 8704 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 8705 return UpdateNodeOperands(N, Ops); 8706 } 8707 8708 SDNode *SelectionDAG:: 8709 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8710 SDValue Op3, SDValue Op4, SDValue Op5) { 8711 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 8712 return UpdateNodeOperands(N, Ops); 8713 } 8714 8715 SDNode *SelectionDAG:: 8716 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 8717 unsigned NumOps = Ops.size(); 8718 assert(N->getNumOperands() == NumOps && 8719 "Update with wrong number of operands"); 8720 8721 // If no operands changed just return the input node. 8722 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 8723 return N; 8724 8725 // See if the modified node already exists. 8726 void *InsertPos = nullptr; 8727 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8728 return Existing; 8729 8730 // Nope it doesn't. Remove the node from its current place in the maps. 8731 if (InsertPos) 8732 if (!RemoveNodeFromCSEMaps(N)) 8733 InsertPos = nullptr; 8734 8735 // Now we update the operands. 8736 for (unsigned i = 0; i != NumOps; ++i) 8737 if (N->OperandList[i] != Ops[i]) 8738 N->OperandList[i].set(Ops[i]); 8739 8740 updateDivergence(N); 8741 // If this gets put into a CSE map, add it. 8742 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8743 return N; 8744 } 8745 8746 /// DropOperands - Release the operands and set this node to have 8747 /// zero operands. 8748 void SDNode::DropOperands() { 8749 // Unlike the code in MorphNodeTo that does this, we don't need to 8750 // watch for dead nodes here. 8751 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8752 SDUse &Use = *I++; 8753 Use.set(SDValue()); 8754 } 8755 } 8756 8757 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8758 ArrayRef<MachineMemOperand *> NewMemRefs) { 8759 if (NewMemRefs.empty()) { 8760 N->clearMemRefs(); 8761 return; 8762 } 8763 8764 // Check if we can avoid allocating by storing a single reference directly. 8765 if (NewMemRefs.size() == 1) { 8766 N->MemRefs = NewMemRefs[0]; 8767 N->NumMemRefs = 1; 8768 return; 8769 } 8770 8771 MachineMemOperand **MemRefsBuffer = 8772 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8773 llvm::copy(NewMemRefs, MemRefsBuffer); 8774 N->MemRefs = MemRefsBuffer; 8775 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8776 } 8777 8778 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8779 /// machine opcode. 8780 /// 8781 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8782 EVT VT) { 8783 SDVTList VTs = getVTList(VT); 8784 return SelectNodeTo(N, MachineOpc, VTs, None); 8785 } 8786 8787 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8788 EVT VT, SDValue Op1) { 8789 SDVTList VTs = getVTList(VT); 8790 SDValue Ops[] = { Op1 }; 8791 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8792 } 8793 8794 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8795 EVT VT, SDValue Op1, 8796 SDValue Op2) { 8797 SDVTList VTs = getVTList(VT); 8798 SDValue Ops[] = { Op1, Op2 }; 8799 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8800 } 8801 8802 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8803 EVT VT, SDValue Op1, 8804 SDValue Op2, SDValue Op3) { 8805 SDVTList VTs = getVTList(VT); 8806 SDValue Ops[] = { Op1, Op2, Op3 }; 8807 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8808 } 8809 8810 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8811 EVT VT, ArrayRef<SDValue> Ops) { 8812 SDVTList VTs = getVTList(VT); 8813 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8814 } 8815 8816 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8817 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8818 SDVTList VTs = getVTList(VT1, VT2); 8819 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8820 } 8821 8822 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8823 EVT VT1, EVT VT2) { 8824 SDVTList VTs = getVTList(VT1, VT2); 8825 return SelectNodeTo(N, MachineOpc, VTs, None); 8826 } 8827 8828 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8829 EVT VT1, EVT VT2, EVT VT3, 8830 ArrayRef<SDValue> Ops) { 8831 SDVTList VTs = getVTList(VT1, VT2, VT3); 8832 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8833 } 8834 8835 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8836 EVT VT1, EVT VT2, 8837 SDValue Op1, SDValue Op2) { 8838 SDVTList VTs = getVTList(VT1, VT2); 8839 SDValue Ops[] = { Op1, Op2 }; 8840 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8841 } 8842 8843 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8844 SDVTList VTs,ArrayRef<SDValue> Ops) { 8845 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8846 // Reset the NodeID to -1. 8847 New->setNodeId(-1); 8848 if (New != N) { 8849 ReplaceAllUsesWith(N, New); 8850 RemoveDeadNode(N); 8851 } 8852 return New; 8853 } 8854 8855 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8856 /// the line number information on the merged node since it is not possible to 8857 /// preserve the information that operation is associated with multiple lines. 8858 /// This will make the debugger working better at -O0, were there is a higher 8859 /// probability having other instructions associated with that line. 8860 /// 8861 /// For IROrder, we keep the smaller of the two 8862 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8863 DebugLoc NLoc = N->getDebugLoc(); 8864 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8865 N->setDebugLoc(DebugLoc()); 8866 } 8867 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8868 N->setIROrder(Order); 8869 return N; 8870 } 8871 8872 /// MorphNodeTo - This *mutates* the specified node to have the specified 8873 /// return type, opcode, and operands. 8874 /// 8875 /// Note that MorphNodeTo returns the resultant node. If there is already a 8876 /// node of the specified opcode and operands, it returns that node instead of 8877 /// the current one. Note that the SDLoc need not be the same. 8878 /// 8879 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8880 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8881 /// node, and because it doesn't require CSE recalculation for any of 8882 /// the node's users. 8883 /// 8884 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8885 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8886 /// the legalizer which maintain worklists that would need to be updated when 8887 /// deleting things. 8888 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8889 SDVTList VTs, ArrayRef<SDValue> Ops) { 8890 // If an identical node already exists, use it. 8891 void *IP = nullptr; 8892 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8893 FoldingSetNodeID ID; 8894 AddNodeIDNode(ID, Opc, VTs, Ops); 8895 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8896 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8897 } 8898 8899 if (!RemoveNodeFromCSEMaps(N)) 8900 IP = nullptr; 8901 8902 // Start the morphing. 8903 N->NodeType = Opc; 8904 N->ValueList = VTs.VTs; 8905 N->NumValues = VTs.NumVTs; 8906 8907 // Clear the operands list, updating used nodes to remove this from their 8908 // use list. Keep track of any operands that become dead as a result. 8909 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8910 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8911 SDUse &Use = *I++; 8912 SDNode *Used = Use.getNode(); 8913 Use.set(SDValue()); 8914 if (Used->use_empty()) 8915 DeadNodeSet.insert(Used); 8916 } 8917 8918 // For MachineNode, initialize the memory references information. 8919 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8920 MN->clearMemRefs(); 8921 8922 // Swap for an appropriately sized array from the recycler. 8923 removeOperands(N); 8924 createOperands(N, Ops); 8925 8926 // Delete any nodes that are still dead after adding the uses for the 8927 // new operands. 8928 if (!DeadNodeSet.empty()) { 8929 SmallVector<SDNode *, 16> DeadNodes; 8930 for (SDNode *N : DeadNodeSet) 8931 if (N->use_empty()) 8932 DeadNodes.push_back(N); 8933 RemoveDeadNodes(DeadNodes); 8934 } 8935 8936 if (IP) 8937 CSEMap.InsertNode(N, IP); // Memoize the new node. 8938 return N; 8939 } 8940 8941 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8942 unsigned OrigOpc = Node->getOpcode(); 8943 unsigned NewOpc; 8944 switch (OrigOpc) { 8945 default: 8946 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8947 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8948 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8949 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8950 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8951 #include "llvm/IR/ConstrainedOps.def" 8952 } 8953 8954 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8955 8956 // We're taking this node out of the chain, so we need to re-link things. 8957 SDValue InputChain = Node->getOperand(0); 8958 SDValue OutputChain = SDValue(Node, 1); 8959 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8960 8961 SmallVector<SDValue, 3> Ops; 8962 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8963 Ops.push_back(Node->getOperand(i)); 8964 8965 SDVTList VTs = getVTList(Node->getValueType(0)); 8966 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8967 8968 // MorphNodeTo can operate in two ways: if an existing node with the 8969 // specified operands exists, it can just return it. Otherwise, it 8970 // updates the node in place to have the requested operands. 8971 if (Res == Node) { 8972 // If we updated the node in place, reset the node ID. To the isel, 8973 // this should be just like a newly allocated machine node. 8974 Res->setNodeId(-1); 8975 } else { 8976 ReplaceAllUsesWith(Node, Res); 8977 RemoveDeadNode(Node); 8978 } 8979 8980 return Res; 8981 } 8982 8983 /// getMachineNode - These are used for target selectors to create a new node 8984 /// with specified return type(s), MachineInstr opcode, and operands. 8985 /// 8986 /// Note that getMachineNode returns the resultant node. If there is already a 8987 /// node of the specified opcode and operands, it returns that node instead of 8988 /// the current one. 8989 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8990 EVT VT) { 8991 SDVTList VTs = getVTList(VT); 8992 return getMachineNode(Opcode, dl, VTs, None); 8993 } 8994 8995 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8996 EVT VT, SDValue Op1) { 8997 SDVTList VTs = getVTList(VT); 8998 SDValue Ops[] = { Op1 }; 8999 return getMachineNode(Opcode, dl, VTs, Ops); 9000 } 9001 9002 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9003 EVT VT, SDValue Op1, SDValue Op2) { 9004 SDVTList VTs = getVTList(VT); 9005 SDValue Ops[] = { Op1, Op2 }; 9006 return getMachineNode(Opcode, dl, VTs, Ops); 9007 } 9008 9009 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9010 EVT VT, SDValue Op1, SDValue Op2, 9011 SDValue Op3) { 9012 SDVTList VTs = getVTList(VT); 9013 SDValue Ops[] = { Op1, Op2, Op3 }; 9014 return getMachineNode(Opcode, dl, VTs, Ops); 9015 } 9016 9017 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9018 EVT VT, ArrayRef<SDValue> Ops) { 9019 SDVTList VTs = getVTList(VT); 9020 return getMachineNode(Opcode, dl, VTs, Ops); 9021 } 9022 9023 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9024 EVT VT1, EVT VT2, SDValue Op1, 9025 SDValue Op2) { 9026 SDVTList VTs = getVTList(VT1, VT2); 9027 SDValue Ops[] = { Op1, Op2 }; 9028 return getMachineNode(Opcode, dl, VTs, Ops); 9029 } 9030 9031 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9032 EVT VT1, EVT VT2, SDValue Op1, 9033 SDValue Op2, SDValue Op3) { 9034 SDVTList VTs = getVTList(VT1, VT2); 9035 SDValue Ops[] = { Op1, Op2, Op3 }; 9036 return getMachineNode(Opcode, dl, VTs, Ops); 9037 } 9038 9039 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9040 EVT VT1, EVT VT2, 9041 ArrayRef<SDValue> Ops) { 9042 SDVTList VTs = getVTList(VT1, VT2); 9043 return getMachineNode(Opcode, dl, VTs, Ops); 9044 } 9045 9046 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9047 EVT VT1, EVT VT2, EVT VT3, 9048 SDValue Op1, SDValue Op2) { 9049 SDVTList VTs = getVTList(VT1, VT2, VT3); 9050 SDValue Ops[] = { Op1, Op2 }; 9051 return getMachineNode(Opcode, dl, VTs, Ops); 9052 } 9053 9054 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9055 EVT VT1, EVT VT2, EVT VT3, 9056 SDValue Op1, SDValue Op2, 9057 SDValue Op3) { 9058 SDVTList VTs = getVTList(VT1, VT2, VT3); 9059 SDValue Ops[] = { Op1, Op2, Op3 }; 9060 return getMachineNode(Opcode, dl, VTs, Ops); 9061 } 9062 9063 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9064 EVT VT1, EVT VT2, EVT VT3, 9065 ArrayRef<SDValue> Ops) { 9066 SDVTList VTs = getVTList(VT1, VT2, VT3); 9067 return getMachineNode(Opcode, dl, VTs, Ops); 9068 } 9069 9070 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9071 ArrayRef<EVT> ResultTys, 9072 ArrayRef<SDValue> Ops) { 9073 SDVTList VTs = getVTList(ResultTys); 9074 return getMachineNode(Opcode, dl, VTs, Ops); 9075 } 9076 9077 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9078 SDVTList VTs, 9079 ArrayRef<SDValue> Ops) { 9080 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9081 MachineSDNode *N; 9082 void *IP = nullptr; 9083 9084 if (DoCSE) { 9085 FoldingSetNodeID ID; 9086 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9087 IP = nullptr; 9088 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9089 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9090 } 9091 } 9092 9093 // Allocate a new MachineSDNode. 9094 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9095 createOperands(N, Ops); 9096 9097 if (DoCSE) 9098 CSEMap.InsertNode(N, IP); 9099 9100 InsertNode(N); 9101 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9102 return N; 9103 } 9104 9105 /// getTargetExtractSubreg - A convenience function for creating 9106 /// TargetOpcode::EXTRACT_SUBREG nodes. 9107 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9108 SDValue Operand) { 9109 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9110 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9111 VT, Operand, SRIdxVal); 9112 return SDValue(Subreg, 0); 9113 } 9114 9115 /// getTargetInsertSubreg - A convenience function for creating 9116 /// TargetOpcode::INSERT_SUBREG nodes. 9117 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9118 SDValue Operand, SDValue Subreg) { 9119 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9120 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9121 VT, Operand, Subreg, SRIdxVal); 9122 return SDValue(Result, 0); 9123 } 9124 9125 /// getNodeIfExists - Get the specified node if it's already available, or 9126 /// else return NULL. 9127 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9128 ArrayRef<SDValue> Ops) { 9129 SDNodeFlags Flags; 9130 if (Inserter) 9131 Flags = Inserter->getFlags(); 9132 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9133 } 9134 9135 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9136 ArrayRef<SDValue> Ops, 9137 const SDNodeFlags Flags) { 9138 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9139 FoldingSetNodeID ID; 9140 AddNodeIDNode(ID, Opcode, VTList, Ops); 9141 void *IP = nullptr; 9142 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9143 E->intersectFlagsWith(Flags); 9144 return E; 9145 } 9146 } 9147 return nullptr; 9148 } 9149 9150 /// doesNodeExist - Check if a node exists without modifying its flags. 9151 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9152 ArrayRef<SDValue> Ops) { 9153 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9154 FoldingSetNodeID ID; 9155 AddNodeIDNode(ID, Opcode, VTList, Ops); 9156 void *IP = nullptr; 9157 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9158 return true; 9159 } 9160 return false; 9161 } 9162 9163 /// getDbgValue - Creates a SDDbgValue node. 9164 /// 9165 /// SDNode 9166 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9167 SDNode *N, unsigned R, bool IsIndirect, 9168 const DebugLoc &DL, unsigned O) { 9169 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9170 "Expected inlined-at fields to agree"); 9171 return new (DbgInfo->getAlloc()) 9172 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9173 {}, IsIndirect, DL, O, 9174 /*IsVariadic=*/false); 9175 } 9176 9177 /// Constant 9178 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9179 DIExpression *Expr, 9180 const Value *C, 9181 const DebugLoc &DL, unsigned O) { 9182 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9183 "Expected inlined-at fields to agree"); 9184 return new (DbgInfo->getAlloc()) 9185 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9186 /*IsIndirect=*/false, DL, O, 9187 /*IsVariadic=*/false); 9188 } 9189 9190 /// FrameIndex 9191 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9192 DIExpression *Expr, unsigned FI, 9193 bool IsIndirect, 9194 const DebugLoc &DL, 9195 unsigned O) { 9196 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9197 "Expected inlined-at fields to agree"); 9198 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9199 } 9200 9201 /// FrameIndex with dependencies 9202 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9203 DIExpression *Expr, unsigned FI, 9204 ArrayRef<SDNode *> Dependencies, 9205 bool IsIndirect, 9206 const DebugLoc &DL, 9207 unsigned O) { 9208 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9209 "Expected inlined-at fields to agree"); 9210 return new (DbgInfo->getAlloc()) 9211 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9212 Dependencies, IsIndirect, DL, O, 9213 /*IsVariadic=*/false); 9214 } 9215 9216 /// VReg 9217 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9218 unsigned VReg, bool IsIndirect, 9219 const DebugLoc &DL, unsigned O) { 9220 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9221 "Expected inlined-at fields to agree"); 9222 return new (DbgInfo->getAlloc()) 9223 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9224 {}, IsIndirect, DL, O, 9225 /*IsVariadic=*/false); 9226 } 9227 9228 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9229 ArrayRef<SDDbgOperand> Locs, 9230 ArrayRef<SDNode *> Dependencies, 9231 bool IsIndirect, const DebugLoc &DL, 9232 unsigned O, bool IsVariadic) { 9233 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9234 "Expected inlined-at fields to agree"); 9235 return new (DbgInfo->getAlloc()) 9236 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9237 DL, O, IsVariadic); 9238 } 9239 9240 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9241 unsigned OffsetInBits, unsigned SizeInBits, 9242 bool InvalidateDbg) { 9243 SDNode *FromNode = From.getNode(); 9244 SDNode *ToNode = To.getNode(); 9245 assert(FromNode && ToNode && "Can't modify dbg values"); 9246 9247 // PR35338 9248 // TODO: assert(From != To && "Redundant dbg value transfer"); 9249 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9250 if (From == To || FromNode == ToNode) 9251 return; 9252 9253 if (!FromNode->getHasDebugValue()) 9254 return; 9255 9256 SDDbgOperand FromLocOp = 9257 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9258 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9259 9260 SmallVector<SDDbgValue *, 2> ClonedDVs; 9261 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9262 if (Dbg->isInvalidated()) 9263 continue; 9264 9265 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9266 9267 // Create a new location ops vector that is equal to the old vector, but 9268 // with each instance of FromLocOp replaced with ToLocOp. 9269 bool Changed = false; 9270 auto NewLocOps = Dbg->copyLocationOps(); 9271 std::replace_if( 9272 NewLocOps.begin(), NewLocOps.end(), 9273 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9274 bool Match = Op == FromLocOp; 9275 Changed |= Match; 9276 return Match; 9277 }, 9278 ToLocOp); 9279 // Ignore this SDDbgValue if we didn't find a matching location. 9280 if (!Changed) 9281 continue; 9282 9283 DIVariable *Var = Dbg->getVariable(); 9284 auto *Expr = Dbg->getExpression(); 9285 // If a fragment is requested, update the expression. 9286 if (SizeInBits) { 9287 // When splitting a larger (e.g., sign-extended) value whose 9288 // lower bits are described with an SDDbgValue, do not attempt 9289 // to transfer the SDDbgValue to the upper bits. 9290 if (auto FI = Expr->getFragmentInfo()) 9291 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9292 continue; 9293 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9294 SizeInBits); 9295 if (!Fragment) 9296 continue; 9297 Expr = *Fragment; 9298 } 9299 9300 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9301 // Clone the SDDbgValue and move it to To. 9302 SDDbgValue *Clone = getDbgValueList( 9303 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9304 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9305 Dbg->isVariadic()); 9306 ClonedDVs.push_back(Clone); 9307 9308 if (InvalidateDbg) { 9309 // Invalidate value and indicate the SDDbgValue should not be emitted. 9310 Dbg->setIsInvalidated(); 9311 Dbg->setIsEmitted(); 9312 } 9313 } 9314 9315 for (SDDbgValue *Dbg : ClonedDVs) { 9316 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9317 "Transferred DbgValues should depend on the new SDNode"); 9318 AddDbgValue(Dbg, false); 9319 } 9320 } 9321 9322 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9323 if (!N.getHasDebugValue()) 9324 return; 9325 9326 SmallVector<SDDbgValue *, 2> ClonedDVs; 9327 for (auto DV : GetDbgValues(&N)) { 9328 if (DV->isInvalidated()) 9329 continue; 9330 switch (N.getOpcode()) { 9331 default: 9332 break; 9333 case ISD::ADD: 9334 SDValue N0 = N.getOperand(0); 9335 SDValue N1 = N.getOperand(1); 9336 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9337 isConstantIntBuildVectorOrConstantInt(N1)) { 9338 uint64_t Offset = N.getConstantOperandVal(1); 9339 9340 // Rewrite an ADD constant node into a DIExpression. Since we are 9341 // performing arithmetic to compute the variable's *value* in the 9342 // DIExpression, we need to mark the expression with a 9343 // DW_OP_stack_value. 9344 auto *DIExpr = DV->getExpression(); 9345 auto NewLocOps = DV->copyLocationOps(); 9346 bool Changed = false; 9347 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9348 // We're not given a ResNo to compare against because the whole 9349 // node is going away. We know that any ISD::ADD only has one 9350 // result, so we can assume any node match is using the result. 9351 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9352 NewLocOps[i].getSDNode() != &N) 9353 continue; 9354 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9355 SmallVector<uint64_t, 3> ExprOps; 9356 DIExpression::appendOffset(ExprOps, Offset); 9357 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9358 Changed = true; 9359 } 9360 (void)Changed; 9361 assert(Changed && "Salvage target doesn't use N"); 9362 9363 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9364 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9365 NewLocOps, AdditionalDependencies, 9366 DV->isIndirect(), DV->getDebugLoc(), 9367 DV->getOrder(), DV->isVariadic()); 9368 ClonedDVs.push_back(Clone); 9369 DV->setIsInvalidated(); 9370 DV->setIsEmitted(); 9371 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9372 N0.getNode()->dumprFull(this); 9373 dbgs() << " into " << *DIExpr << '\n'); 9374 } 9375 } 9376 } 9377 9378 for (SDDbgValue *Dbg : ClonedDVs) { 9379 assert(!Dbg->getSDNodes().empty() && 9380 "Salvaged DbgValue should depend on a new SDNode"); 9381 AddDbgValue(Dbg, false); 9382 } 9383 } 9384 9385 /// Creates a SDDbgLabel node. 9386 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9387 const DebugLoc &DL, unsigned O) { 9388 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9389 "Expected inlined-at fields to agree"); 9390 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9391 } 9392 9393 namespace { 9394 9395 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9396 /// pointed to by a use iterator is deleted, increment the use iterator 9397 /// so that it doesn't dangle. 9398 /// 9399 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9400 SDNode::use_iterator &UI; 9401 SDNode::use_iterator &UE; 9402 9403 void NodeDeleted(SDNode *N, SDNode *E) override { 9404 // Increment the iterator as needed. 9405 while (UI != UE && N == *UI) 9406 ++UI; 9407 } 9408 9409 public: 9410 RAUWUpdateListener(SelectionDAG &d, 9411 SDNode::use_iterator &ui, 9412 SDNode::use_iterator &ue) 9413 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9414 }; 9415 9416 } // end anonymous namespace 9417 9418 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9419 /// This can cause recursive merging of nodes in the DAG. 9420 /// 9421 /// This version assumes From has a single result value. 9422 /// 9423 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9424 SDNode *From = FromN.getNode(); 9425 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9426 "Cannot replace with this method!"); 9427 assert(From != To.getNode() && "Cannot replace uses of with self"); 9428 9429 // Preserve Debug Values 9430 transferDbgValues(FromN, To); 9431 9432 // Iterate over all the existing uses of From. New uses will be added 9433 // to the beginning of the use list, which we avoid visiting. 9434 // This specifically avoids visiting uses of From that arise while the 9435 // replacement is happening, because any such uses would be the result 9436 // of CSE: If an existing node looks like From after one of its operands 9437 // is replaced by To, we don't want to replace of all its users with To 9438 // too. See PR3018 for more info. 9439 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9440 RAUWUpdateListener Listener(*this, UI, UE); 9441 while (UI != UE) { 9442 SDNode *User = *UI; 9443 9444 // This node is about to morph, remove its old self from the CSE maps. 9445 RemoveNodeFromCSEMaps(User); 9446 9447 // A user can appear in a use list multiple times, and when this 9448 // happens the uses are usually next to each other in the list. 9449 // To help reduce the number of CSE recomputations, process all 9450 // the uses of this user that we can find this way. 9451 do { 9452 SDUse &Use = UI.getUse(); 9453 ++UI; 9454 Use.set(To); 9455 if (To->isDivergent() != From->isDivergent()) 9456 updateDivergence(User); 9457 } while (UI != UE && *UI == User); 9458 // Now that we have modified User, add it back to the CSE maps. If it 9459 // already exists there, recursively merge the results together. 9460 AddModifiedNodeToCSEMaps(User); 9461 } 9462 9463 // If we just RAUW'd the root, take note. 9464 if (FromN == getRoot()) 9465 setRoot(To); 9466 } 9467 9468 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9469 /// This can cause recursive merging of nodes in the DAG. 9470 /// 9471 /// This version assumes that for each value of From, there is a 9472 /// corresponding value in To in the same position with the same type. 9473 /// 9474 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9475 #ifndef NDEBUG 9476 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9477 assert((!From->hasAnyUseOfValue(i) || 9478 From->getValueType(i) == To->getValueType(i)) && 9479 "Cannot use this version of ReplaceAllUsesWith!"); 9480 #endif 9481 9482 // Handle the trivial case. 9483 if (From == To) 9484 return; 9485 9486 // Preserve Debug Info. Only do this if there's a use. 9487 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9488 if (From->hasAnyUseOfValue(i)) { 9489 assert((i < To->getNumValues()) && "Invalid To location"); 9490 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9491 } 9492 9493 // Iterate over just the existing users of From. See the comments in 9494 // the ReplaceAllUsesWith above. 9495 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9496 RAUWUpdateListener Listener(*this, UI, UE); 9497 while (UI != UE) { 9498 SDNode *User = *UI; 9499 9500 // This node is about to morph, remove its old self from the CSE maps. 9501 RemoveNodeFromCSEMaps(User); 9502 9503 // A user can appear in a use list multiple times, and when this 9504 // happens the uses are usually next to each other in the list. 9505 // To help reduce the number of CSE recomputations, process all 9506 // the uses of this user that we can find this way. 9507 do { 9508 SDUse &Use = UI.getUse(); 9509 ++UI; 9510 Use.setNode(To); 9511 if (To->isDivergent() != From->isDivergent()) 9512 updateDivergence(User); 9513 } while (UI != UE && *UI == User); 9514 9515 // Now that we have modified User, add it back to the CSE maps. If it 9516 // already exists there, recursively merge the results together. 9517 AddModifiedNodeToCSEMaps(User); 9518 } 9519 9520 // If we just RAUW'd the root, take note. 9521 if (From == getRoot().getNode()) 9522 setRoot(SDValue(To, getRoot().getResNo())); 9523 } 9524 9525 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9526 /// This can cause recursive merging of nodes in the DAG. 9527 /// 9528 /// This version can replace From with any result values. To must match the 9529 /// number and types of values returned by From. 9530 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9531 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9532 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9533 9534 // Preserve Debug Info. 9535 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9536 transferDbgValues(SDValue(From, i), To[i]); 9537 9538 // Iterate over just the existing users of From. See the comments in 9539 // the ReplaceAllUsesWith above. 9540 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9541 RAUWUpdateListener Listener(*this, UI, UE); 9542 while (UI != UE) { 9543 SDNode *User = *UI; 9544 9545 // This node is about to morph, remove its old self from the CSE maps. 9546 RemoveNodeFromCSEMaps(User); 9547 9548 // A user can appear in a use list multiple times, and when this happens the 9549 // uses are usually next to each other in the list. To help reduce the 9550 // number of CSE and divergence recomputations, process all the uses of this 9551 // user that we can find this way. 9552 bool To_IsDivergent = false; 9553 do { 9554 SDUse &Use = UI.getUse(); 9555 const SDValue &ToOp = To[Use.getResNo()]; 9556 ++UI; 9557 Use.set(ToOp); 9558 To_IsDivergent |= ToOp->isDivergent(); 9559 } while (UI != UE && *UI == User); 9560 9561 if (To_IsDivergent != From->isDivergent()) 9562 updateDivergence(User); 9563 9564 // Now that we have modified User, add it back to the CSE maps. If it 9565 // already exists there, recursively merge the results together. 9566 AddModifiedNodeToCSEMaps(User); 9567 } 9568 9569 // If we just RAUW'd the root, take note. 9570 if (From == getRoot().getNode()) 9571 setRoot(SDValue(To[getRoot().getResNo()])); 9572 } 9573 9574 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 9575 /// uses of other values produced by From.getNode() alone. The Deleted 9576 /// vector is handled the same way as for ReplaceAllUsesWith. 9577 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 9578 // Handle the really simple, really trivial case efficiently. 9579 if (From == To) return; 9580 9581 // Handle the simple, trivial, case efficiently. 9582 if (From.getNode()->getNumValues() == 1) { 9583 ReplaceAllUsesWith(From, To); 9584 return; 9585 } 9586 9587 // Preserve Debug Info. 9588 transferDbgValues(From, To); 9589 9590 // Iterate over just the existing users of From. See the comments in 9591 // the ReplaceAllUsesWith above. 9592 SDNode::use_iterator UI = From.getNode()->use_begin(), 9593 UE = From.getNode()->use_end(); 9594 RAUWUpdateListener Listener(*this, UI, UE); 9595 while (UI != UE) { 9596 SDNode *User = *UI; 9597 bool UserRemovedFromCSEMaps = false; 9598 9599 // A user can appear in a use list multiple times, and when this 9600 // happens the uses are usually next to each other in the list. 9601 // To help reduce the number of CSE recomputations, process all 9602 // the uses of this user that we can find this way. 9603 do { 9604 SDUse &Use = UI.getUse(); 9605 9606 // Skip uses of different values from the same node. 9607 if (Use.getResNo() != From.getResNo()) { 9608 ++UI; 9609 continue; 9610 } 9611 9612 // If this node hasn't been modified yet, it's still in the CSE maps, 9613 // so remove its old self from the CSE maps. 9614 if (!UserRemovedFromCSEMaps) { 9615 RemoveNodeFromCSEMaps(User); 9616 UserRemovedFromCSEMaps = true; 9617 } 9618 9619 ++UI; 9620 Use.set(To); 9621 if (To->isDivergent() != From->isDivergent()) 9622 updateDivergence(User); 9623 } while (UI != UE && *UI == User); 9624 // We are iterating over all uses of the From node, so if a use 9625 // doesn't use the specific value, no changes are made. 9626 if (!UserRemovedFromCSEMaps) 9627 continue; 9628 9629 // Now that we have modified User, add it back to the CSE maps. If it 9630 // already exists there, recursively merge the results together. 9631 AddModifiedNodeToCSEMaps(User); 9632 } 9633 9634 // If we just RAUW'd the root, take note. 9635 if (From == getRoot()) 9636 setRoot(To); 9637 } 9638 9639 namespace { 9640 9641 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 9642 /// to record information about a use. 9643 struct UseMemo { 9644 SDNode *User; 9645 unsigned Index; 9646 SDUse *Use; 9647 }; 9648 9649 /// operator< - Sort Memos by User. 9650 bool operator<(const UseMemo &L, const UseMemo &R) { 9651 return (intptr_t)L.User < (intptr_t)R.User; 9652 } 9653 9654 } // end anonymous namespace 9655 9656 bool SelectionDAG::calculateDivergence(SDNode *N) { 9657 if (TLI->isSDNodeAlwaysUniform(N)) { 9658 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 9659 "Conflicting divergence information!"); 9660 return false; 9661 } 9662 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 9663 return true; 9664 for (auto &Op : N->ops()) { 9665 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 9666 return true; 9667 } 9668 return false; 9669 } 9670 9671 void SelectionDAG::updateDivergence(SDNode *N) { 9672 SmallVector<SDNode *, 16> Worklist(1, N); 9673 do { 9674 N = Worklist.pop_back_val(); 9675 bool IsDivergent = calculateDivergence(N); 9676 if (N->SDNodeBits.IsDivergent != IsDivergent) { 9677 N->SDNodeBits.IsDivergent = IsDivergent; 9678 llvm::append_range(Worklist, N->uses()); 9679 } 9680 } while (!Worklist.empty()); 9681 } 9682 9683 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 9684 DenseMap<SDNode *, unsigned> Degree; 9685 Order.reserve(AllNodes.size()); 9686 for (auto &N : allnodes()) { 9687 unsigned NOps = N.getNumOperands(); 9688 Degree[&N] = NOps; 9689 if (0 == NOps) 9690 Order.push_back(&N); 9691 } 9692 for (size_t I = 0; I != Order.size(); ++I) { 9693 SDNode *N = Order[I]; 9694 for (auto U : N->uses()) { 9695 unsigned &UnsortedOps = Degree[U]; 9696 if (0 == --UnsortedOps) 9697 Order.push_back(U); 9698 } 9699 } 9700 } 9701 9702 #ifndef NDEBUG 9703 void SelectionDAG::VerifyDAGDivergence() { 9704 std::vector<SDNode *> TopoOrder; 9705 CreateTopologicalOrder(TopoOrder); 9706 for (auto *N : TopoOrder) { 9707 assert(calculateDivergence(N) == N->isDivergent() && 9708 "Divergence bit inconsistency detected"); 9709 } 9710 } 9711 #endif 9712 9713 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 9714 /// uses of other values produced by From.getNode() alone. The same value 9715 /// may appear in both the From and To list. The Deleted vector is 9716 /// handled the same way as for ReplaceAllUsesWith. 9717 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 9718 const SDValue *To, 9719 unsigned Num){ 9720 // Handle the simple, trivial case efficiently. 9721 if (Num == 1) 9722 return ReplaceAllUsesOfValueWith(*From, *To); 9723 9724 transferDbgValues(*From, *To); 9725 9726 // Read up all the uses and make records of them. This helps 9727 // processing new uses that are introduced during the 9728 // replacement process. 9729 SmallVector<UseMemo, 4> Uses; 9730 for (unsigned i = 0; i != Num; ++i) { 9731 unsigned FromResNo = From[i].getResNo(); 9732 SDNode *FromNode = From[i].getNode(); 9733 for (SDNode::use_iterator UI = FromNode->use_begin(), 9734 E = FromNode->use_end(); UI != E; ++UI) { 9735 SDUse &Use = UI.getUse(); 9736 if (Use.getResNo() == FromResNo) { 9737 UseMemo Memo = { *UI, i, &Use }; 9738 Uses.push_back(Memo); 9739 } 9740 } 9741 } 9742 9743 // Sort the uses, so that all the uses from a given User are together. 9744 llvm::sort(Uses); 9745 9746 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 9747 UseIndex != UseIndexEnd; ) { 9748 // We know that this user uses some value of From. If it is the right 9749 // value, update it. 9750 SDNode *User = Uses[UseIndex].User; 9751 9752 // This node is about to morph, remove its old self from the CSE maps. 9753 RemoveNodeFromCSEMaps(User); 9754 9755 // The Uses array is sorted, so all the uses for a given User 9756 // are next to each other in the list. 9757 // To help reduce the number of CSE recomputations, process all 9758 // the uses of this user that we can find this way. 9759 do { 9760 unsigned i = Uses[UseIndex].Index; 9761 SDUse &Use = *Uses[UseIndex].Use; 9762 ++UseIndex; 9763 9764 Use.set(To[i]); 9765 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 9766 9767 // Now that we have modified User, add it back to the CSE maps. If it 9768 // already exists there, recursively merge the results together. 9769 AddModifiedNodeToCSEMaps(User); 9770 } 9771 } 9772 9773 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 9774 /// based on their topological order. It returns the maximum id and a vector 9775 /// of the SDNodes* in assigned order by reference. 9776 unsigned SelectionDAG::AssignTopologicalOrder() { 9777 unsigned DAGSize = 0; 9778 9779 // SortedPos tracks the progress of the algorithm. Nodes before it are 9780 // sorted, nodes after it are unsorted. When the algorithm completes 9781 // it is at the end of the list. 9782 allnodes_iterator SortedPos = allnodes_begin(); 9783 9784 // Visit all the nodes. Move nodes with no operands to the front of 9785 // the list immediately. Annotate nodes that do have operands with their 9786 // operand count. Before we do this, the Node Id fields of the nodes 9787 // may contain arbitrary values. After, the Node Id fields for nodes 9788 // before SortedPos will contain the topological sort index, and the 9789 // Node Id fields for nodes At SortedPos and after will contain the 9790 // count of outstanding operands. 9791 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 9792 SDNode *N = &*I++; 9793 checkForCycles(N, this); 9794 unsigned Degree = N->getNumOperands(); 9795 if (Degree == 0) { 9796 // A node with no uses, add it to the result array immediately. 9797 N->setNodeId(DAGSize++); 9798 allnodes_iterator Q(N); 9799 if (Q != SortedPos) 9800 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 9801 assert(SortedPos != AllNodes.end() && "Overran node list"); 9802 ++SortedPos; 9803 } else { 9804 // Temporarily use the Node Id as scratch space for the degree count. 9805 N->setNodeId(Degree); 9806 } 9807 } 9808 9809 // Visit all the nodes. As we iterate, move nodes into sorted order, 9810 // such that by the time the end is reached all nodes will be sorted. 9811 for (SDNode &Node : allnodes()) { 9812 SDNode *N = &Node; 9813 checkForCycles(N, this); 9814 // N is in sorted position, so all its uses have one less operand 9815 // that needs to be sorted. 9816 for (SDNode *P : N->uses()) { 9817 unsigned Degree = P->getNodeId(); 9818 assert(Degree != 0 && "Invalid node degree"); 9819 --Degree; 9820 if (Degree == 0) { 9821 // All of P's operands are sorted, so P may sorted now. 9822 P->setNodeId(DAGSize++); 9823 if (P->getIterator() != SortedPos) 9824 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9825 assert(SortedPos != AllNodes.end() && "Overran node list"); 9826 ++SortedPos; 9827 } else { 9828 // Update P's outstanding operand count. 9829 P->setNodeId(Degree); 9830 } 9831 } 9832 if (Node.getIterator() == SortedPos) { 9833 #ifndef NDEBUG 9834 allnodes_iterator I(N); 9835 SDNode *S = &*++I; 9836 dbgs() << "Overran sorted position:\n"; 9837 S->dumprFull(this); dbgs() << "\n"; 9838 dbgs() << "Checking if this is due to cycles\n"; 9839 checkForCycles(this, true); 9840 #endif 9841 llvm_unreachable(nullptr); 9842 } 9843 } 9844 9845 assert(SortedPos == AllNodes.end() && 9846 "Topological sort incomplete!"); 9847 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9848 "First node in topological sort is not the entry token!"); 9849 assert(AllNodes.front().getNodeId() == 0 && 9850 "First node in topological sort has non-zero id!"); 9851 assert(AllNodes.front().getNumOperands() == 0 && 9852 "First node in topological sort has operands!"); 9853 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9854 "Last node in topologic sort has unexpected id!"); 9855 assert(AllNodes.back().use_empty() && 9856 "Last node in topologic sort has users!"); 9857 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9858 return DAGSize; 9859 } 9860 9861 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9862 /// value is produced by SD. 9863 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 9864 for (SDNode *SD : DB->getSDNodes()) { 9865 if (!SD) 9866 continue; 9867 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9868 SD->setHasDebugValue(true); 9869 } 9870 DbgInfo->add(DB, isParameter); 9871 } 9872 9873 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 9874 9875 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9876 SDValue NewMemOpChain) { 9877 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9878 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9879 // The new memory operation must have the same position as the old load in 9880 // terms of memory dependency. Create a TokenFactor for the old load and new 9881 // memory operation and update uses of the old load's output chain to use that 9882 // TokenFactor. 9883 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9884 return NewMemOpChain; 9885 9886 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9887 OldChain, NewMemOpChain); 9888 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9889 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9890 return TokenFactor; 9891 } 9892 9893 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9894 SDValue NewMemOp) { 9895 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9896 SDValue OldChain = SDValue(OldLoad, 1); 9897 SDValue NewMemOpChain = NewMemOp.getValue(1); 9898 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9899 } 9900 9901 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9902 Function **OutFunction) { 9903 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9904 9905 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9906 auto *Module = MF->getFunction().getParent(); 9907 auto *Function = Module->getFunction(Symbol); 9908 9909 if (OutFunction != nullptr) 9910 *OutFunction = Function; 9911 9912 if (Function != nullptr) { 9913 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9914 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9915 } 9916 9917 std::string ErrorStr; 9918 raw_string_ostream ErrorFormatter(ErrorStr); 9919 9920 ErrorFormatter << "Undefined external symbol "; 9921 ErrorFormatter << '"' << Symbol << '"'; 9922 ErrorFormatter.flush(); 9923 9924 report_fatal_error(ErrorStr); 9925 } 9926 9927 //===----------------------------------------------------------------------===// 9928 // SDNode Class 9929 //===----------------------------------------------------------------------===// 9930 9931 bool llvm::isNullConstant(SDValue V) { 9932 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9933 return Const != nullptr && Const->isZero(); 9934 } 9935 9936 bool llvm::isNullFPConstant(SDValue V) { 9937 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9938 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9939 } 9940 9941 bool llvm::isAllOnesConstant(SDValue V) { 9942 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9943 return Const != nullptr && Const->isAllOnes(); 9944 } 9945 9946 bool llvm::isOneConstant(SDValue V) { 9947 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9948 return Const != nullptr && Const->isOne(); 9949 } 9950 9951 SDValue llvm::peekThroughBitcasts(SDValue V) { 9952 while (V.getOpcode() == ISD::BITCAST) 9953 V = V.getOperand(0); 9954 return V; 9955 } 9956 9957 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9958 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9959 V = V.getOperand(0); 9960 return V; 9961 } 9962 9963 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9964 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9965 V = V.getOperand(0); 9966 return V; 9967 } 9968 9969 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9970 if (V.getOpcode() != ISD::XOR) 9971 return false; 9972 V = peekThroughBitcasts(V.getOperand(1)); 9973 unsigned NumBits = V.getScalarValueSizeInBits(); 9974 ConstantSDNode *C = 9975 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 9976 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 9977 } 9978 9979 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 9980 bool AllowTruncation) { 9981 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9982 return CN; 9983 9984 // SplatVectors can truncate their operands. Ignore that case here unless 9985 // AllowTruncation is set. 9986 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 9987 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 9988 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9989 EVT CVT = CN->getValueType(0); 9990 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 9991 if (AllowTruncation || CVT == VecEltVT) 9992 return CN; 9993 } 9994 } 9995 9996 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9997 BitVector UndefElements; 9998 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 9999 10000 // BuildVectors can truncate their operands. Ignore that case here unless 10001 // AllowTruncation is set. 10002 if (CN && (UndefElements.none() || AllowUndefs)) { 10003 EVT CVT = CN->getValueType(0); 10004 EVT NSVT = N.getValueType().getScalarType(); 10005 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10006 if (AllowTruncation || (CVT == NSVT)) 10007 return CN; 10008 } 10009 } 10010 10011 return nullptr; 10012 } 10013 10014 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10015 bool AllowUndefs, 10016 bool AllowTruncation) { 10017 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10018 return CN; 10019 10020 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10021 BitVector UndefElements; 10022 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10023 10024 // BuildVectors can truncate their operands. Ignore that case here unless 10025 // AllowTruncation is set. 10026 if (CN && (UndefElements.none() || AllowUndefs)) { 10027 EVT CVT = CN->getValueType(0); 10028 EVT NSVT = N.getValueType().getScalarType(); 10029 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10030 if (AllowTruncation || (CVT == NSVT)) 10031 return CN; 10032 } 10033 } 10034 10035 return nullptr; 10036 } 10037 10038 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10039 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10040 return CN; 10041 10042 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10043 BitVector UndefElements; 10044 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10045 if (CN && (UndefElements.none() || AllowUndefs)) 10046 return CN; 10047 } 10048 10049 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10050 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10051 return CN; 10052 10053 return nullptr; 10054 } 10055 10056 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10057 const APInt &DemandedElts, 10058 bool AllowUndefs) { 10059 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10060 return CN; 10061 10062 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10063 BitVector UndefElements; 10064 ConstantFPSDNode *CN = 10065 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10066 if (CN && (UndefElements.none() || AllowUndefs)) 10067 return CN; 10068 } 10069 10070 return nullptr; 10071 } 10072 10073 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10074 // TODO: may want to use peekThroughBitcast() here. 10075 ConstantSDNode *C = 10076 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10077 return C && C->isZero(); 10078 } 10079 10080 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10081 // TODO: may want to use peekThroughBitcast() here. 10082 unsigned BitWidth = N.getScalarValueSizeInBits(); 10083 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10084 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10085 } 10086 10087 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10088 N = peekThroughBitcasts(N); 10089 unsigned BitWidth = N.getScalarValueSizeInBits(); 10090 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10091 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10092 } 10093 10094 HandleSDNode::~HandleSDNode() { 10095 DropOperands(); 10096 } 10097 10098 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10099 const DebugLoc &DL, 10100 const GlobalValue *GA, EVT VT, 10101 int64_t o, unsigned TF) 10102 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10103 TheGlobal = GA; 10104 } 10105 10106 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10107 EVT VT, unsigned SrcAS, 10108 unsigned DestAS) 10109 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10110 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10111 10112 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10113 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10114 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10115 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10116 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10117 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10118 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10119 10120 // We check here that the size of the memory operand fits within the size of 10121 // the MMO. This is because the MMO might indicate only a possible address 10122 // range instead of specifying the affected memory addresses precisely. 10123 // TODO: Make MachineMemOperands aware of scalable vectors. 10124 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10125 "Size mismatch!"); 10126 } 10127 10128 /// Profile - Gather unique data for the node. 10129 /// 10130 void SDNode::Profile(FoldingSetNodeID &ID) const { 10131 AddNodeIDNode(ID, this); 10132 } 10133 10134 namespace { 10135 10136 struct EVTArray { 10137 std::vector<EVT> VTs; 10138 10139 EVTArray() { 10140 VTs.reserve(MVT::VALUETYPE_SIZE); 10141 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10142 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10143 } 10144 }; 10145 10146 } // end anonymous namespace 10147 10148 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10149 static ManagedStatic<EVTArray> SimpleVTArray; 10150 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10151 10152 /// getValueTypeList - Return a pointer to the specified value type. 10153 /// 10154 const EVT *SDNode::getValueTypeList(EVT VT) { 10155 if (VT.isExtended()) { 10156 sys::SmartScopedLock<true> Lock(*VTMutex); 10157 return &(*EVTs->insert(VT).first); 10158 } 10159 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10160 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10161 } 10162 10163 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10164 /// indicated value. This method ignores uses of other values defined by this 10165 /// operation. 10166 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10167 assert(Value < getNumValues() && "Bad value!"); 10168 10169 // TODO: Only iterate over uses of a given value of the node 10170 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10171 if (UI.getUse().getResNo() == Value) { 10172 if (NUses == 0) 10173 return false; 10174 --NUses; 10175 } 10176 } 10177 10178 // Found exactly the right number of uses? 10179 return NUses == 0; 10180 } 10181 10182 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10183 /// value. This method ignores uses of other values defined by this operation. 10184 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10185 assert(Value < getNumValues() && "Bad value!"); 10186 10187 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10188 if (UI.getUse().getResNo() == Value) 10189 return true; 10190 10191 return false; 10192 } 10193 10194 /// isOnlyUserOf - Return true if this node is the only use of N. 10195 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10196 bool Seen = false; 10197 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 10198 SDNode *User = *I; 10199 if (User == this) 10200 Seen = true; 10201 else 10202 return false; 10203 } 10204 10205 return Seen; 10206 } 10207 10208 /// Return true if the only users of N are contained in Nodes. 10209 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10210 bool Seen = false; 10211 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 10212 SDNode *User = *I; 10213 if (llvm::is_contained(Nodes, User)) 10214 Seen = true; 10215 else 10216 return false; 10217 } 10218 10219 return Seen; 10220 } 10221 10222 /// isOperand - Return true if this node is an operand of N. 10223 bool SDValue::isOperandOf(const SDNode *N) const { 10224 return is_contained(N->op_values(), *this); 10225 } 10226 10227 bool SDNode::isOperandOf(const SDNode *N) const { 10228 return any_of(N->op_values(), 10229 [this](SDValue Op) { return this == Op.getNode(); }); 10230 } 10231 10232 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10233 /// be a chain) reaches the specified operand without crossing any 10234 /// side-effecting instructions on any chain path. In practice, this looks 10235 /// through token factors and non-volatile loads. In order to remain efficient, 10236 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10237 /// 10238 /// Note that we only need to examine chains when we're searching for 10239 /// side-effects; SelectionDAG requires that all side-effects are represented 10240 /// by chains, even if another operand would force a specific ordering. This 10241 /// constraint is necessary to allow transformations like splitting loads. 10242 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10243 unsigned Depth) const { 10244 if (*this == Dest) return true; 10245 10246 // Don't search too deeply, we just want to be able to see through 10247 // TokenFactor's etc. 10248 if (Depth == 0) return false; 10249 10250 // If this is a token factor, all inputs to the TF happen in parallel. 10251 if (getOpcode() == ISD::TokenFactor) { 10252 // First, try a shallow search. 10253 if (is_contained((*this)->ops(), Dest)) { 10254 // We found the chain we want as an operand of this TokenFactor. 10255 // Essentially, we reach the chain without side-effects if we could 10256 // serialize the TokenFactor into a simple chain of operations with 10257 // Dest as the last operation. This is automatically true if the 10258 // chain has one use: there are no other ordering constraints. 10259 // If the chain has more than one use, we give up: some other 10260 // use of Dest might force a side-effect between Dest and the current 10261 // node. 10262 if (Dest.hasOneUse()) 10263 return true; 10264 } 10265 // Next, try a deep search: check whether every operand of the TokenFactor 10266 // reaches Dest. 10267 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10268 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10269 }); 10270 } 10271 10272 // Loads don't have side effects, look through them. 10273 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10274 if (Ld->isUnordered()) 10275 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10276 } 10277 return false; 10278 } 10279 10280 bool SDNode::hasPredecessor(const SDNode *N) const { 10281 SmallPtrSet<const SDNode *, 32> Visited; 10282 SmallVector<const SDNode *, 16> Worklist; 10283 Worklist.push_back(this); 10284 return hasPredecessorHelper(N, Visited, Worklist); 10285 } 10286 10287 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10288 this->Flags.intersectWith(Flags); 10289 } 10290 10291 SDValue 10292 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10293 ArrayRef<ISD::NodeType> CandidateBinOps, 10294 bool AllowPartials) { 10295 // The pattern must end in an extract from index 0. 10296 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10297 !isNullConstant(Extract->getOperand(1))) 10298 return SDValue(); 10299 10300 // Match against one of the candidate binary ops. 10301 SDValue Op = Extract->getOperand(0); 10302 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10303 return Op.getOpcode() == unsigned(BinOp); 10304 })) 10305 return SDValue(); 10306 10307 // Floating-point reductions may require relaxed constraints on the final step 10308 // of the reduction because they may reorder intermediate operations. 10309 unsigned CandidateBinOp = Op.getOpcode(); 10310 if (Op.getValueType().isFloatingPoint()) { 10311 SDNodeFlags Flags = Op->getFlags(); 10312 switch (CandidateBinOp) { 10313 case ISD::FADD: 10314 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10315 return SDValue(); 10316 break; 10317 default: 10318 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10319 } 10320 } 10321 10322 // Matching failed - attempt to see if we did enough stages that a partial 10323 // reduction from a subvector is possible. 10324 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10325 if (!AllowPartials || !Op) 10326 return SDValue(); 10327 EVT OpVT = Op.getValueType(); 10328 EVT OpSVT = OpVT.getScalarType(); 10329 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10330 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10331 return SDValue(); 10332 BinOp = (ISD::NodeType)CandidateBinOp; 10333 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10334 getVectorIdxConstant(0, SDLoc(Op))); 10335 }; 10336 10337 // At each stage, we're looking for something that looks like: 10338 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10339 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10340 // i32 undef, i32 undef, i32 undef, i32 undef> 10341 // %a = binop <8 x i32> %op, %s 10342 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10343 // we expect something like: 10344 // <4,5,6,7,u,u,u,u> 10345 // <2,3,u,u,u,u,u,u> 10346 // <1,u,u,u,u,u,u,u> 10347 // While a partial reduction match would be: 10348 // <2,3,u,u,u,u,u,u> 10349 // <1,u,u,u,u,u,u,u> 10350 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10351 SDValue PrevOp; 10352 for (unsigned i = 0; i < Stages; ++i) { 10353 unsigned MaskEnd = (1 << i); 10354 10355 if (Op.getOpcode() != CandidateBinOp) 10356 return PartialReduction(PrevOp, MaskEnd); 10357 10358 SDValue Op0 = Op.getOperand(0); 10359 SDValue Op1 = Op.getOperand(1); 10360 10361 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10362 if (Shuffle) { 10363 Op = Op1; 10364 } else { 10365 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10366 Op = Op0; 10367 } 10368 10369 // The first operand of the shuffle should be the same as the other operand 10370 // of the binop. 10371 if (!Shuffle || Shuffle->getOperand(0) != Op) 10372 return PartialReduction(PrevOp, MaskEnd); 10373 10374 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10375 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10376 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10377 return PartialReduction(PrevOp, MaskEnd); 10378 10379 PrevOp = Op; 10380 } 10381 10382 // Handle subvector reductions, which tend to appear after the shuffle 10383 // reduction stages. 10384 while (Op.getOpcode() == CandidateBinOp) { 10385 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10386 SDValue Op0 = Op.getOperand(0); 10387 SDValue Op1 = Op.getOperand(1); 10388 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10389 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10390 Op0.getOperand(0) != Op1.getOperand(0)) 10391 break; 10392 SDValue Src = Op0.getOperand(0); 10393 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10394 if (NumSrcElts != (2 * NumElts)) 10395 break; 10396 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10397 Op1.getConstantOperandAPInt(1) == NumElts) && 10398 !(Op1.getConstantOperandAPInt(1) == 0 && 10399 Op0.getConstantOperandAPInt(1) == NumElts)) 10400 break; 10401 Op = Src; 10402 } 10403 10404 BinOp = (ISD::NodeType)CandidateBinOp; 10405 return Op; 10406 } 10407 10408 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10409 assert(N->getNumValues() == 1 && 10410 "Can't unroll a vector with multiple results!"); 10411 10412 EVT VT = N->getValueType(0); 10413 unsigned NE = VT.getVectorNumElements(); 10414 EVT EltVT = VT.getVectorElementType(); 10415 SDLoc dl(N); 10416 10417 SmallVector<SDValue, 8> Scalars; 10418 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10419 10420 // If ResNE is 0, fully unroll the vector op. 10421 if (ResNE == 0) 10422 ResNE = NE; 10423 else if (NE > ResNE) 10424 NE = ResNE; 10425 10426 unsigned i; 10427 for (i= 0; i != NE; ++i) { 10428 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10429 SDValue Operand = N->getOperand(j); 10430 EVT OperandVT = Operand.getValueType(); 10431 if (OperandVT.isVector()) { 10432 // A vector operand; extract a single element. 10433 EVT OperandEltVT = OperandVT.getVectorElementType(); 10434 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10435 Operand, getVectorIdxConstant(i, dl)); 10436 } else { 10437 // A scalar operand; just use it as is. 10438 Operands[j] = Operand; 10439 } 10440 } 10441 10442 switch (N->getOpcode()) { 10443 default: { 10444 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10445 N->getFlags())); 10446 break; 10447 } 10448 case ISD::VSELECT: 10449 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10450 break; 10451 case ISD::SHL: 10452 case ISD::SRA: 10453 case ISD::SRL: 10454 case ISD::ROTL: 10455 case ISD::ROTR: 10456 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10457 getShiftAmountOperand(Operands[0].getValueType(), 10458 Operands[1]))); 10459 break; 10460 case ISD::SIGN_EXTEND_INREG: { 10461 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10462 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10463 Operands[0], 10464 getValueType(ExtVT))); 10465 } 10466 } 10467 } 10468 10469 for (; i < ResNE; ++i) 10470 Scalars.push_back(getUNDEF(EltVT)); 10471 10472 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10473 return getBuildVector(VecVT, dl, Scalars); 10474 } 10475 10476 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10477 SDNode *N, unsigned ResNE) { 10478 unsigned Opcode = N->getOpcode(); 10479 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10480 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10481 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10482 "Expected an overflow opcode"); 10483 10484 EVT ResVT = N->getValueType(0); 10485 EVT OvVT = N->getValueType(1); 10486 EVT ResEltVT = ResVT.getVectorElementType(); 10487 EVT OvEltVT = OvVT.getVectorElementType(); 10488 SDLoc dl(N); 10489 10490 // If ResNE is 0, fully unroll the vector op. 10491 unsigned NE = ResVT.getVectorNumElements(); 10492 if (ResNE == 0) 10493 ResNE = NE; 10494 else if (NE > ResNE) 10495 NE = ResNE; 10496 10497 SmallVector<SDValue, 8> LHSScalars; 10498 SmallVector<SDValue, 8> RHSScalars; 10499 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10500 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10501 10502 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10503 SDVTList VTs = getVTList(ResEltVT, SVT); 10504 SmallVector<SDValue, 8> ResScalars; 10505 SmallVector<SDValue, 8> OvScalars; 10506 for (unsigned i = 0; i < NE; ++i) { 10507 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10508 SDValue Ov = 10509 getSelect(dl, OvEltVT, Res.getValue(1), 10510 getBoolConstant(true, dl, OvEltVT, ResVT), 10511 getConstant(0, dl, OvEltVT)); 10512 10513 ResScalars.push_back(Res); 10514 OvScalars.push_back(Ov); 10515 } 10516 10517 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10518 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10519 10520 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10521 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10522 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10523 getBuildVector(NewOvVT, dl, OvScalars)); 10524 } 10525 10526 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10527 LoadSDNode *Base, 10528 unsigned Bytes, 10529 int Dist) const { 10530 if (LD->isVolatile() || Base->isVolatile()) 10531 return false; 10532 // TODO: probably too restrictive for atomics, revisit 10533 if (!LD->isSimple()) 10534 return false; 10535 if (LD->isIndexed() || Base->isIndexed()) 10536 return false; 10537 if (LD->getChain() != Base->getChain()) 10538 return false; 10539 EVT VT = LD->getValueType(0); 10540 if (VT.getSizeInBits() / 8 != Bytes) 10541 return false; 10542 10543 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10544 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10545 10546 int64_t Offset = 0; 10547 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 10548 return (Dist * Bytes == Offset); 10549 return false; 10550 } 10551 10552 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 10553 /// if it cannot be inferred. 10554 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 10555 // If this is a GlobalAddress + cst, return the alignment. 10556 const GlobalValue *GV = nullptr; 10557 int64_t GVOffset = 0; 10558 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 10559 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 10560 KnownBits Known(PtrWidth); 10561 llvm::computeKnownBits(GV, Known, getDataLayout()); 10562 unsigned AlignBits = Known.countMinTrailingZeros(); 10563 if (AlignBits) 10564 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 10565 } 10566 10567 // If this is a direct reference to a stack slot, use information about the 10568 // stack slot's alignment. 10569 int FrameIdx = INT_MIN; 10570 int64_t FrameOffset = 0; 10571 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 10572 FrameIdx = FI->getIndex(); 10573 } else if (isBaseWithConstantOffset(Ptr) && 10574 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 10575 // Handle FI+Cst 10576 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 10577 FrameOffset = Ptr.getConstantOperandVal(1); 10578 } 10579 10580 if (FrameIdx != INT_MIN) { 10581 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 10582 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 10583 } 10584 10585 return None; 10586 } 10587 10588 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 10589 /// which is split (or expanded) into two not necessarily identical pieces. 10590 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 10591 // Currently all types are split in half. 10592 EVT LoVT, HiVT; 10593 if (!VT.isVector()) 10594 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 10595 else 10596 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 10597 10598 return std::make_pair(LoVT, HiVT); 10599 } 10600 10601 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 10602 /// type, dependent on an enveloping VT that has been split into two identical 10603 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 10604 std::pair<EVT, EVT> 10605 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 10606 bool *HiIsEmpty) const { 10607 EVT EltTp = VT.getVectorElementType(); 10608 // Examples: 10609 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 10610 // custom VL=9 with enveloping VL=8/8 yields 8/1 10611 // custom VL=10 with enveloping VL=8/8 yields 8/2 10612 // etc. 10613 ElementCount VTNumElts = VT.getVectorElementCount(); 10614 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 10615 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 10616 "Mixing fixed width and scalable vectors when enveloping a type"); 10617 EVT LoVT, HiVT; 10618 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 10619 LoVT = EnvVT; 10620 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 10621 *HiIsEmpty = false; 10622 } else { 10623 // Flag that hi type has zero storage size, but return split envelop type 10624 // (this would be easier if vector types with zero elements were allowed). 10625 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 10626 HiVT = EnvVT; 10627 *HiIsEmpty = true; 10628 } 10629 return std::make_pair(LoVT, HiVT); 10630 } 10631 10632 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 10633 /// low/high part. 10634 std::pair<SDValue, SDValue> 10635 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 10636 const EVT &HiVT) { 10637 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 10638 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 10639 "Splitting vector with an invalid mixture of fixed and scalable " 10640 "vector types"); 10641 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 10642 N.getValueType().getVectorMinNumElements() && 10643 "More vector elements requested than available!"); 10644 SDValue Lo, Hi; 10645 Lo = 10646 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 10647 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 10648 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 10649 // IDX with the runtime scaling factor of the result vector type. For 10650 // fixed-width result vectors, that runtime scaling factor is 1. 10651 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 10652 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 10653 return std::make_pair(Lo, Hi); 10654 } 10655 10656 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 10657 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 10658 EVT VT = N.getValueType(); 10659 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 10660 NextPowerOf2(VT.getVectorNumElements())); 10661 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 10662 getVectorIdxConstant(0, DL)); 10663 } 10664 10665 void SelectionDAG::ExtractVectorElements(SDValue Op, 10666 SmallVectorImpl<SDValue> &Args, 10667 unsigned Start, unsigned Count, 10668 EVT EltVT) { 10669 EVT VT = Op.getValueType(); 10670 if (Count == 0) 10671 Count = VT.getVectorNumElements(); 10672 if (EltVT == EVT()) 10673 EltVT = VT.getVectorElementType(); 10674 SDLoc SL(Op); 10675 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 10676 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 10677 getVectorIdxConstant(i, SL))); 10678 } 10679 } 10680 10681 // getAddressSpace - Return the address space this GlobalAddress belongs to. 10682 unsigned GlobalAddressSDNode::getAddressSpace() const { 10683 return getGlobal()->getType()->getAddressSpace(); 10684 } 10685 10686 Type *ConstantPoolSDNode::getType() const { 10687 if (isMachineConstantPoolEntry()) 10688 return Val.MachineCPVal->getType(); 10689 return Val.ConstVal->getType(); 10690 } 10691 10692 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 10693 unsigned &SplatBitSize, 10694 bool &HasAnyUndefs, 10695 unsigned MinSplatBits, 10696 bool IsBigEndian) const { 10697 EVT VT = getValueType(0); 10698 assert(VT.isVector() && "Expected a vector type"); 10699 unsigned VecWidth = VT.getSizeInBits(); 10700 if (MinSplatBits > VecWidth) 10701 return false; 10702 10703 // FIXME: The widths are based on this node's type, but build vectors can 10704 // truncate their operands. 10705 SplatValue = APInt(VecWidth, 0); 10706 SplatUndef = APInt(VecWidth, 0); 10707 10708 // Get the bits. Bits with undefined values (when the corresponding element 10709 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 10710 // in SplatValue. If any of the values are not constant, give up and return 10711 // false. 10712 unsigned int NumOps = getNumOperands(); 10713 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 10714 unsigned EltWidth = VT.getScalarSizeInBits(); 10715 10716 for (unsigned j = 0; j < NumOps; ++j) { 10717 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 10718 SDValue OpVal = getOperand(i); 10719 unsigned BitPos = j * EltWidth; 10720 10721 if (OpVal.isUndef()) 10722 SplatUndef.setBits(BitPos, BitPos + EltWidth); 10723 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 10724 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 10725 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 10726 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 10727 else 10728 return false; 10729 } 10730 10731 // The build_vector is all constants or undefs. Find the smallest element 10732 // size that splats the vector. 10733 HasAnyUndefs = (SplatUndef != 0); 10734 10735 // FIXME: This does not work for vectors with elements less than 8 bits. 10736 while (VecWidth > 8) { 10737 unsigned HalfSize = VecWidth / 2; 10738 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 10739 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 10740 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 10741 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 10742 10743 // If the two halves do not match (ignoring undef bits), stop here. 10744 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 10745 MinSplatBits > HalfSize) 10746 break; 10747 10748 SplatValue = HighValue | LowValue; 10749 SplatUndef = HighUndef & LowUndef; 10750 10751 VecWidth = HalfSize; 10752 } 10753 10754 SplatBitSize = VecWidth; 10755 return true; 10756 } 10757 10758 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 10759 BitVector *UndefElements) const { 10760 unsigned NumOps = getNumOperands(); 10761 if (UndefElements) { 10762 UndefElements->clear(); 10763 UndefElements->resize(NumOps); 10764 } 10765 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10766 if (!DemandedElts) 10767 return SDValue(); 10768 SDValue Splatted; 10769 for (unsigned i = 0; i != NumOps; ++i) { 10770 if (!DemandedElts[i]) 10771 continue; 10772 SDValue Op = getOperand(i); 10773 if (Op.isUndef()) { 10774 if (UndefElements) 10775 (*UndefElements)[i] = true; 10776 } else if (!Splatted) { 10777 Splatted = Op; 10778 } else if (Splatted != Op) { 10779 return SDValue(); 10780 } 10781 } 10782 10783 if (!Splatted) { 10784 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 10785 assert(getOperand(FirstDemandedIdx).isUndef() && 10786 "Can only have a splat without a constant for all undefs."); 10787 return getOperand(FirstDemandedIdx); 10788 } 10789 10790 return Splatted; 10791 } 10792 10793 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 10794 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10795 return getSplatValue(DemandedElts, UndefElements); 10796 } 10797 10798 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 10799 SmallVectorImpl<SDValue> &Sequence, 10800 BitVector *UndefElements) const { 10801 unsigned NumOps = getNumOperands(); 10802 Sequence.clear(); 10803 if (UndefElements) { 10804 UndefElements->clear(); 10805 UndefElements->resize(NumOps); 10806 } 10807 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10808 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10809 return false; 10810 10811 // Set the undefs even if we don't find a sequence (like getSplatValue). 10812 if (UndefElements) 10813 for (unsigned I = 0; I != NumOps; ++I) 10814 if (DemandedElts[I] && getOperand(I).isUndef()) 10815 (*UndefElements)[I] = true; 10816 10817 // Iteratively widen the sequence length looking for repetitions. 10818 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10819 Sequence.append(SeqLen, SDValue()); 10820 for (unsigned I = 0; I != NumOps; ++I) { 10821 if (!DemandedElts[I]) 10822 continue; 10823 SDValue &SeqOp = Sequence[I % SeqLen]; 10824 SDValue Op = getOperand(I); 10825 if (Op.isUndef()) { 10826 if (!SeqOp) 10827 SeqOp = Op; 10828 continue; 10829 } 10830 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10831 Sequence.clear(); 10832 break; 10833 } 10834 SeqOp = Op; 10835 } 10836 if (!Sequence.empty()) 10837 return true; 10838 } 10839 10840 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10841 return false; 10842 } 10843 10844 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10845 BitVector *UndefElements) const { 10846 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10847 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10848 } 10849 10850 ConstantSDNode * 10851 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10852 BitVector *UndefElements) const { 10853 return dyn_cast_or_null<ConstantSDNode>( 10854 getSplatValue(DemandedElts, UndefElements)); 10855 } 10856 10857 ConstantSDNode * 10858 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10859 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10860 } 10861 10862 ConstantFPSDNode * 10863 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10864 BitVector *UndefElements) const { 10865 return dyn_cast_or_null<ConstantFPSDNode>( 10866 getSplatValue(DemandedElts, UndefElements)); 10867 } 10868 10869 ConstantFPSDNode * 10870 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10871 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10872 } 10873 10874 int32_t 10875 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10876 uint32_t BitWidth) const { 10877 if (ConstantFPSDNode *CN = 10878 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10879 bool IsExact; 10880 APSInt IntVal(BitWidth); 10881 const APFloat &APF = CN->getValueAPF(); 10882 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10883 APFloat::opOK || 10884 !IsExact) 10885 return -1; 10886 10887 return IntVal.exactLogBase2(); 10888 } 10889 return -1; 10890 } 10891 10892 bool BuildVectorSDNode::isConstant() const { 10893 for (const SDValue &Op : op_values()) { 10894 unsigned Opc = Op.getOpcode(); 10895 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 10896 return false; 10897 } 10898 return true; 10899 } 10900 10901 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 10902 // Find the first non-undef value in the shuffle mask. 10903 unsigned i, e; 10904 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 10905 /* search */; 10906 10907 // If all elements are undefined, this shuffle can be considered a splat 10908 // (although it should eventually get simplified away completely). 10909 if (i == e) 10910 return true; 10911 10912 // Make sure all remaining elements are either undef or the same as the first 10913 // non-undef value. 10914 for (int Idx = Mask[i]; i != e; ++i) 10915 if (Mask[i] >= 0 && Mask[i] != Idx) 10916 return false; 10917 return true; 10918 } 10919 10920 // Returns the SDNode if it is a constant integer BuildVector 10921 // or constant integer. 10922 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 10923 if (isa<ConstantSDNode>(N)) 10924 return N.getNode(); 10925 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 10926 return N.getNode(); 10927 // Treat a GlobalAddress supporting constant offset folding as a 10928 // constant integer. 10929 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 10930 if (GA->getOpcode() == ISD::GlobalAddress && 10931 TLI->isOffsetFoldingLegal(GA)) 10932 return GA; 10933 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 10934 isa<ConstantSDNode>(N.getOperand(0))) 10935 return N.getNode(); 10936 return nullptr; 10937 } 10938 10939 // Returns the SDNode if it is a constant float BuildVector 10940 // or constant float. 10941 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 10942 if (isa<ConstantFPSDNode>(N)) 10943 return N.getNode(); 10944 10945 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 10946 return N.getNode(); 10947 10948 return nullptr; 10949 } 10950 10951 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 10952 assert(!Node->OperandList && "Node already has operands"); 10953 assert(SDNode::getMaxNumOperands() >= Vals.size() && 10954 "too many operands to fit into SDNode"); 10955 SDUse *Ops = OperandRecycler.allocate( 10956 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 10957 10958 bool IsDivergent = false; 10959 for (unsigned I = 0; I != Vals.size(); ++I) { 10960 Ops[I].setUser(Node); 10961 Ops[I].setInitial(Vals[I]); 10962 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 10963 IsDivergent |= Ops[I].getNode()->isDivergent(); 10964 } 10965 Node->NumOperands = Vals.size(); 10966 Node->OperandList = Ops; 10967 if (!TLI->isSDNodeAlwaysUniform(Node)) { 10968 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 10969 Node->SDNodeBits.IsDivergent = IsDivergent; 10970 } 10971 checkForCycles(Node); 10972 } 10973 10974 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 10975 SmallVectorImpl<SDValue> &Vals) { 10976 size_t Limit = SDNode::getMaxNumOperands(); 10977 while (Vals.size() > Limit) { 10978 unsigned SliceIdx = Vals.size() - Limit; 10979 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 10980 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 10981 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 10982 Vals.emplace_back(NewTF); 10983 } 10984 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 10985 } 10986 10987 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 10988 EVT VT, SDNodeFlags Flags) { 10989 switch (Opcode) { 10990 default: 10991 return SDValue(); 10992 case ISD::ADD: 10993 case ISD::OR: 10994 case ISD::XOR: 10995 case ISD::UMAX: 10996 return getConstant(0, DL, VT); 10997 case ISD::MUL: 10998 return getConstant(1, DL, VT); 10999 case ISD::AND: 11000 case ISD::UMIN: 11001 return getAllOnesConstant(DL, VT); 11002 case ISD::SMAX: 11003 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11004 case ISD::SMIN: 11005 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11006 case ISD::FADD: 11007 return getConstantFP(-0.0, DL, VT); 11008 case ISD::FMUL: 11009 return getConstantFP(1.0, DL, VT); 11010 case ISD::FMINNUM: 11011 case ISD::FMAXNUM: { 11012 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11013 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11014 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11015 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11016 APFloat::getLargest(Semantics); 11017 if (Opcode == ISD::FMAXNUM) 11018 NeutralAF.changeSign(); 11019 11020 return getConstantFP(NeutralAF, DL, VT); 11021 } 11022 } 11023 } 11024 11025 #ifndef NDEBUG 11026 static void checkForCyclesHelper(const SDNode *N, 11027 SmallPtrSetImpl<const SDNode*> &Visited, 11028 SmallPtrSetImpl<const SDNode*> &Checked, 11029 const llvm::SelectionDAG *DAG) { 11030 // If this node has already been checked, don't check it again. 11031 if (Checked.count(N)) 11032 return; 11033 11034 // If a node has already been visited on this depth-first walk, reject it as 11035 // a cycle. 11036 if (!Visited.insert(N).second) { 11037 errs() << "Detected cycle in SelectionDAG\n"; 11038 dbgs() << "Offending node:\n"; 11039 N->dumprFull(DAG); dbgs() << "\n"; 11040 abort(); 11041 } 11042 11043 for (const SDValue &Op : N->op_values()) 11044 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11045 11046 Checked.insert(N); 11047 Visited.erase(N); 11048 } 11049 #endif 11050 11051 void llvm::checkForCycles(const llvm::SDNode *N, 11052 const llvm::SelectionDAG *DAG, 11053 bool force) { 11054 #ifndef NDEBUG 11055 bool check = force; 11056 #ifdef EXPENSIVE_CHECKS 11057 check = true; 11058 #endif // EXPENSIVE_CHECKS 11059 if (check) { 11060 assert(N && "Checking nonexistent SDNode"); 11061 SmallPtrSet<const SDNode*, 32> visited; 11062 SmallPtrSet<const SDNode*, 32> checked; 11063 checkForCyclesHelper(N, visited, checked, DAG); 11064 } 11065 #endif // !NDEBUG 11066 } 11067 11068 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11069 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11070 } 11071