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 (ISD::BUILD_VECTOR != LHS.getOpcode() || 346 ISD::BUILD_VECTOR != RHS.getOpcode()) 347 return false; 348 349 EVT SVT = LHS.getValueType().getScalarType(); 350 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 351 SDValue LHSOp = LHS.getOperand(i); 352 SDValue RHSOp = RHS.getOperand(i); 353 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 354 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 355 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 356 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 357 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 358 return false; 359 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 360 LHSOp.getValueType() != RHSOp.getValueType())) 361 return false; 362 if (!Match(LHSCst, RHSCst)) 363 return false; 364 } 365 return true; 366 } 367 368 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 369 switch (VecReduceOpcode) { 370 default: 371 llvm_unreachable("Expected VECREDUCE opcode"); 372 case ISD::VECREDUCE_FADD: 373 case ISD::VECREDUCE_SEQ_FADD: 374 return ISD::FADD; 375 case ISD::VECREDUCE_FMUL: 376 case ISD::VECREDUCE_SEQ_FMUL: 377 return ISD::FMUL; 378 case ISD::VECREDUCE_ADD: 379 return ISD::ADD; 380 case ISD::VECREDUCE_MUL: 381 return ISD::MUL; 382 case ISD::VECREDUCE_AND: 383 return ISD::AND; 384 case ISD::VECREDUCE_OR: 385 return ISD::OR; 386 case ISD::VECREDUCE_XOR: 387 return ISD::XOR; 388 case ISD::VECREDUCE_SMAX: 389 return ISD::SMAX; 390 case ISD::VECREDUCE_SMIN: 391 return ISD::SMIN; 392 case ISD::VECREDUCE_UMAX: 393 return ISD::UMAX; 394 case ISD::VECREDUCE_UMIN: 395 return ISD::UMIN; 396 case ISD::VECREDUCE_FMAX: 397 return ISD::FMAXNUM; 398 case ISD::VECREDUCE_FMIN: 399 return ISD::FMINNUM; 400 } 401 } 402 403 bool ISD::isVPOpcode(unsigned Opcode) { 404 switch (Opcode) { 405 default: 406 return false; 407 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \ 408 case ISD::SDOPC: \ 409 return true; 410 #include "llvm/IR/VPIntrinsics.def" 411 } 412 } 413 414 /// The operand position of the vector mask. 415 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 416 switch (Opcode) { 417 default: 418 return None; 419 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...) \ 420 case ISD::SDOPC: \ 421 return MASKPOS; 422 #include "llvm/IR/VPIntrinsics.def" 423 } 424 } 425 426 /// The operand position of the explicit vector length parameter. 427 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 428 switch (Opcode) { 429 default: 430 return None; 431 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 432 case ISD::SDOPC: \ 433 return EVLPOS; 434 #include "llvm/IR/VPIntrinsics.def" 435 } 436 } 437 438 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 439 switch (ExtType) { 440 case ISD::EXTLOAD: 441 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 442 case ISD::SEXTLOAD: 443 return ISD::SIGN_EXTEND; 444 case ISD::ZEXTLOAD: 445 return ISD::ZERO_EXTEND; 446 default: 447 break; 448 } 449 450 llvm_unreachable("Invalid LoadExtType"); 451 } 452 453 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 454 // To perform this operation, we just need to swap the L and G bits of the 455 // operation. 456 unsigned OldL = (Operation >> 2) & 1; 457 unsigned OldG = (Operation >> 1) & 1; 458 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 459 (OldL << 1) | // New G bit 460 (OldG << 2)); // New L bit. 461 } 462 463 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 464 unsigned Operation = Op; 465 if (isIntegerLike) 466 Operation ^= 7; // Flip L, G, E bits, but not U. 467 else 468 Operation ^= 15; // Flip all of the condition bits. 469 470 if (Operation > ISD::SETTRUE2) 471 Operation &= ~8; // Don't let N and U bits get set. 472 473 return ISD::CondCode(Operation); 474 } 475 476 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 477 return getSetCCInverseImpl(Op, Type.isInteger()); 478 } 479 480 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 481 bool isIntegerLike) { 482 return getSetCCInverseImpl(Op, isIntegerLike); 483 } 484 485 /// For an integer comparison, return 1 if the comparison is a signed operation 486 /// and 2 if the result is an unsigned comparison. Return zero if the operation 487 /// does not depend on the sign of the input (setne and seteq). 488 static int isSignedOp(ISD::CondCode Opcode) { 489 switch (Opcode) { 490 default: llvm_unreachable("Illegal integer setcc operation!"); 491 case ISD::SETEQ: 492 case ISD::SETNE: return 0; 493 case ISD::SETLT: 494 case ISD::SETLE: 495 case ISD::SETGT: 496 case ISD::SETGE: return 1; 497 case ISD::SETULT: 498 case ISD::SETULE: 499 case ISD::SETUGT: 500 case ISD::SETUGE: return 2; 501 } 502 } 503 504 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 505 EVT Type) { 506 bool IsInteger = Type.isInteger(); 507 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 508 // Cannot fold a signed integer setcc with an unsigned integer setcc. 509 return ISD::SETCC_INVALID; 510 511 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 512 513 // If the N and U bits get set, then the resultant comparison DOES suddenly 514 // care about orderedness, and it is true when ordered. 515 if (Op > ISD::SETTRUE2) 516 Op &= ~16; // Clear the U bit if the N bit is set. 517 518 // Canonicalize illegal integer setcc's. 519 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 520 Op = ISD::SETNE; 521 522 return ISD::CondCode(Op); 523 } 524 525 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 526 EVT Type) { 527 bool IsInteger = Type.isInteger(); 528 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 529 // Cannot fold a signed setcc with an unsigned setcc. 530 return ISD::SETCC_INVALID; 531 532 // Combine all of the condition bits. 533 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 534 535 // Canonicalize illegal integer setcc's. 536 if (IsInteger) { 537 switch (Result) { 538 default: break; 539 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 540 case ISD::SETOEQ: // SETEQ & SETU[LG]E 541 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 542 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 543 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 544 } 545 } 546 547 return Result; 548 } 549 550 //===----------------------------------------------------------------------===// 551 // SDNode Profile Support 552 //===----------------------------------------------------------------------===// 553 554 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 555 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 556 ID.AddInteger(OpC); 557 } 558 559 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 560 /// solely with their pointer. 561 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 562 ID.AddPointer(VTList.VTs); 563 } 564 565 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 566 static void AddNodeIDOperands(FoldingSetNodeID &ID, 567 ArrayRef<SDValue> Ops) { 568 for (auto& Op : Ops) { 569 ID.AddPointer(Op.getNode()); 570 ID.AddInteger(Op.getResNo()); 571 } 572 } 573 574 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 575 static void AddNodeIDOperands(FoldingSetNodeID &ID, 576 ArrayRef<SDUse> Ops) { 577 for (auto& Op : Ops) { 578 ID.AddPointer(Op.getNode()); 579 ID.AddInteger(Op.getResNo()); 580 } 581 } 582 583 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 584 SDVTList VTList, ArrayRef<SDValue> OpList) { 585 AddNodeIDOpcode(ID, OpC); 586 AddNodeIDValueTypes(ID, VTList); 587 AddNodeIDOperands(ID, OpList); 588 } 589 590 /// If this is an SDNode with special info, add this info to the NodeID data. 591 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 592 switch (N->getOpcode()) { 593 case ISD::TargetExternalSymbol: 594 case ISD::ExternalSymbol: 595 case ISD::MCSymbol: 596 llvm_unreachable("Should only be used on nodes with operands"); 597 default: break; // Normal nodes don't need extra info. 598 case ISD::TargetConstant: 599 case ISD::Constant: { 600 const ConstantSDNode *C = cast<ConstantSDNode>(N); 601 ID.AddPointer(C->getConstantIntValue()); 602 ID.AddBoolean(C->isOpaque()); 603 break; 604 } 605 case ISD::TargetConstantFP: 606 case ISD::ConstantFP: 607 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 608 break; 609 case ISD::TargetGlobalAddress: 610 case ISD::GlobalAddress: 611 case ISD::TargetGlobalTLSAddress: 612 case ISD::GlobalTLSAddress: { 613 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 614 ID.AddPointer(GA->getGlobal()); 615 ID.AddInteger(GA->getOffset()); 616 ID.AddInteger(GA->getTargetFlags()); 617 break; 618 } 619 case ISD::BasicBlock: 620 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 621 break; 622 case ISD::Register: 623 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 624 break; 625 case ISD::RegisterMask: 626 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 627 break; 628 case ISD::SRCVALUE: 629 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 630 break; 631 case ISD::FrameIndex: 632 case ISD::TargetFrameIndex: 633 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 634 break; 635 case ISD::LIFETIME_START: 636 case ISD::LIFETIME_END: 637 if (cast<LifetimeSDNode>(N)->hasOffset()) { 638 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 639 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 640 } 641 break; 642 case ISD::PSEUDO_PROBE: 643 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 644 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 645 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 646 break; 647 case ISD::JumpTable: 648 case ISD::TargetJumpTable: 649 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 650 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 651 break; 652 case ISD::ConstantPool: 653 case ISD::TargetConstantPool: { 654 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 655 ID.AddInteger(CP->getAlign().value()); 656 ID.AddInteger(CP->getOffset()); 657 if (CP->isMachineConstantPoolEntry()) 658 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 659 else 660 ID.AddPointer(CP->getConstVal()); 661 ID.AddInteger(CP->getTargetFlags()); 662 break; 663 } 664 case ISD::TargetIndex: { 665 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 666 ID.AddInteger(TI->getIndex()); 667 ID.AddInteger(TI->getOffset()); 668 ID.AddInteger(TI->getTargetFlags()); 669 break; 670 } 671 case ISD::LOAD: { 672 const LoadSDNode *LD = cast<LoadSDNode>(N); 673 ID.AddInteger(LD->getMemoryVT().getRawBits()); 674 ID.AddInteger(LD->getRawSubclassData()); 675 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 676 break; 677 } 678 case ISD::STORE: { 679 const StoreSDNode *ST = cast<StoreSDNode>(N); 680 ID.AddInteger(ST->getMemoryVT().getRawBits()); 681 ID.AddInteger(ST->getRawSubclassData()); 682 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 683 break; 684 } 685 case ISD::MLOAD: { 686 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 687 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 688 ID.AddInteger(MLD->getRawSubclassData()); 689 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 690 break; 691 } 692 case ISD::MSTORE: { 693 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 694 ID.AddInteger(MST->getMemoryVT().getRawBits()); 695 ID.AddInteger(MST->getRawSubclassData()); 696 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 697 break; 698 } 699 case ISD::MGATHER: { 700 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 701 ID.AddInteger(MG->getMemoryVT().getRawBits()); 702 ID.AddInteger(MG->getRawSubclassData()); 703 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 704 break; 705 } 706 case ISD::MSCATTER: { 707 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 708 ID.AddInteger(MS->getMemoryVT().getRawBits()); 709 ID.AddInteger(MS->getRawSubclassData()); 710 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 711 break; 712 } 713 case ISD::ATOMIC_CMP_SWAP: 714 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 715 case ISD::ATOMIC_SWAP: 716 case ISD::ATOMIC_LOAD_ADD: 717 case ISD::ATOMIC_LOAD_SUB: 718 case ISD::ATOMIC_LOAD_AND: 719 case ISD::ATOMIC_LOAD_CLR: 720 case ISD::ATOMIC_LOAD_OR: 721 case ISD::ATOMIC_LOAD_XOR: 722 case ISD::ATOMIC_LOAD_NAND: 723 case ISD::ATOMIC_LOAD_MIN: 724 case ISD::ATOMIC_LOAD_MAX: 725 case ISD::ATOMIC_LOAD_UMIN: 726 case ISD::ATOMIC_LOAD_UMAX: 727 case ISD::ATOMIC_LOAD: 728 case ISD::ATOMIC_STORE: { 729 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 730 ID.AddInteger(AT->getMemoryVT().getRawBits()); 731 ID.AddInteger(AT->getRawSubclassData()); 732 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 733 break; 734 } 735 case ISD::PREFETCH: { 736 const MemSDNode *PF = cast<MemSDNode>(N); 737 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 738 break; 739 } 740 case ISD::VECTOR_SHUFFLE: { 741 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 742 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 743 i != e; ++i) 744 ID.AddInteger(SVN->getMaskElt(i)); 745 break; 746 } 747 case ISD::TargetBlockAddress: 748 case ISD::BlockAddress: { 749 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 750 ID.AddPointer(BA->getBlockAddress()); 751 ID.AddInteger(BA->getOffset()); 752 ID.AddInteger(BA->getTargetFlags()); 753 break; 754 } 755 } // end switch (N->getOpcode()) 756 757 // Target specific memory nodes could also have address spaces to check. 758 if (N->isTargetMemoryOpcode()) 759 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 760 } 761 762 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 763 /// data. 764 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 765 AddNodeIDOpcode(ID, N->getOpcode()); 766 // Add the return value info. 767 AddNodeIDValueTypes(ID, N->getVTList()); 768 // Add the operand info. 769 AddNodeIDOperands(ID, N->ops()); 770 771 // Handle SDNode leafs with special info. 772 AddNodeIDCustom(ID, N); 773 } 774 775 //===----------------------------------------------------------------------===// 776 // SelectionDAG Class 777 //===----------------------------------------------------------------------===// 778 779 /// doNotCSE - Return true if CSE should not be performed for this node. 780 static bool doNotCSE(SDNode *N) { 781 if (N->getValueType(0) == MVT::Glue) 782 return true; // Never CSE anything that produces a flag. 783 784 switch (N->getOpcode()) { 785 default: break; 786 case ISD::HANDLENODE: 787 case ISD::EH_LABEL: 788 return true; // Never CSE these nodes. 789 } 790 791 // Check that remaining values produced are not flags. 792 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 793 if (N->getValueType(i) == MVT::Glue) 794 return true; // Never CSE anything that produces a flag. 795 796 return false; 797 } 798 799 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 800 /// SelectionDAG. 801 void SelectionDAG::RemoveDeadNodes() { 802 // Create a dummy node (which is not added to allnodes), that adds a reference 803 // to the root node, preventing it from being deleted. 804 HandleSDNode Dummy(getRoot()); 805 806 SmallVector<SDNode*, 128> DeadNodes; 807 808 // Add all obviously-dead nodes to the DeadNodes worklist. 809 for (SDNode &Node : allnodes()) 810 if (Node.use_empty()) 811 DeadNodes.push_back(&Node); 812 813 RemoveDeadNodes(DeadNodes); 814 815 // If the root changed (e.g. it was a dead load, update the root). 816 setRoot(Dummy.getValue()); 817 } 818 819 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 820 /// given list, and any nodes that become unreachable as a result. 821 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 822 823 // Process the worklist, deleting the nodes and adding their uses to the 824 // worklist. 825 while (!DeadNodes.empty()) { 826 SDNode *N = DeadNodes.pop_back_val(); 827 // Skip to next node if we've already managed to delete the node. This could 828 // happen if replacing a node causes a node previously added to the node to 829 // be deleted. 830 if (N->getOpcode() == ISD::DELETED_NODE) 831 continue; 832 833 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 834 DUL->NodeDeleted(N, nullptr); 835 836 // Take the node out of the appropriate CSE map. 837 RemoveNodeFromCSEMaps(N); 838 839 // Next, brutally remove the operand list. This is safe to do, as there are 840 // no cycles in the graph. 841 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 842 SDUse &Use = *I++; 843 SDNode *Operand = Use.getNode(); 844 Use.set(SDValue()); 845 846 // Now that we removed this operand, see if there are no uses of it left. 847 if (Operand->use_empty()) 848 DeadNodes.push_back(Operand); 849 } 850 851 DeallocateNode(N); 852 } 853 } 854 855 void SelectionDAG::RemoveDeadNode(SDNode *N){ 856 SmallVector<SDNode*, 16> DeadNodes(1, N); 857 858 // Create a dummy node that adds a reference to the root node, preventing 859 // it from being deleted. (This matters if the root is an operand of the 860 // dead node.) 861 HandleSDNode Dummy(getRoot()); 862 863 RemoveDeadNodes(DeadNodes); 864 } 865 866 void SelectionDAG::DeleteNode(SDNode *N) { 867 // First take this out of the appropriate CSE map. 868 RemoveNodeFromCSEMaps(N); 869 870 // Finally, remove uses due to operands of this node, remove from the 871 // AllNodes list, and delete the node. 872 DeleteNodeNotInCSEMaps(N); 873 } 874 875 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 876 assert(N->getIterator() != AllNodes.begin() && 877 "Cannot delete the entry node!"); 878 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 879 880 // Drop all of the operands and decrement used node's use counts. 881 N->DropOperands(); 882 883 DeallocateNode(N); 884 } 885 886 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 887 assert(!(V->isVariadic() && isParameter)); 888 if (isParameter) 889 ByvalParmDbgValues.push_back(V); 890 else 891 DbgValues.push_back(V); 892 for (const SDNode *Node : V->getSDNodes()) 893 if (Node) 894 DbgValMap[Node].push_back(V); 895 } 896 897 void SDDbgInfo::erase(const SDNode *Node) { 898 DbgValMapType::iterator I = DbgValMap.find(Node); 899 if (I == DbgValMap.end()) 900 return; 901 for (auto &Val: I->second) 902 Val->setIsInvalidated(); 903 DbgValMap.erase(I); 904 } 905 906 void SelectionDAG::DeallocateNode(SDNode *N) { 907 // If we have operands, deallocate them. 908 removeOperands(N); 909 910 NodeAllocator.Deallocate(AllNodes.remove(N)); 911 912 // Set the opcode to DELETED_NODE to help catch bugs when node 913 // memory is reallocated. 914 // FIXME: There are places in SDag that have grown a dependency on the opcode 915 // value in the released node. 916 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 917 N->NodeType = ISD::DELETED_NODE; 918 919 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 920 // them and forget about that node. 921 DbgInfo->erase(N); 922 } 923 924 #ifndef NDEBUG 925 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 926 static void VerifySDNode(SDNode *N) { 927 switch (N->getOpcode()) { 928 default: 929 break; 930 case ISD::BUILD_PAIR: { 931 EVT VT = N->getValueType(0); 932 assert(N->getNumValues() == 1 && "Too many results!"); 933 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 934 "Wrong return type!"); 935 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 936 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 937 "Mismatched operand types!"); 938 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 939 "Wrong operand type!"); 940 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 941 "Wrong return type size"); 942 break; 943 } 944 case ISD::BUILD_VECTOR: { 945 assert(N->getNumValues() == 1 && "Too many results!"); 946 assert(N->getValueType(0).isVector() && "Wrong return type!"); 947 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 948 "Wrong number of operands!"); 949 EVT EltVT = N->getValueType(0).getVectorElementType(); 950 for (const SDUse &Op : N->ops()) { 951 assert((Op.getValueType() == EltVT || 952 (EltVT.isInteger() && Op.getValueType().isInteger() && 953 EltVT.bitsLE(Op.getValueType()))) && 954 "Wrong operand type!"); 955 assert(Op.getValueType() == N->getOperand(0).getValueType() && 956 "Operands must all have the same type"); 957 } 958 break; 959 } 960 } 961 } 962 #endif // NDEBUG 963 964 /// Insert a newly allocated node into the DAG. 965 /// 966 /// Handles insertion into the all nodes list and CSE map, as well as 967 /// verification and other common operations when a new node is allocated. 968 void SelectionDAG::InsertNode(SDNode *N) { 969 AllNodes.push_back(N); 970 #ifndef NDEBUG 971 N->PersistentId = NextPersistentId++; 972 VerifySDNode(N); 973 #endif 974 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 975 DUL->NodeInserted(N); 976 } 977 978 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 979 /// correspond to it. This is useful when we're about to delete or repurpose 980 /// the node. We don't want future request for structurally identical nodes 981 /// to return N anymore. 982 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 983 bool Erased = false; 984 switch (N->getOpcode()) { 985 case ISD::HANDLENODE: return false; // noop. 986 case ISD::CONDCODE: 987 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 988 "Cond code doesn't exist!"); 989 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 990 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 991 break; 992 case ISD::ExternalSymbol: 993 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 994 break; 995 case ISD::TargetExternalSymbol: { 996 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 997 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 998 ESN->getSymbol(), ESN->getTargetFlags())); 999 break; 1000 } 1001 case ISD::MCSymbol: { 1002 auto *MCSN = cast<MCSymbolSDNode>(N); 1003 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1004 break; 1005 } 1006 case ISD::VALUETYPE: { 1007 EVT VT = cast<VTSDNode>(N)->getVT(); 1008 if (VT.isExtended()) { 1009 Erased = ExtendedValueTypeNodes.erase(VT); 1010 } else { 1011 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1012 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1013 } 1014 break; 1015 } 1016 default: 1017 // Remove it from the CSE Map. 1018 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1019 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1020 Erased = CSEMap.RemoveNode(N); 1021 break; 1022 } 1023 #ifndef NDEBUG 1024 // Verify that the node was actually in one of the CSE maps, unless it has a 1025 // flag result (which cannot be CSE'd) or is one of the special cases that are 1026 // not subject to CSE. 1027 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1028 !N->isMachineOpcode() && !doNotCSE(N)) { 1029 N->dump(this); 1030 dbgs() << "\n"; 1031 llvm_unreachable("Node is not in map!"); 1032 } 1033 #endif 1034 return Erased; 1035 } 1036 1037 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1038 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1039 /// node already exists, in which case transfer all its users to the existing 1040 /// node. This transfer can potentially trigger recursive merging. 1041 void 1042 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1043 // For node types that aren't CSE'd, just act as if no identical node 1044 // already exists. 1045 if (!doNotCSE(N)) { 1046 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1047 if (Existing != N) { 1048 // If there was already an existing matching node, use ReplaceAllUsesWith 1049 // to replace the dead one with the existing one. This can cause 1050 // recursive merging of other unrelated nodes down the line. 1051 ReplaceAllUsesWith(N, Existing); 1052 1053 // N is now dead. Inform the listeners and delete it. 1054 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1055 DUL->NodeDeleted(N, Existing); 1056 DeleteNodeNotInCSEMaps(N); 1057 return; 1058 } 1059 } 1060 1061 // If the node doesn't already exist, we updated it. Inform listeners. 1062 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1063 DUL->NodeUpdated(N); 1064 } 1065 1066 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1067 /// were replaced with those specified. If this node is never memoized, 1068 /// return null, otherwise return a pointer to the slot it would take. If a 1069 /// node already exists with these operands, the slot will be non-null. 1070 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1071 void *&InsertPos) { 1072 if (doNotCSE(N)) 1073 return nullptr; 1074 1075 SDValue Ops[] = { Op }; 1076 FoldingSetNodeID ID; 1077 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1078 AddNodeIDCustom(ID, N); 1079 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1080 if (Node) 1081 Node->intersectFlagsWith(N->getFlags()); 1082 return Node; 1083 } 1084 1085 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1086 /// were replaced with those specified. If this node is never memoized, 1087 /// return null, otherwise return a pointer to the slot it would take. If a 1088 /// node already exists with these operands, the slot will be non-null. 1089 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1090 SDValue Op1, SDValue Op2, 1091 void *&InsertPos) { 1092 if (doNotCSE(N)) 1093 return nullptr; 1094 1095 SDValue Ops[] = { Op1, Op2 }; 1096 FoldingSetNodeID ID; 1097 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1098 AddNodeIDCustom(ID, N); 1099 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1100 if (Node) 1101 Node->intersectFlagsWith(N->getFlags()); 1102 return Node; 1103 } 1104 1105 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1106 /// were replaced with those specified. If this node is never memoized, 1107 /// return null, otherwise return a pointer to the slot it would take. If a 1108 /// node already exists with these operands, the slot will be non-null. 1109 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1110 void *&InsertPos) { 1111 if (doNotCSE(N)) 1112 return nullptr; 1113 1114 FoldingSetNodeID ID; 1115 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1116 AddNodeIDCustom(ID, N); 1117 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1118 if (Node) 1119 Node->intersectFlagsWith(N->getFlags()); 1120 return Node; 1121 } 1122 1123 Align SelectionDAG::getEVTAlign(EVT VT) const { 1124 Type *Ty = VT == MVT::iPTR ? 1125 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1126 VT.getTypeForEVT(*getContext()); 1127 1128 return getDataLayout().getABITypeAlign(Ty); 1129 } 1130 1131 // EntryNode could meaningfully have debug info if we can find it... 1132 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1133 : TM(tm), OptLevel(OL), 1134 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1135 Root(getEntryNode()) { 1136 InsertNode(&EntryNode); 1137 DbgInfo = new SDDbgInfo(); 1138 } 1139 1140 void SelectionDAG::init(MachineFunction &NewMF, 1141 OptimizationRemarkEmitter &NewORE, 1142 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1143 LegacyDivergenceAnalysis * Divergence, 1144 ProfileSummaryInfo *PSIin, 1145 BlockFrequencyInfo *BFIin) { 1146 MF = &NewMF; 1147 SDAGISelPass = PassPtr; 1148 ORE = &NewORE; 1149 TLI = getSubtarget().getTargetLowering(); 1150 TSI = getSubtarget().getSelectionDAGInfo(); 1151 LibInfo = LibraryInfo; 1152 Context = &MF->getFunction().getContext(); 1153 DA = Divergence; 1154 PSI = PSIin; 1155 BFI = BFIin; 1156 } 1157 1158 SelectionDAG::~SelectionDAG() { 1159 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1160 allnodes_clear(); 1161 OperandRecycler.clear(OperandAllocator); 1162 delete DbgInfo; 1163 } 1164 1165 bool SelectionDAG::shouldOptForSize() const { 1166 return MF->getFunction().hasOptSize() || 1167 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1168 } 1169 1170 void SelectionDAG::allnodes_clear() { 1171 assert(&*AllNodes.begin() == &EntryNode); 1172 AllNodes.remove(AllNodes.begin()); 1173 while (!AllNodes.empty()) 1174 DeallocateNode(&AllNodes.front()); 1175 #ifndef NDEBUG 1176 NextPersistentId = 0; 1177 #endif 1178 } 1179 1180 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1181 void *&InsertPos) { 1182 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1183 if (N) { 1184 switch (N->getOpcode()) { 1185 default: break; 1186 case ISD::Constant: 1187 case ISD::ConstantFP: 1188 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1189 "debug location. Use another overload."); 1190 } 1191 } 1192 return N; 1193 } 1194 1195 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1196 const SDLoc &DL, void *&InsertPos) { 1197 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1198 if (N) { 1199 switch (N->getOpcode()) { 1200 case ISD::Constant: 1201 case ISD::ConstantFP: 1202 // Erase debug location from the node if the node is used at several 1203 // different places. Do not propagate one location to all uses as it 1204 // will cause a worse single stepping debugging experience. 1205 if (N->getDebugLoc() != DL.getDebugLoc()) 1206 N->setDebugLoc(DebugLoc()); 1207 break; 1208 default: 1209 // When the node's point of use is located earlier in the instruction 1210 // sequence than its prior point of use, update its debug info to the 1211 // earlier location. 1212 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1213 N->setDebugLoc(DL.getDebugLoc()); 1214 break; 1215 } 1216 } 1217 return N; 1218 } 1219 1220 void SelectionDAG::clear() { 1221 allnodes_clear(); 1222 OperandRecycler.clear(OperandAllocator); 1223 OperandAllocator.Reset(); 1224 CSEMap.clear(); 1225 1226 ExtendedValueTypeNodes.clear(); 1227 ExternalSymbols.clear(); 1228 TargetExternalSymbols.clear(); 1229 MCSymbols.clear(); 1230 SDCallSiteDbgInfo.clear(); 1231 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1232 static_cast<CondCodeSDNode*>(nullptr)); 1233 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1234 static_cast<SDNode*>(nullptr)); 1235 1236 EntryNode.UseList = nullptr; 1237 InsertNode(&EntryNode); 1238 Root = getEntryNode(); 1239 DbgInfo->clear(); 1240 } 1241 1242 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1243 return VT.bitsGT(Op.getValueType()) 1244 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1245 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1246 } 1247 1248 std::pair<SDValue, SDValue> 1249 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1250 const SDLoc &DL, EVT VT) { 1251 assert(!VT.bitsEq(Op.getValueType()) && 1252 "Strict no-op FP extend/round not allowed."); 1253 SDValue Res = 1254 VT.bitsGT(Op.getValueType()) 1255 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1256 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1257 {Chain, Op, getIntPtrConstant(0, DL)}); 1258 1259 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1260 } 1261 1262 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1263 return VT.bitsGT(Op.getValueType()) ? 1264 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1265 getNode(ISD::TRUNCATE, DL, VT, Op); 1266 } 1267 1268 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1269 return VT.bitsGT(Op.getValueType()) ? 1270 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1271 getNode(ISD::TRUNCATE, DL, VT, Op); 1272 } 1273 1274 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1275 return VT.bitsGT(Op.getValueType()) ? 1276 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1277 getNode(ISD::TRUNCATE, DL, VT, Op); 1278 } 1279 1280 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1281 EVT OpVT) { 1282 if (VT.bitsLE(Op.getValueType())) 1283 return getNode(ISD::TRUNCATE, SL, VT, Op); 1284 1285 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1286 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1287 } 1288 1289 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1290 EVT OpVT = Op.getValueType(); 1291 assert(VT.isInteger() && OpVT.isInteger() && 1292 "Cannot getZeroExtendInReg FP types"); 1293 assert(VT.isVector() == OpVT.isVector() && 1294 "getZeroExtendInReg type should be vector iff the operand " 1295 "type is vector!"); 1296 assert((!VT.isVector() || 1297 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1298 "Vector element counts must match in getZeroExtendInReg"); 1299 assert(VT.bitsLE(OpVT) && "Not extending!"); 1300 if (OpVT == VT) 1301 return Op; 1302 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1303 VT.getScalarSizeInBits()); 1304 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1305 } 1306 1307 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1308 // Only unsigned pointer semantics are supported right now. In the future this 1309 // might delegate to TLI to check pointer signedness. 1310 return getZExtOrTrunc(Op, DL, VT); 1311 } 1312 1313 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1314 // Only unsigned pointer semantics are supported right now. In the future this 1315 // might delegate to TLI to check pointer signedness. 1316 return getZeroExtendInReg(Op, DL, VT); 1317 } 1318 1319 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1320 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1321 EVT EltVT = VT.getScalarType(); 1322 SDValue NegOne = 1323 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT); 1324 return getNode(ISD::XOR, DL, VT, Val, NegOne); 1325 } 1326 1327 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1328 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1329 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1330 } 1331 1332 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1333 EVT OpVT) { 1334 if (!V) 1335 return getConstant(0, DL, VT); 1336 1337 switch (TLI->getBooleanContents(OpVT)) { 1338 case TargetLowering::ZeroOrOneBooleanContent: 1339 case TargetLowering::UndefinedBooleanContent: 1340 return getConstant(1, DL, VT); 1341 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1342 return getAllOnesConstant(DL, VT); 1343 } 1344 llvm_unreachable("Unexpected boolean content enum!"); 1345 } 1346 1347 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1348 bool isT, bool isO) { 1349 EVT EltVT = VT.getScalarType(); 1350 assert((EltVT.getSizeInBits() >= 64 || 1351 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1352 "getConstant with a uint64_t value that doesn't fit in the type!"); 1353 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1354 } 1355 1356 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1357 bool isT, bool isO) { 1358 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1359 } 1360 1361 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1362 EVT VT, bool isT, bool isO) { 1363 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1364 1365 EVT EltVT = VT.getScalarType(); 1366 const ConstantInt *Elt = &Val; 1367 1368 // In some cases the vector type is legal but the element type is illegal and 1369 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1370 // inserted value (the type does not need to match the vector element type). 1371 // Any extra bits introduced will be truncated away. 1372 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1373 TargetLowering::TypePromoteInteger) { 1374 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1375 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1376 Elt = ConstantInt::get(*getContext(), NewVal); 1377 } 1378 // In other cases the element type is illegal and needs to be expanded, for 1379 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1380 // the value into n parts and use a vector type with n-times the elements. 1381 // Then bitcast to the type requested. 1382 // Legalizing constants too early makes the DAGCombiner's job harder so we 1383 // only legalize if the DAG tells us we must produce legal types. 1384 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1385 TLI->getTypeAction(*getContext(), EltVT) == 1386 TargetLowering::TypeExpandInteger) { 1387 const APInt &NewVal = Elt->getValue(); 1388 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1389 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1390 1391 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1392 if (VT.isScalableVector()) { 1393 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1394 "Can only handle an even split!"); 1395 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1396 1397 SmallVector<SDValue, 2> ScalarParts; 1398 for (unsigned i = 0; i != Parts; ++i) 1399 ScalarParts.push_back(getConstant( 1400 NewVal.lshr(i * ViaEltSizeInBits).trunc(ViaEltSizeInBits), DL, 1401 ViaEltVT, isT, isO)); 1402 1403 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1404 } 1405 1406 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1407 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1408 1409 // Check the temporary vector is the correct size. If this fails then 1410 // getTypeToTransformTo() probably returned a type whose size (in bits) 1411 // isn't a power-of-2 factor of the requested type size. 1412 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1413 1414 SmallVector<SDValue, 2> EltParts; 1415 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) { 1416 EltParts.push_back(getConstant( 1417 NewVal.lshr(i * ViaEltSizeInBits).zextOrTrunc(ViaEltSizeInBits), DL, 1418 ViaEltVT, isT, isO)); 1419 } 1420 1421 // EltParts is currently in little endian order. If we actually want 1422 // big-endian order then reverse it now. 1423 if (getDataLayout().isBigEndian()) 1424 std::reverse(EltParts.begin(), EltParts.end()); 1425 1426 // The elements must be reversed when the element order is different 1427 // to the endianness of the elements (because the BITCAST is itself a 1428 // vector shuffle in this situation). However, we do not need any code to 1429 // perform this reversal because getConstant() is producing a vector 1430 // splat. 1431 // This situation occurs in MIPS MSA. 1432 1433 SmallVector<SDValue, 8> Ops; 1434 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1435 llvm::append_range(Ops, EltParts); 1436 1437 SDValue V = 1438 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1439 return V; 1440 } 1441 1442 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1443 "APInt size does not match type size!"); 1444 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1445 FoldingSetNodeID ID; 1446 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1447 ID.AddPointer(Elt); 1448 ID.AddBoolean(isO); 1449 void *IP = nullptr; 1450 SDNode *N = nullptr; 1451 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1452 if (!VT.isVector()) 1453 return SDValue(N, 0); 1454 1455 if (!N) { 1456 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1457 CSEMap.InsertNode(N, IP); 1458 InsertNode(N); 1459 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1460 } 1461 1462 SDValue Result(N, 0); 1463 if (VT.isScalableVector()) 1464 Result = getSplatVector(VT, DL, Result); 1465 else if (VT.isVector()) 1466 Result = getSplatBuildVector(VT, DL, Result); 1467 1468 return Result; 1469 } 1470 1471 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1472 bool isTarget) { 1473 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1474 } 1475 1476 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1477 const SDLoc &DL, bool LegalTypes) { 1478 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1479 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1480 return getConstant(Val, DL, ShiftVT); 1481 } 1482 1483 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1484 bool isTarget) { 1485 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1486 } 1487 1488 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1489 bool isTarget) { 1490 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1491 } 1492 1493 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1494 EVT VT, bool isTarget) { 1495 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1496 1497 EVT EltVT = VT.getScalarType(); 1498 1499 // Do the map lookup using the actual bit pattern for the floating point 1500 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1501 // we don't have issues with SNANs. 1502 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1503 FoldingSetNodeID ID; 1504 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1505 ID.AddPointer(&V); 1506 void *IP = nullptr; 1507 SDNode *N = nullptr; 1508 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1509 if (!VT.isVector()) 1510 return SDValue(N, 0); 1511 1512 if (!N) { 1513 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1514 CSEMap.InsertNode(N, IP); 1515 InsertNode(N); 1516 } 1517 1518 SDValue Result(N, 0); 1519 if (VT.isScalableVector()) 1520 Result = getSplatVector(VT, DL, Result); 1521 else if (VT.isVector()) 1522 Result = getSplatBuildVector(VT, DL, Result); 1523 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1524 return Result; 1525 } 1526 1527 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1528 bool isTarget) { 1529 EVT EltVT = VT.getScalarType(); 1530 if (EltVT == MVT::f32) 1531 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1532 if (EltVT == MVT::f64) 1533 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1534 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1535 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1536 bool Ignored; 1537 APFloat APF = APFloat(Val); 1538 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1539 &Ignored); 1540 return getConstantFP(APF, DL, VT, isTarget); 1541 } 1542 llvm_unreachable("Unsupported type in getConstantFP"); 1543 } 1544 1545 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1546 EVT VT, int64_t Offset, bool isTargetGA, 1547 unsigned TargetFlags) { 1548 assert((TargetFlags == 0 || isTargetGA) && 1549 "Cannot set target flags on target-independent globals"); 1550 1551 // Truncate (with sign-extension) the offset value to the pointer size. 1552 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1553 if (BitWidth < 64) 1554 Offset = SignExtend64(Offset, BitWidth); 1555 1556 unsigned Opc; 1557 if (GV->isThreadLocal()) 1558 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1559 else 1560 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1561 1562 FoldingSetNodeID ID; 1563 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1564 ID.AddPointer(GV); 1565 ID.AddInteger(Offset); 1566 ID.AddInteger(TargetFlags); 1567 void *IP = nullptr; 1568 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1569 return SDValue(E, 0); 1570 1571 auto *N = newSDNode<GlobalAddressSDNode>( 1572 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1573 CSEMap.InsertNode(N, IP); 1574 InsertNode(N); 1575 return SDValue(N, 0); 1576 } 1577 1578 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1579 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1580 FoldingSetNodeID ID; 1581 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1582 ID.AddInteger(FI); 1583 void *IP = nullptr; 1584 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1585 return SDValue(E, 0); 1586 1587 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1588 CSEMap.InsertNode(N, IP); 1589 InsertNode(N); 1590 return SDValue(N, 0); 1591 } 1592 1593 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1594 unsigned TargetFlags) { 1595 assert((TargetFlags == 0 || isTarget) && 1596 "Cannot set target flags on target-independent jump tables"); 1597 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1598 FoldingSetNodeID ID; 1599 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1600 ID.AddInteger(JTI); 1601 ID.AddInteger(TargetFlags); 1602 void *IP = nullptr; 1603 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1604 return SDValue(E, 0); 1605 1606 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1607 CSEMap.InsertNode(N, IP); 1608 InsertNode(N); 1609 return SDValue(N, 0); 1610 } 1611 1612 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1613 MaybeAlign Alignment, int Offset, 1614 bool isTarget, unsigned TargetFlags) { 1615 assert((TargetFlags == 0 || isTarget) && 1616 "Cannot set target flags on target-independent globals"); 1617 if (!Alignment) 1618 Alignment = shouldOptForSize() 1619 ? getDataLayout().getABITypeAlign(C->getType()) 1620 : getDataLayout().getPrefTypeAlign(C->getType()); 1621 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1622 FoldingSetNodeID ID; 1623 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1624 ID.AddInteger(Alignment->value()); 1625 ID.AddInteger(Offset); 1626 ID.AddPointer(C); 1627 ID.AddInteger(TargetFlags); 1628 void *IP = nullptr; 1629 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1630 return SDValue(E, 0); 1631 1632 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1633 TargetFlags); 1634 CSEMap.InsertNode(N, IP); 1635 InsertNode(N); 1636 SDValue V = SDValue(N, 0); 1637 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1638 return V; 1639 } 1640 1641 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1642 MaybeAlign Alignment, int Offset, 1643 bool isTarget, unsigned TargetFlags) { 1644 assert((TargetFlags == 0 || isTarget) && 1645 "Cannot set target flags on target-independent globals"); 1646 if (!Alignment) 1647 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1648 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1649 FoldingSetNodeID ID; 1650 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1651 ID.AddInteger(Alignment->value()); 1652 ID.AddInteger(Offset); 1653 C->addSelectionDAGCSEId(ID); 1654 ID.AddInteger(TargetFlags); 1655 void *IP = nullptr; 1656 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1657 return SDValue(E, 0); 1658 1659 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1660 TargetFlags); 1661 CSEMap.InsertNode(N, IP); 1662 InsertNode(N); 1663 return SDValue(N, 0); 1664 } 1665 1666 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1667 unsigned TargetFlags) { 1668 FoldingSetNodeID ID; 1669 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1670 ID.AddInteger(Index); 1671 ID.AddInteger(Offset); 1672 ID.AddInteger(TargetFlags); 1673 void *IP = nullptr; 1674 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1675 return SDValue(E, 0); 1676 1677 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1678 CSEMap.InsertNode(N, IP); 1679 InsertNode(N); 1680 return SDValue(N, 0); 1681 } 1682 1683 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1684 FoldingSetNodeID ID; 1685 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1686 ID.AddPointer(MBB); 1687 void *IP = nullptr; 1688 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1689 return SDValue(E, 0); 1690 1691 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1692 CSEMap.InsertNode(N, IP); 1693 InsertNode(N); 1694 return SDValue(N, 0); 1695 } 1696 1697 SDValue SelectionDAG::getValueType(EVT VT) { 1698 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1699 ValueTypeNodes.size()) 1700 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1701 1702 SDNode *&N = VT.isExtended() ? 1703 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1704 1705 if (N) return SDValue(N, 0); 1706 N = newSDNode<VTSDNode>(VT); 1707 InsertNode(N); 1708 return SDValue(N, 0); 1709 } 1710 1711 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1712 SDNode *&N = ExternalSymbols[Sym]; 1713 if (N) return SDValue(N, 0); 1714 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1715 InsertNode(N); 1716 return SDValue(N, 0); 1717 } 1718 1719 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1720 SDNode *&N = MCSymbols[Sym]; 1721 if (N) 1722 return SDValue(N, 0); 1723 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1724 InsertNode(N); 1725 return SDValue(N, 0); 1726 } 1727 1728 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1729 unsigned TargetFlags) { 1730 SDNode *&N = 1731 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1732 if (N) return SDValue(N, 0); 1733 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1734 InsertNode(N); 1735 return SDValue(N, 0); 1736 } 1737 1738 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1739 if ((unsigned)Cond >= CondCodeNodes.size()) 1740 CondCodeNodes.resize(Cond+1); 1741 1742 if (!CondCodeNodes[Cond]) { 1743 auto *N = newSDNode<CondCodeSDNode>(Cond); 1744 CondCodeNodes[Cond] = N; 1745 InsertNode(N); 1746 } 1747 1748 return SDValue(CondCodeNodes[Cond], 0); 1749 } 1750 1751 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, SDValue Step) { 1752 if (ResVT.isScalableVector()) 1753 return getNode(ISD::STEP_VECTOR, DL, ResVT, Step); 1754 1755 EVT OpVT = Step.getValueType(); 1756 APInt StepVal = cast<ConstantSDNode>(Step)->getAPIntValue(); 1757 SmallVector<SDValue, 16> OpsStepConstants; 1758 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1759 OpsStepConstants.push_back(getConstant(StepVal * i, DL, OpVT)); 1760 return getBuildVector(ResVT, DL, OpsStepConstants); 1761 } 1762 1763 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1764 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1765 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1766 std::swap(N1, N2); 1767 ShuffleVectorSDNode::commuteMask(M); 1768 } 1769 1770 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1771 SDValue N2, ArrayRef<int> Mask) { 1772 assert(VT.getVectorNumElements() == Mask.size() && 1773 "Must have the same number of vector elements as mask elements!"); 1774 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1775 "Invalid VECTOR_SHUFFLE"); 1776 1777 // Canonicalize shuffle undef, undef -> undef 1778 if (N1.isUndef() && N2.isUndef()) 1779 return getUNDEF(VT); 1780 1781 // Validate that all indices in Mask are within the range of the elements 1782 // input to the shuffle. 1783 int NElts = Mask.size(); 1784 assert(llvm::all_of(Mask, 1785 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1786 "Index out of range"); 1787 1788 // Copy the mask so we can do any needed cleanup. 1789 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1790 1791 // Canonicalize shuffle v, v -> v, undef 1792 if (N1 == N2) { 1793 N2 = getUNDEF(VT); 1794 for (int i = 0; i != NElts; ++i) 1795 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1796 } 1797 1798 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1799 if (N1.isUndef()) 1800 commuteShuffle(N1, N2, MaskVec); 1801 1802 if (TLI->hasVectorBlend()) { 1803 // If shuffling a splat, try to blend the splat instead. We do this here so 1804 // that even when this arises during lowering we don't have to re-handle it. 1805 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1806 BitVector UndefElements; 1807 SDValue Splat = BV->getSplatValue(&UndefElements); 1808 if (!Splat) 1809 return; 1810 1811 for (int i = 0; i < NElts; ++i) { 1812 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1813 continue; 1814 1815 // If this input comes from undef, mark it as such. 1816 if (UndefElements[MaskVec[i] - Offset]) { 1817 MaskVec[i] = -1; 1818 continue; 1819 } 1820 1821 // If we can blend a non-undef lane, use that instead. 1822 if (!UndefElements[i]) 1823 MaskVec[i] = i + Offset; 1824 } 1825 }; 1826 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1827 BlendSplat(N1BV, 0); 1828 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1829 BlendSplat(N2BV, NElts); 1830 } 1831 1832 // Canonicalize all index into lhs, -> shuffle lhs, undef 1833 // Canonicalize all index into rhs, -> shuffle rhs, undef 1834 bool AllLHS = true, AllRHS = true; 1835 bool N2Undef = N2.isUndef(); 1836 for (int i = 0; i != NElts; ++i) { 1837 if (MaskVec[i] >= NElts) { 1838 if (N2Undef) 1839 MaskVec[i] = -1; 1840 else 1841 AllLHS = false; 1842 } else if (MaskVec[i] >= 0) { 1843 AllRHS = false; 1844 } 1845 } 1846 if (AllLHS && AllRHS) 1847 return getUNDEF(VT); 1848 if (AllLHS && !N2Undef) 1849 N2 = getUNDEF(VT); 1850 if (AllRHS) { 1851 N1 = getUNDEF(VT); 1852 commuteShuffle(N1, N2, MaskVec); 1853 } 1854 // Reset our undef status after accounting for the mask. 1855 N2Undef = N2.isUndef(); 1856 // Re-check whether both sides ended up undef. 1857 if (N1.isUndef() && N2Undef) 1858 return getUNDEF(VT); 1859 1860 // If Identity shuffle return that node. 1861 bool Identity = true, AllSame = true; 1862 for (int i = 0; i != NElts; ++i) { 1863 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1864 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1865 } 1866 if (Identity && NElts) 1867 return N1; 1868 1869 // Shuffling a constant splat doesn't change the result. 1870 if (N2Undef) { 1871 SDValue V = N1; 1872 1873 // Look through any bitcasts. We check that these don't change the number 1874 // (and size) of elements and just changes their types. 1875 while (V.getOpcode() == ISD::BITCAST) 1876 V = V->getOperand(0); 1877 1878 // A splat should always show up as a build vector node. 1879 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1880 BitVector UndefElements; 1881 SDValue Splat = BV->getSplatValue(&UndefElements); 1882 // If this is a splat of an undef, shuffling it is also undef. 1883 if (Splat && Splat.isUndef()) 1884 return getUNDEF(VT); 1885 1886 bool SameNumElts = 1887 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1888 1889 // We only have a splat which can skip shuffles if there is a splatted 1890 // value and no undef lanes rearranged by the shuffle. 1891 if (Splat && UndefElements.none()) { 1892 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1893 // number of elements match or the value splatted is a zero constant. 1894 if (SameNumElts) 1895 return N1; 1896 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1897 if (C->isNullValue()) 1898 return N1; 1899 } 1900 1901 // If the shuffle itself creates a splat, build the vector directly. 1902 if (AllSame && SameNumElts) { 1903 EVT BuildVT = BV->getValueType(0); 1904 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1905 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1906 1907 // We may have jumped through bitcasts, so the type of the 1908 // BUILD_VECTOR may not match the type of the shuffle. 1909 if (BuildVT != VT) 1910 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1911 return NewBV; 1912 } 1913 } 1914 } 1915 1916 FoldingSetNodeID ID; 1917 SDValue Ops[2] = { N1, N2 }; 1918 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1919 for (int i = 0; i != NElts; ++i) 1920 ID.AddInteger(MaskVec[i]); 1921 1922 void* IP = nullptr; 1923 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1924 return SDValue(E, 0); 1925 1926 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1927 // SDNode doesn't have access to it. This memory will be "leaked" when 1928 // the node is deallocated, but recovered when the NodeAllocator is released. 1929 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1930 llvm::copy(MaskVec, MaskAlloc); 1931 1932 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 1933 dl.getDebugLoc(), MaskAlloc); 1934 createOperands(N, Ops); 1935 1936 CSEMap.InsertNode(N, IP); 1937 InsertNode(N); 1938 SDValue V = SDValue(N, 0); 1939 NewSDValueDbgMsg(V, "Creating new node: ", this); 1940 return V; 1941 } 1942 1943 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 1944 EVT VT = SV.getValueType(0); 1945 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 1946 ShuffleVectorSDNode::commuteMask(MaskVec); 1947 1948 SDValue Op0 = SV.getOperand(0); 1949 SDValue Op1 = SV.getOperand(1); 1950 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 1951 } 1952 1953 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1954 FoldingSetNodeID ID; 1955 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 1956 ID.AddInteger(RegNo); 1957 void *IP = nullptr; 1958 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1959 return SDValue(E, 0); 1960 1961 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 1962 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 1963 CSEMap.InsertNode(N, IP); 1964 InsertNode(N); 1965 return SDValue(N, 0); 1966 } 1967 1968 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 1969 FoldingSetNodeID ID; 1970 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 1971 ID.AddPointer(RegMask); 1972 void *IP = nullptr; 1973 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1974 return SDValue(E, 0); 1975 1976 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 1977 CSEMap.InsertNode(N, IP); 1978 InsertNode(N); 1979 return SDValue(N, 0); 1980 } 1981 1982 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 1983 MCSymbol *Label) { 1984 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 1985 } 1986 1987 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 1988 SDValue Root, MCSymbol *Label) { 1989 FoldingSetNodeID ID; 1990 SDValue Ops[] = { Root }; 1991 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 1992 ID.AddPointer(Label); 1993 void *IP = nullptr; 1994 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1995 return SDValue(E, 0); 1996 1997 auto *N = 1998 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 1999 createOperands(N, Ops); 2000 2001 CSEMap.InsertNode(N, IP); 2002 InsertNode(N); 2003 return SDValue(N, 0); 2004 } 2005 2006 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2007 int64_t Offset, bool isTarget, 2008 unsigned TargetFlags) { 2009 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2010 2011 FoldingSetNodeID ID; 2012 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2013 ID.AddPointer(BA); 2014 ID.AddInteger(Offset); 2015 ID.AddInteger(TargetFlags); 2016 void *IP = nullptr; 2017 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2018 return SDValue(E, 0); 2019 2020 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2021 CSEMap.InsertNode(N, IP); 2022 InsertNode(N); 2023 return SDValue(N, 0); 2024 } 2025 2026 SDValue SelectionDAG::getSrcValue(const Value *V) { 2027 FoldingSetNodeID ID; 2028 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2029 ID.AddPointer(V); 2030 2031 void *IP = nullptr; 2032 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2033 return SDValue(E, 0); 2034 2035 auto *N = newSDNode<SrcValueSDNode>(V); 2036 CSEMap.InsertNode(N, IP); 2037 InsertNode(N); 2038 return SDValue(N, 0); 2039 } 2040 2041 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2042 FoldingSetNodeID ID; 2043 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2044 ID.AddPointer(MD); 2045 2046 void *IP = nullptr; 2047 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2048 return SDValue(E, 0); 2049 2050 auto *N = newSDNode<MDNodeSDNode>(MD); 2051 CSEMap.InsertNode(N, IP); 2052 InsertNode(N); 2053 return SDValue(N, 0); 2054 } 2055 2056 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2057 if (VT == V.getValueType()) 2058 return V; 2059 2060 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2061 } 2062 2063 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2064 unsigned SrcAS, unsigned DestAS) { 2065 SDValue Ops[] = {Ptr}; 2066 FoldingSetNodeID ID; 2067 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2068 ID.AddInteger(SrcAS); 2069 ID.AddInteger(DestAS); 2070 2071 void *IP = nullptr; 2072 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2073 return SDValue(E, 0); 2074 2075 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2076 VT, SrcAS, DestAS); 2077 createOperands(N, Ops); 2078 2079 CSEMap.InsertNode(N, IP); 2080 InsertNode(N); 2081 return SDValue(N, 0); 2082 } 2083 2084 SDValue SelectionDAG::getFreeze(SDValue V) { 2085 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2086 } 2087 2088 /// getShiftAmountOperand - Return the specified value casted to 2089 /// the target's desired shift amount type. 2090 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2091 EVT OpTy = Op.getValueType(); 2092 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2093 if (OpTy == ShTy || OpTy.isVector()) return Op; 2094 2095 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2096 } 2097 2098 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2099 SDLoc dl(Node); 2100 const TargetLowering &TLI = getTargetLoweringInfo(); 2101 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2102 EVT VT = Node->getValueType(0); 2103 SDValue Tmp1 = Node->getOperand(0); 2104 SDValue Tmp2 = Node->getOperand(1); 2105 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2106 2107 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2108 Tmp2, MachinePointerInfo(V)); 2109 SDValue VAList = VAListLoad; 2110 2111 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2112 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2113 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2114 2115 VAList = 2116 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2117 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2118 } 2119 2120 // Increment the pointer, VAList, to the next vaarg 2121 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2122 getConstant(getDataLayout().getTypeAllocSize( 2123 VT.getTypeForEVT(*getContext())), 2124 dl, VAList.getValueType())); 2125 // Store the incremented VAList to the legalized pointer 2126 Tmp1 = 2127 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2128 // Load the actual argument out of the pointer VAList 2129 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2130 } 2131 2132 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2133 SDLoc dl(Node); 2134 const TargetLowering &TLI = getTargetLoweringInfo(); 2135 // This defaults to loading a pointer from the input and storing it to the 2136 // output, returning the chain. 2137 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2138 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2139 SDValue Tmp1 = 2140 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2141 Node->getOperand(2), MachinePointerInfo(VS)); 2142 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2143 MachinePointerInfo(VD)); 2144 } 2145 2146 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2147 const DataLayout &DL = getDataLayout(); 2148 Type *Ty = VT.getTypeForEVT(*getContext()); 2149 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2150 2151 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2152 return RedAlign; 2153 2154 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2155 const Align StackAlign = TFI->getStackAlign(); 2156 2157 // See if we can choose a smaller ABI alignment in cases where it's an 2158 // illegal vector type that will get broken down. 2159 if (RedAlign > StackAlign) { 2160 EVT IntermediateVT; 2161 MVT RegisterVT; 2162 unsigned NumIntermediates; 2163 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2164 NumIntermediates, RegisterVT); 2165 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2166 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2167 if (RedAlign2 < RedAlign) 2168 RedAlign = RedAlign2; 2169 } 2170 2171 return RedAlign; 2172 } 2173 2174 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2175 MachineFrameInfo &MFI = MF->getFrameInfo(); 2176 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2177 int StackID = 0; 2178 if (Bytes.isScalable()) 2179 StackID = TFI->getStackIDForScalableVectors(); 2180 // The stack id gives an indication of whether the object is scalable or 2181 // not, so it's safe to pass in the minimum size here. 2182 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2183 false, nullptr, StackID); 2184 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2185 } 2186 2187 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2188 Type *Ty = VT.getTypeForEVT(*getContext()); 2189 Align StackAlign = 2190 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2191 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2192 } 2193 2194 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2195 TypeSize VT1Size = VT1.getStoreSize(); 2196 TypeSize VT2Size = VT2.getStoreSize(); 2197 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2198 "Don't know how to choose the maximum size when creating a stack " 2199 "temporary"); 2200 TypeSize Bytes = 2201 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2202 2203 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2204 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2205 const DataLayout &DL = getDataLayout(); 2206 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2207 return CreateStackTemporary(Bytes, Align); 2208 } 2209 2210 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2211 ISD::CondCode Cond, const SDLoc &dl) { 2212 EVT OpVT = N1.getValueType(); 2213 2214 // These setcc operations always fold. 2215 switch (Cond) { 2216 default: break; 2217 case ISD::SETFALSE: 2218 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2219 case ISD::SETTRUE: 2220 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2221 2222 case ISD::SETOEQ: 2223 case ISD::SETOGT: 2224 case ISD::SETOGE: 2225 case ISD::SETOLT: 2226 case ISD::SETOLE: 2227 case ISD::SETONE: 2228 case ISD::SETO: 2229 case ISD::SETUO: 2230 case ISD::SETUEQ: 2231 case ISD::SETUNE: 2232 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2233 break; 2234 } 2235 2236 if (OpVT.isInteger()) { 2237 // For EQ and NE, we can always pick a value for the undef to make the 2238 // predicate pass or fail, so we can return undef. 2239 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2240 // icmp eq/ne X, undef -> undef. 2241 if ((N1.isUndef() || N2.isUndef()) && 2242 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2243 return getUNDEF(VT); 2244 2245 // If both operands are undef, we can return undef for int comparison. 2246 // icmp undef, undef -> undef. 2247 if (N1.isUndef() && N2.isUndef()) 2248 return getUNDEF(VT); 2249 2250 // icmp X, X -> true/false 2251 // icmp X, undef -> true/false because undef could be X. 2252 if (N1 == N2) 2253 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2254 } 2255 2256 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2257 const APInt &C2 = N2C->getAPIntValue(); 2258 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2259 const APInt &C1 = N1C->getAPIntValue(); 2260 2261 switch (Cond) { 2262 default: llvm_unreachable("Unknown integer setcc!"); 2263 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT); 2264 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT); 2265 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT); 2266 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT); 2267 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT); 2268 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT); 2269 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT); 2270 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT); 2271 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT); 2272 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT); 2273 } 2274 } 2275 } 2276 2277 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2278 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2279 2280 if (N1CFP && N2CFP) { 2281 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2282 switch (Cond) { 2283 default: break; 2284 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2285 return getUNDEF(VT); 2286 LLVM_FALLTHROUGH; 2287 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2288 OpVT); 2289 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2290 return getUNDEF(VT); 2291 LLVM_FALLTHROUGH; 2292 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2293 R==APFloat::cmpLessThan, dl, VT, 2294 OpVT); 2295 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2296 return getUNDEF(VT); 2297 LLVM_FALLTHROUGH; 2298 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2299 OpVT); 2300 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2301 return getUNDEF(VT); 2302 LLVM_FALLTHROUGH; 2303 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2304 VT, OpVT); 2305 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2306 return getUNDEF(VT); 2307 LLVM_FALLTHROUGH; 2308 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2309 R==APFloat::cmpEqual, dl, VT, 2310 OpVT); 2311 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2312 return getUNDEF(VT); 2313 LLVM_FALLTHROUGH; 2314 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2315 R==APFloat::cmpEqual, dl, VT, OpVT); 2316 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2317 OpVT); 2318 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2319 OpVT); 2320 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2321 R==APFloat::cmpEqual, dl, VT, 2322 OpVT); 2323 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2324 OpVT); 2325 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2326 R==APFloat::cmpLessThan, dl, VT, 2327 OpVT); 2328 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2329 R==APFloat::cmpUnordered, dl, VT, 2330 OpVT); 2331 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2332 VT, OpVT); 2333 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2334 OpVT); 2335 } 2336 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2337 // Ensure that the constant occurs on the RHS. 2338 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2339 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2340 return SDValue(); 2341 return getSetCC(dl, VT, N2, N1, SwappedCond); 2342 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2343 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2344 // If an operand is known to be a nan (or undef that could be a nan), we can 2345 // fold it. 2346 // Choosing NaN for the undef will always make unordered comparison succeed 2347 // and ordered comparison fails. 2348 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2349 switch (ISD::getUnorderedFlavor(Cond)) { 2350 default: 2351 llvm_unreachable("Unknown flavor!"); 2352 case 0: // Known false. 2353 return getBoolConstant(false, dl, VT, OpVT); 2354 case 1: // Known true. 2355 return getBoolConstant(true, dl, VT, OpVT); 2356 case 2: // Undefined. 2357 return getUNDEF(VT); 2358 } 2359 } 2360 2361 // Could not fold it. 2362 return SDValue(); 2363 } 2364 2365 /// See if the specified operand can be simplified with the knowledge that only 2366 /// the bits specified by DemandedBits are used. 2367 /// TODO: really we should be making this into the DAG equivalent of 2368 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2369 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2370 EVT VT = V.getValueType(); 2371 2372 if (VT.isScalableVector()) 2373 return SDValue(); 2374 2375 APInt DemandedElts = VT.isVector() 2376 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2377 : APInt(1, 1); 2378 return GetDemandedBits(V, DemandedBits, DemandedElts); 2379 } 2380 2381 /// See if the specified operand can be simplified with the knowledge that only 2382 /// the bits specified by DemandedBits are used in the elements specified by 2383 /// DemandedElts. 2384 /// TODO: really we should be making this into the DAG equivalent of 2385 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2386 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2387 const APInt &DemandedElts) { 2388 switch (V.getOpcode()) { 2389 default: 2390 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2391 *this, 0); 2392 case ISD::Constant: { 2393 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2394 APInt NewVal = CVal & DemandedBits; 2395 if (NewVal != CVal) 2396 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2397 break; 2398 } 2399 case ISD::SRL: 2400 // Only look at single-use SRLs. 2401 if (!V.getNode()->hasOneUse()) 2402 break; 2403 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2404 // See if we can recursively simplify the LHS. 2405 unsigned Amt = RHSC->getZExtValue(); 2406 2407 // Watch out for shift count overflow though. 2408 if (Amt >= DemandedBits.getBitWidth()) 2409 break; 2410 APInt SrcDemandedBits = DemandedBits << Amt; 2411 if (SDValue SimplifyLHS = 2412 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2413 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2414 V.getOperand(1)); 2415 } 2416 break; 2417 } 2418 return SDValue(); 2419 } 2420 2421 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2422 /// use this predicate to simplify operations downstream. 2423 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2424 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2425 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2426 } 2427 2428 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2429 /// this predicate to simplify operations downstream. Mask is known to be zero 2430 /// for bits that V cannot have. 2431 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2432 unsigned Depth) const { 2433 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2434 } 2435 2436 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2437 /// DemandedElts. We use this predicate to simplify operations downstream. 2438 /// Mask is known to be zero for bits that V cannot have. 2439 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2440 const APInt &DemandedElts, 2441 unsigned Depth) const { 2442 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2443 } 2444 2445 /// Return true if the DemandedElts of the vector Op are all zero. We 2446 /// use this predicate to simplify operations downstream. 2447 bool SelectionDAG::MaskedElementsAreZero(SDValue Op, const APInt &DemandedElts, 2448 unsigned Depth) const { 2449 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2450 APInt DemandedBits = APInt::getAllOnesValue(BitWidth); 2451 return MaskedValueIsZero(Op, DemandedBits, DemandedElts, Depth); 2452 } 2453 2454 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2455 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2456 unsigned Depth) const { 2457 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2458 } 2459 2460 /// isSplatValue - Return true if the vector V has the same value 2461 /// across all DemandedElts. For scalable vectors it does not make 2462 /// sense to specify which elements are demanded or undefined, therefore 2463 /// they are simply ignored. 2464 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2465 APInt &UndefElts, unsigned Depth) { 2466 EVT VT = V.getValueType(); 2467 assert(VT.isVector() && "Vector type expected"); 2468 2469 if (!VT.isScalableVector() && !DemandedElts) 2470 return false; // No demanded elts, better to assume we don't know anything. 2471 2472 if (Depth >= MaxRecursionDepth) 2473 return false; // Limit search depth. 2474 2475 // Deal with some common cases here that work for both fixed and scalable 2476 // vector types. 2477 switch (V.getOpcode()) { 2478 case ISD::SPLAT_VECTOR: 2479 UndefElts = V.getOperand(0).isUndef() 2480 ? APInt::getAllOnesValue(DemandedElts.getBitWidth()) 2481 : APInt(DemandedElts.getBitWidth(), 0); 2482 return true; 2483 case ISD::ADD: 2484 case ISD::SUB: 2485 case ISD::AND: 2486 case ISD::XOR: 2487 case ISD::OR: { 2488 APInt UndefLHS, UndefRHS; 2489 SDValue LHS = V.getOperand(0); 2490 SDValue RHS = V.getOperand(1); 2491 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2492 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2493 UndefElts = UndefLHS | UndefRHS; 2494 return true; 2495 } 2496 return false; 2497 } 2498 case ISD::ABS: 2499 case ISD::TRUNCATE: 2500 case ISD::SIGN_EXTEND: 2501 case ISD::ZERO_EXTEND: 2502 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2503 } 2504 2505 // We don't support other cases than those above for scalable vectors at 2506 // the moment. 2507 if (VT.isScalableVector()) 2508 return false; 2509 2510 unsigned NumElts = VT.getVectorNumElements(); 2511 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2512 UndefElts = APInt::getNullValue(NumElts); 2513 2514 switch (V.getOpcode()) { 2515 case ISD::BUILD_VECTOR: { 2516 SDValue Scl; 2517 for (unsigned i = 0; i != NumElts; ++i) { 2518 SDValue Op = V.getOperand(i); 2519 if (Op.isUndef()) { 2520 UndefElts.setBit(i); 2521 continue; 2522 } 2523 if (!DemandedElts[i]) 2524 continue; 2525 if (Scl && Scl != Op) 2526 return false; 2527 Scl = Op; 2528 } 2529 return true; 2530 } 2531 case ISD::VECTOR_SHUFFLE: { 2532 // Check if this is a shuffle node doing a splat. 2533 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2534 int SplatIndex = -1; 2535 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2536 for (int i = 0; i != (int)NumElts; ++i) { 2537 int M = Mask[i]; 2538 if (M < 0) { 2539 UndefElts.setBit(i); 2540 continue; 2541 } 2542 if (!DemandedElts[i]) 2543 continue; 2544 if (0 <= SplatIndex && SplatIndex != M) 2545 return false; 2546 SplatIndex = M; 2547 } 2548 return true; 2549 } 2550 case ISD::EXTRACT_SUBVECTOR: { 2551 // Offset the demanded elts by the subvector index. 2552 SDValue Src = V.getOperand(0); 2553 // We don't support scalable vectors at the moment. 2554 if (Src.getValueType().isScalableVector()) 2555 return false; 2556 uint64_t Idx = V.getConstantOperandVal(1); 2557 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2558 APInt UndefSrcElts; 2559 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2560 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2561 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2562 return true; 2563 } 2564 break; 2565 } 2566 } 2567 2568 return false; 2569 } 2570 2571 /// Helper wrapper to main isSplatValue function. 2572 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) { 2573 EVT VT = V.getValueType(); 2574 assert(VT.isVector() && "Vector type expected"); 2575 2576 APInt UndefElts; 2577 APInt DemandedElts; 2578 2579 // For now we don't support this with scalable vectors. 2580 if (!VT.isScalableVector()) 2581 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2582 return isSplatValue(V, DemandedElts, UndefElts) && 2583 (AllowUndefs || !UndefElts); 2584 } 2585 2586 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2587 V = peekThroughExtractSubvectors(V); 2588 2589 EVT VT = V.getValueType(); 2590 unsigned Opcode = V.getOpcode(); 2591 switch (Opcode) { 2592 default: { 2593 APInt UndefElts; 2594 APInt DemandedElts; 2595 2596 if (!VT.isScalableVector()) 2597 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2598 2599 if (isSplatValue(V, DemandedElts, UndefElts)) { 2600 if (VT.isScalableVector()) { 2601 // DemandedElts and UndefElts are ignored for scalable vectors, since 2602 // the only supported cases are SPLAT_VECTOR nodes. 2603 SplatIdx = 0; 2604 } else { 2605 // Handle case where all demanded elements are UNDEF. 2606 if (DemandedElts.isSubsetOf(UndefElts)) { 2607 SplatIdx = 0; 2608 return getUNDEF(VT); 2609 } 2610 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2611 } 2612 return V; 2613 } 2614 break; 2615 } 2616 case ISD::SPLAT_VECTOR: 2617 SplatIdx = 0; 2618 return V; 2619 case ISD::VECTOR_SHUFFLE: { 2620 if (VT.isScalableVector()) 2621 return SDValue(); 2622 2623 // Check if this is a shuffle node doing a splat. 2624 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2625 // getTargetVShiftNode currently struggles without the splat source. 2626 auto *SVN = cast<ShuffleVectorSDNode>(V); 2627 if (!SVN->isSplat()) 2628 break; 2629 int Idx = SVN->getSplatIndex(); 2630 int NumElts = V.getValueType().getVectorNumElements(); 2631 SplatIdx = Idx % NumElts; 2632 return V.getOperand(Idx / NumElts); 2633 } 2634 } 2635 2636 return SDValue(); 2637 } 2638 2639 SDValue SelectionDAG::getSplatValue(SDValue V) { 2640 int SplatIdx; 2641 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) 2642 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), 2643 SrcVector.getValueType().getScalarType(), SrcVector, 2644 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2645 return SDValue(); 2646 } 2647 2648 const APInt * 2649 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2650 const APInt &DemandedElts) const { 2651 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2652 V.getOpcode() == ISD::SRA) && 2653 "Unknown shift node"); 2654 unsigned BitWidth = V.getScalarValueSizeInBits(); 2655 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2656 // Shifting more than the bitwidth is not valid. 2657 const APInt &ShAmt = SA->getAPIntValue(); 2658 if (ShAmt.ult(BitWidth)) 2659 return &ShAmt; 2660 } 2661 return nullptr; 2662 } 2663 2664 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2665 SDValue V, const APInt &DemandedElts) const { 2666 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2667 V.getOpcode() == ISD::SRA) && 2668 "Unknown shift node"); 2669 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2670 return ValidAmt; 2671 unsigned BitWidth = V.getScalarValueSizeInBits(); 2672 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2673 if (!BV) 2674 return nullptr; 2675 const APInt *MinShAmt = nullptr; 2676 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2677 if (!DemandedElts[i]) 2678 continue; 2679 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2680 if (!SA) 2681 return nullptr; 2682 // Shifting more than the bitwidth is not valid. 2683 const APInt &ShAmt = SA->getAPIntValue(); 2684 if (ShAmt.uge(BitWidth)) 2685 return nullptr; 2686 if (MinShAmt && MinShAmt->ule(ShAmt)) 2687 continue; 2688 MinShAmt = &ShAmt; 2689 } 2690 return MinShAmt; 2691 } 2692 2693 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2694 SDValue V, const APInt &DemandedElts) const { 2695 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2696 V.getOpcode() == ISD::SRA) && 2697 "Unknown shift node"); 2698 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2699 return ValidAmt; 2700 unsigned BitWidth = V.getScalarValueSizeInBits(); 2701 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2702 if (!BV) 2703 return nullptr; 2704 const APInt *MaxShAmt = nullptr; 2705 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2706 if (!DemandedElts[i]) 2707 continue; 2708 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2709 if (!SA) 2710 return nullptr; 2711 // Shifting more than the bitwidth is not valid. 2712 const APInt &ShAmt = SA->getAPIntValue(); 2713 if (ShAmt.uge(BitWidth)) 2714 return nullptr; 2715 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2716 continue; 2717 MaxShAmt = &ShAmt; 2718 } 2719 return MaxShAmt; 2720 } 2721 2722 /// Determine which bits of Op are known to be either zero or one and return 2723 /// them in Known. For vectors, the known bits are those that are shared by 2724 /// every vector element. 2725 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2726 EVT VT = Op.getValueType(); 2727 2728 // TOOD: Until we have a plan for how to represent demanded elements for 2729 // scalable vectors, we can just bail out for now. 2730 if (Op.getValueType().isScalableVector()) { 2731 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2732 return KnownBits(BitWidth); 2733 } 2734 2735 APInt DemandedElts = VT.isVector() 2736 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2737 : APInt(1, 1); 2738 return computeKnownBits(Op, DemandedElts, Depth); 2739 } 2740 2741 /// Determine which bits of Op are known to be either zero or one and return 2742 /// them in Known. The DemandedElts argument allows us to only collect the known 2743 /// bits that are shared by the requested vector elements. 2744 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2745 unsigned Depth) const { 2746 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2747 2748 KnownBits Known(BitWidth); // Don't know anything. 2749 2750 // TOOD: Until we have a plan for how to represent demanded elements for 2751 // scalable vectors, we can just bail out for now. 2752 if (Op.getValueType().isScalableVector()) 2753 return Known; 2754 2755 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2756 // We know all of the bits for a constant! 2757 return KnownBits::makeConstant(C->getAPIntValue()); 2758 } 2759 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2760 // We know all of the bits for a constant fp! 2761 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2762 } 2763 2764 if (Depth >= MaxRecursionDepth) 2765 return Known; // Limit search depth. 2766 2767 KnownBits Known2; 2768 unsigned NumElts = DemandedElts.getBitWidth(); 2769 assert((!Op.getValueType().isVector() || 2770 NumElts == Op.getValueType().getVectorNumElements()) && 2771 "Unexpected vector size"); 2772 2773 if (!DemandedElts) 2774 return Known; // No demanded elts, better to assume we don't know anything. 2775 2776 unsigned Opcode = Op.getOpcode(); 2777 switch (Opcode) { 2778 case ISD::BUILD_VECTOR: 2779 // Collect the known bits that are shared by every demanded vector element. 2780 Known.Zero.setAllBits(); Known.One.setAllBits(); 2781 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2782 if (!DemandedElts[i]) 2783 continue; 2784 2785 SDValue SrcOp = Op.getOperand(i); 2786 Known2 = computeKnownBits(SrcOp, Depth + 1); 2787 2788 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2789 if (SrcOp.getValueSizeInBits() != BitWidth) { 2790 assert(SrcOp.getValueSizeInBits() > BitWidth && 2791 "Expected BUILD_VECTOR implicit truncation"); 2792 Known2 = Known2.trunc(BitWidth); 2793 } 2794 2795 // Known bits are the values that are shared by every demanded element. 2796 Known = KnownBits::commonBits(Known, Known2); 2797 2798 // If we don't know any bits, early out. 2799 if (Known.isUnknown()) 2800 break; 2801 } 2802 break; 2803 case ISD::VECTOR_SHUFFLE: { 2804 // Collect the known bits that are shared by every vector element referenced 2805 // by the shuffle. 2806 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2807 Known.Zero.setAllBits(); Known.One.setAllBits(); 2808 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2809 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2810 for (unsigned i = 0; i != NumElts; ++i) { 2811 if (!DemandedElts[i]) 2812 continue; 2813 2814 int M = SVN->getMaskElt(i); 2815 if (M < 0) { 2816 // For UNDEF elements, we don't know anything about the common state of 2817 // the shuffle result. 2818 Known.resetAll(); 2819 DemandedLHS.clearAllBits(); 2820 DemandedRHS.clearAllBits(); 2821 break; 2822 } 2823 2824 if ((unsigned)M < NumElts) 2825 DemandedLHS.setBit((unsigned)M % NumElts); 2826 else 2827 DemandedRHS.setBit((unsigned)M % NumElts); 2828 } 2829 // Known bits are the values that are shared by every demanded element. 2830 if (!!DemandedLHS) { 2831 SDValue LHS = Op.getOperand(0); 2832 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2833 Known = KnownBits::commonBits(Known, Known2); 2834 } 2835 // If we don't know any bits, early out. 2836 if (Known.isUnknown()) 2837 break; 2838 if (!!DemandedRHS) { 2839 SDValue RHS = Op.getOperand(1); 2840 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2841 Known = KnownBits::commonBits(Known, Known2); 2842 } 2843 break; 2844 } 2845 case ISD::CONCAT_VECTORS: { 2846 // Split DemandedElts and test each of the demanded subvectors. 2847 Known.Zero.setAllBits(); Known.One.setAllBits(); 2848 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2849 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2850 unsigned NumSubVectors = Op.getNumOperands(); 2851 for (unsigned i = 0; i != NumSubVectors; ++i) { 2852 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); 2853 DemandedSub = DemandedSub.trunc(NumSubVectorElts); 2854 if (!!DemandedSub) { 2855 SDValue Sub = Op.getOperand(i); 2856 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2857 Known = KnownBits::commonBits(Known, Known2); 2858 } 2859 // If we don't know any bits, early out. 2860 if (Known.isUnknown()) 2861 break; 2862 } 2863 break; 2864 } 2865 case ISD::INSERT_SUBVECTOR: { 2866 // Demand any elements from the subvector and the remainder from the src its 2867 // inserted into. 2868 SDValue Src = Op.getOperand(0); 2869 SDValue Sub = Op.getOperand(1); 2870 uint64_t Idx = Op.getConstantOperandVal(2); 2871 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2872 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2873 APInt DemandedSrcElts = DemandedElts; 2874 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 2875 2876 Known.One.setAllBits(); 2877 Known.Zero.setAllBits(); 2878 if (!!DemandedSubElts) { 2879 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2880 if (Known.isUnknown()) 2881 break; // early-out. 2882 } 2883 if (!!DemandedSrcElts) { 2884 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2885 Known = KnownBits::commonBits(Known, Known2); 2886 } 2887 break; 2888 } 2889 case ISD::EXTRACT_SUBVECTOR: { 2890 // Offset the demanded elts by the subvector index. 2891 SDValue Src = Op.getOperand(0); 2892 // Bail until we can represent demanded elements for scalable vectors. 2893 if (Src.getValueType().isScalableVector()) 2894 break; 2895 uint64_t Idx = Op.getConstantOperandVal(1); 2896 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2897 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2898 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2899 break; 2900 } 2901 case ISD::SCALAR_TO_VECTOR: { 2902 // We know about scalar_to_vector as much as we know about it source, 2903 // which becomes the first element of otherwise unknown vector. 2904 if (DemandedElts != 1) 2905 break; 2906 2907 SDValue N0 = Op.getOperand(0); 2908 Known = computeKnownBits(N0, Depth + 1); 2909 if (N0.getValueSizeInBits() != BitWidth) 2910 Known = Known.trunc(BitWidth); 2911 2912 break; 2913 } 2914 case ISD::BITCAST: { 2915 SDValue N0 = Op.getOperand(0); 2916 EVT SubVT = N0.getValueType(); 2917 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 2918 2919 // Ignore bitcasts from unsupported types. 2920 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 2921 break; 2922 2923 // Fast handling of 'identity' bitcasts. 2924 if (BitWidth == SubBitWidth) { 2925 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 2926 break; 2927 } 2928 2929 bool IsLE = getDataLayout().isLittleEndian(); 2930 2931 // Bitcast 'small element' vector to 'large element' scalar/vector. 2932 if ((BitWidth % SubBitWidth) == 0) { 2933 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 2934 2935 // Collect known bits for the (larger) output by collecting the known 2936 // bits from each set of sub elements and shift these into place. 2937 // We need to separately call computeKnownBits for each set of 2938 // sub elements as the knownbits for each is likely to be different. 2939 unsigned SubScale = BitWidth / SubBitWidth; 2940 APInt SubDemandedElts(NumElts * SubScale, 0); 2941 for (unsigned i = 0; i != NumElts; ++i) 2942 if (DemandedElts[i]) 2943 SubDemandedElts.setBit(i * SubScale); 2944 2945 for (unsigned i = 0; i != SubScale; ++i) { 2946 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 2947 Depth + 1); 2948 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 2949 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts); 2950 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts); 2951 } 2952 } 2953 2954 // Bitcast 'large element' scalar/vector to 'small element' vector. 2955 if ((SubBitWidth % BitWidth) == 0) { 2956 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 2957 2958 // Collect known bits for the (smaller) output by collecting the known 2959 // bits from the overlapping larger input elements and extracting the 2960 // sub sections we actually care about. 2961 unsigned SubScale = SubBitWidth / BitWidth; 2962 APInt SubDemandedElts(NumElts / SubScale, 0); 2963 for (unsigned i = 0; i != NumElts; ++i) 2964 if (DemandedElts[i]) 2965 SubDemandedElts.setBit(i / SubScale); 2966 2967 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 2968 2969 Known.Zero.setAllBits(); Known.One.setAllBits(); 2970 for (unsigned i = 0; i != NumElts; ++i) 2971 if (DemandedElts[i]) { 2972 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 2973 unsigned Offset = (Shifts % SubScale) * BitWidth; 2974 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth); 2975 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth); 2976 // If we don't know any bits, early out. 2977 if (Known.isUnknown()) 2978 break; 2979 } 2980 } 2981 break; 2982 } 2983 case ISD::AND: 2984 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2985 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2986 2987 Known &= Known2; 2988 break; 2989 case ISD::OR: 2990 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2991 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2992 2993 Known |= Known2; 2994 break; 2995 case ISD::XOR: 2996 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2997 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2998 2999 Known ^= Known2; 3000 break; 3001 case ISD::MUL: { 3002 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3003 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3004 Known = KnownBits::mul(Known, Known2); 3005 break; 3006 } 3007 case ISD::MULHU: { 3008 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3009 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3010 Known = KnownBits::mulhu(Known, Known2); 3011 break; 3012 } 3013 case ISD::MULHS: { 3014 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3015 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3016 Known = KnownBits::mulhs(Known, Known2); 3017 break; 3018 } 3019 case ISD::UMUL_LOHI: { 3020 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3021 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3022 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3023 if (Op.getResNo() == 0) 3024 Known = KnownBits::mul(Known, Known2); 3025 else 3026 Known = KnownBits::mulhu(Known, Known2); 3027 break; 3028 } 3029 case ISD::SMUL_LOHI: { 3030 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3031 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3032 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3033 if (Op.getResNo() == 0) 3034 Known = KnownBits::mul(Known, Known2); 3035 else 3036 Known = KnownBits::mulhs(Known, Known2); 3037 break; 3038 } 3039 case ISD::UDIV: { 3040 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3041 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3042 Known = KnownBits::udiv(Known, Known2); 3043 break; 3044 } 3045 case ISD::SELECT: 3046 case ISD::VSELECT: 3047 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3048 // If we don't know any bits, early out. 3049 if (Known.isUnknown()) 3050 break; 3051 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3052 3053 // Only known if known in both the LHS and RHS. 3054 Known = KnownBits::commonBits(Known, Known2); 3055 break; 3056 case ISD::SELECT_CC: 3057 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3058 // If we don't know any bits, early out. 3059 if (Known.isUnknown()) 3060 break; 3061 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3062 3063 // Only known if known in both the LHS and RHS. 3064 Known = KnownBits::commonBits(Known, Known2); 3065 break; 3066 case ISD::SMULO: 3067 case ISD::UMULO: 3068 if (Op.getResNo() != 1) 3069 break; 3070 // The boolean result conforms to getBooleanContents. 3071 // If we know the result of a setcc has the top bits zero, use this info. 3072 // We know that we have an integer-based boolean since these operations 3073 // are only available for integer. 3074 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3075 TargetLowering::ZeroOrOneBooleanContent && 3076 BitWidth > 1) 3077 Known.Zero.setBitsFrom(1); 3078 break; 3079 case ISD::SETCC: 3080 case ISD::STRICT_FSETCC: 3081 case ISD::STRICT_FSETCCS: { 3082 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3083 // If we know the result of a setcc has the top bits zero, use this info. 3084 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3085 TargetLowering::ZeroOrOneBooleanContent && 3086 BitWidth > 1) 3087 Known.Zero.setBitsFrom(1); 3088 break; 3089 } 3090 case ISD::SHL: 3091 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3092 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3093 Known = KnownBits::shl(Known, Known2); 3094 3095 // Minimum shift low bits are known zero. 3096 if (const APInt *ShMinAmt = 3097 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3098 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3099 break; 3100 case ISD::SRL: 3101 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3102 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3103 Known = KnownBits::lshr(Known, Known2); 3104 3105 // Minimum shift high bits are known zero. 3106 if (const APInt *ShMinAmt = 3107 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3108 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3109 break; 3110 case ISD::SRA: 3111 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3112 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3113 Known = KnownBits::ashr(Known, Known2); 3114 // TODO: Add minimum shift high known sign bits. 3115 break; 3116 case ISD::FSHL: 3117 case ISD::FSHR: 3118 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3119 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3120 3121 // For fshl, 0-shift returns the 1st arg. 3122 // For fshr, 0-shift returns the 2nd arg. 3123 if (Amt == 0) { 3124 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3125 DemandedElts, Depth + 1); 3126 break; 3127 } 3128 3129 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3130 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3131 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3132 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3133 if (Opcode == ISD::FSHL) { 3134 Known.One <<= Amt; 3135 Known.Zero <<= Amt; 3136 Known2.One.lshrInPlace(BitWidth - Amt); 3137 Known2.Zero.lshrInPlace(BitWidth - Amt); 3138 } else { 3139 Known.One <<= BitWidth - Amt; 3140 Known.Zero <<= BitWidth - Amt; 3141 Known2.One.lshrInPlace(Amt); 3142 Known2.Zero.lshrInPlace(Amt); 3143 } 3144 Known.One |= Known2.One; 3145 Known.Zero |= Known2.Zero; 3146 } 3147 break; 3148 case ISD::SIGN_EXTEND_INREG: { 3149 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3150 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3151 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3152 break; 3153 } 3154 case ISD::CTTZ: 3155 case ISD::CTTZ_ZERO_UNDEF: { 3156 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3157 // If we have a known 1, its position is our upper bound. 3158 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3159 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3160 Known.Zero.setBitsFrom(LowBits); 3161 break; 3162 } 3163 case ISD::CTLZ: 3164 case ISD::CTLZ_ZERO_UNDEF: { 3165 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3166 // If we have a known 1, its position is our upper bound. 3167 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3168 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3169 Known.Zero.setBitsFrom(LowBits); 3170 break; 3171 } 3172 case ISD::CTPOP: { 3173 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3174 // If we know some of the bits are zero, they can't be one. 3175 unsigned PossibleOnes = Known2.countMaxPopulation(); 3176 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3177 break; 3178 } 3179 case ISD::PARITY: { 3180 // Parity returns 0 everywhere but the LSB. 3181 Known.Zero.setBitsFrom(1); 3182 break; 3183 } 3184 case ISD::LOAD: { 3185 LoadSDNode *LD = cast<LoadSDNode>(Op); 3186 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3187 if (ISD::isNON_EXTLoad(LD) && Cst) { 3188 // Determine any common known bits from the loaded constant pool value. 3189 Type *CstTy = Cst->getType(); 3190 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3191 // If its a vector splat, then we can (quickly) reuse the scalar path. 3192 // NOTE: We assume all elements match and none are UNDEF. 3193 if (CstTy->isVectorTy()) { 3194 if (const Constant *Splat = Cst->getSplatValue()) { 3195 Cst = Splat; 3196 CstTy = Cst->getType(); 3197 } 3198 } 3199 // TODO - do we need to handle different bitwidths? 3200 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3201 // Iterate across all vector elements finding common known bits. 3202 Known.One.setAllBits(); 3203 Known.Zero.setAllBits(); 3204 for (unsigned i = 0; i != NumElts; ++i) { 3205 if (!DemandedElts[i]) 3206 continue; 3207 if (Constant *Elt = Cst->getAggregateElement(i)) { 3208 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3209 const APInt &Value = CInt->getValue(); 3210 Known.One &= Value; 3211 Known.Zero &= ~Value; 3212 continue; 3213 } 3214 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3215 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3216 Known.One &= Value; 3217 Known.Zero &= ~Value; 3218 continue; 3219 } 3220 } 3221 Known.One.clearAllBits(); 3222 Known.Zero.clearAllBits(); 3223 break; 3224 } 3225 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3226 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3227 Known = KnownBits::makeConstant(CInt->getValue()); 3228 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3229 Known = 3230 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3231 } 3232 } 3233 } 3234 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3235 // If this is a ZEXTLoad and we are looking at the loaded value. 3236 EVT VT = LD->getMemoryVT(); 3237 unsigned MemBits = VT.getScalarSizeInBits(); 3238 Known.Zero.setBitsFrom(MemBits); 3239 } else if (const MDNode *Ranges = LD->getRanges()) { 3240 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3241 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3242 } 3243 break; 3244 } 3245 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3246 EVT InVT = Op.getOperand(0).getValueType(); 3247 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3248 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3249 Known = Known.zext(BitWidth); 3250 break; 3251 } 3252 case ISD::ZERO_EXTEND: { 3253 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3254 Known = Known.zext(BitWidth); 3255 break; 3256 } 3257 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3258 EVT InVT = Op.getOperand(0).getValueType(); 3259 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3260 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3261 // If the sign bit is known to be zero or one, then sext will extend 3262 // it to the top bits, else it will just zext. 3263 Known = Known.sext(BitWidth); 3264 break; 3265 } 3266 case ISD::SIGN_EXTEND: { 3267 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3268 // If the sign bit is known to be zero or one, then sext will extend 3269 // it to the top bits, else it will just zext. 3270 Known = Known.sext(BitWidth); 3271 break; 3272 } 3273 case ISD::ANY_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.anyext(BitWidth); 3278 break; 3279 } 3280 case ISD::ANY_EXTEND: { 3281 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3282 Known = Known.anyext(BitWidth); 3283 break; 3284 } 3285 case ISD::TRUNCATE: { 3286 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3287 Known = Known.trunc(BitWidth); 3288 break; 3289 } 3290 case ISD::AssertZext: { 3291 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3292 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3293 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3294 Known.Zero |= (~InMask); 3295 Known.One &= (~Known.Zero); 3296 break; 3297 } 3298 case ISD::AssertAlign: { 3299 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3300 assert(LogOfAlign != 0); 3301 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3302 // well as clearing one bits. 3303 Known.Zero.setLowBits(LogOfAlign); 3304 Known.One.clearLowBits(LogOfAlign); 3305 break; 3306 } 3307 case ISD::FGETSIGN: 3308 // All bits are zero except the low bit. 3309 Known.Zero.setBitsFrom(1); 3310 break; 3311 case ISD::USUBO: 3312 case ISD::SSUBO: 3313 if (Op.getResNo() == 1) { 3314 // If we know the result of a setcc has the top bits zero, use this info. 3315 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3316 TargetLowering::ZeroOrOneBooleanContent && 3317 BitWidth > 1) 3318 Known.Zero.setBitsFrom(1); 3319 break; 3320 } 3321 LLVM_FALLTHROUGH; 3322 case ISD::SUB: 3323 case ISD::SUBC: { 3324 assert(Op.getResNo() == 0 && 3325 "We only compute knownbits for the difference here."); 3326 3327 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3328 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3329 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3330 Known, Known2); 3331 break; 3332 } 3333 case ISD::UADDO: 3334 case ISD::SADDO: 3335 case ISD::ADDCARRY: 3336 if (Op.getResNo() == 1) { 3337 // If we know the result of a setcc has the top bits zero, use this info. 3338 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3339 TargetLowering::ZeroOrOneBooleanContent && 3340 BitWidth > 1) 3341 Known.Zero.setBitsFrom(1); 3342 break; 3343 } 3344 LLVM_FALLTHROUGH; 3345 case ISD::ADD: 3346 case ISD::ADDC: 3347 case ISD::ADDE: { 3348 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3349 3350 // With ADDE and ADDCARRY, a carry bit may be added in. 3351 KnownBits Carry(1); 3352 if (Opcode == ISD::ADDE) 3353 // Can't track carry from glue, set carry to unknown. 3354 Carry.resetAll(); 3355 else if (Opcode == ISD::ADDCARRY) 3356 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3357 // the trouble (how often will we find a known carry bit). And I haven't 3358 // tested this very much yet, but something like this might work: 3359 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3360 // Carry = Carry.zextOrTrunc(1, false); 3361 Carry.resetAll(); 3362 else 3363 Carry.setAllZero(); 3364 3365 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3366 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3367 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3368 break; 3369 } 3370 case ISD::SREM: { 3371 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3372 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3373 Known = KnownBits::srem(Known, Known2); 3374 break; 3375 } 3376 case ISD::UREM: { 3377 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3378 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3379 Known = KnownBits::urem(Known, Known2); 3380 break; 3381 } 3382 case ISD::EXTRACT_ELEMENT: { 3383 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3384 const unsigned Index = Op.getConstantOperandVal(1); 3385 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3386 3387 // Remove low part of known bits mask 3388 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3389 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3390 3391 // Remove high part of known bit mask 3392 Known = Known.trunc(EltBitWidth); 3393 break; 3394 } 3395 case ISD::EXTRACT_VECTOR_ELT: { 3396 SDValue InVec = Op.getOperand(0); 3397 SDValue EltNo = Op.getOperand(1); 3398 EVT VecVT = InVec.getValueType(); 3399 // computeKnownBits not yet implemented for scalable vectors. 3400 if (VecVT.isScalableVector()) 3401 break; 3402 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3403 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3404 3405 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3406 // anything about the extended bits. 3407 if (BitWidth > EltBitWidth) 3408 Known = Known.trunc(EltBitWidth); 3409 3410 // If we know the element index, just demand that vector element, else for 3411 // an unknown element index, ignore DemandedElts and demand them all. 3412 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 3413 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3414 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3415 DemandedSrcElts = 3416 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3417 3418 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3419 if (BitWidth > EltBitWidth) 3420 Known = Known.anyext(BitWidth); 3421 break; 3422 } 3423 case ISD::INSERT_VECTOR_ELT: { 3424 // If we know the element index, split the demand between the 3425 // source vector and the inserted element, otherwise assume we need 3426 // the original demanded vector elements and the value. 3427 SDValue InVec = Op.getOperand(0); 3428 SDValue InVal = Op.getOperand(1); 3429 SDValue EltNo = Op.getOperand(2); 3430 bool DemandedVal = true; 3431 APInt DemandedVecElts = DemandedElts; 3432 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3433 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3434 unsigned EltIdx = CEltNo->getZExtValue(); 3435 DemandedVal = !!DemandedElts[EltIdx]; 3436 DemandedVecElts.clearBit(EltIdx); 3437 } 3438 Known.One.setAllBits(); 3439 Known.Zero.setAllBits(); 3440 if (DemandedVal) { 3441 Known2 = computeKnownBits(InVal, Depth + 1); 3442 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3443 } 3444 if (!!DemandedVecElts) { 3445 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3446 Known = KnownBits::commonBits(Known, Known2); 3447 } 3448 break; 3449 } 3450 case ISD::BITREVERSE: { 3451 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3452 Known = Known2.reverseBits(); 3453 break; 3454 } 3455 case ISD::BSWAP: { 3456 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3457 Known = Known2.byteSwap(); 3458 break; 3459 } 3460 case ISD::ABS: { 3461 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3462 Known = Known2.abs(); 3463 break; 3464 } 3465 case ISD::USUBSAT: { 3466 // The result of usubsat will never be larger than the LHS. 3467 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3468 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3469 break; 3470 } 3471 case ISD::UMIN: { 3472 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3473 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3474 Known = KnownBits::umin(Known, Known2); 3475 break; 3476 } 3477 case ISD::UMAX: { 3478 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3479 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3480 Known = KnownBits::umax(Known, Known2); 3481 break; 3482 } 3483 case ISD::SMIN: 3484 case ISD::SMAX: { 3485 // If we have a clamp pattern, we know that the number of sign bits will be 3486 // the minimum of the clamp min/max range. 3487 bool IsMax = (Opcode == ISD::SMAX); 3488 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3489 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3490 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3491 CstHigh = 3492 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3493 if (CstLow && CstHigh) { 3494 if (!IsMax) 3495 std::swap(CstLow, CstHigh); 3496 3497 const APInt &ValueLow = CstLow->getAPIntValue(); 3498 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3499 if (ValueLow.sle(ValueHigh)) { 3500 unsigned LowSignBits = ValueLow.getNumSignBits(); 3501 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3502 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3503 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3504 Known.One.setHighBits(MinSignBits); 3505 break; 3506 } 3507 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3508 Known.Zero.setHighBits(MinSignBits); 3509 break; 3510 } 3511 } 3512 } 3513 3514 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3515 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3516 if (IsMax) 3517 Known = KnownBits::smax(Known, Known2); 3518 else 3519 Known = KnownBits::smin(Known, Known2); 3520 break; 3521 } 3522 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3523 if (Op.getResNo() == 1) { 3524 // The boolean result conforms to getBooleanContents. 3525 // If we know the result of a setcc has the top bits zero, use this info. 3526 // We know that we have an integer-based boolean since these operations 3527 // are only available for integer. 3528 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3529 TargetLowering::ZeroOrOneBooleanContent && 3530 BitWidth > 1) 3531 Known.Zero.setBitsFrom(1); 3532 break; 3533 } 3534 LLVM_FALLTHROUGH; 3535 case ISD::ATOMIC_CMP_SWAP: 3536 case ISD::ATOMIC_SWAP: 3537 case ISD::ATOMIC_LOAD_ADD: 3538 case ISD::ATOMIC_LOAD_SUB: 3539 case ISD::ATOMIC_LOAD_AND: 3540 case ISD::ATOMIC_LOAD_CLR: 3541 case ISD::ATOMIC_LOAD_OR: 3542 case ISD::ATOMIC_LOAD_XOR: 3543 case ISD::ATOMIC_LOAD_NAND: 3544 case ISD::ATOMIC_LOAD_MIN: 3545 case ISD::ATOMIC_LOAD_MAX: 3546 case ISD::ATOMIC_LOAD_UMIN: 3547 case ISD::ATOMIC_LOAD_UMAX: 3548 case ISD::ATOMIC_LOAD: { 3549 unsigned MemBits = 3550 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3551 // If we are looking at the loaded value. 3552 if (Op.getResNo() == 0) { 3553 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3554 Known.Zero.setBitsFrom(MemBits); 3555 } 3556 break; 3557 } 3558 case ISD::FrameIndex: 3559 case ISD::TargetFrameIndex: 3560 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3561 Known, getMachineFunction()); 3562 break; 3563 3564 default: 3565 if (Opcode < ISD::BUILTIN_OP_END) 3566 break; 3567 LLVM_FALLTHROUGH; 3568 case ISD::INTRINSIC_WO_CHAIN: 3569 case ISD::INTRINSIC_W_CHAIN: 3570 case ISD::INTRINSIC_VOID: 3571 // Allow the target to implement this method for its nodes. 3572 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3573 break; 3574 } 3575 3576 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3577 return Known; 3578 } 3579 3580 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3581 SDValue N1) const { 3582 // X + 0 never overflow 3583 if (isNullConstant(N1)) 3584 return OFK_Never; 3585 3586 KnownBits N1Known = computeKnownBits(N1); 3587 if (N1Known.Zero.getBoolValue()) { 3588 KnownBits N0Known = computeKnownBits(N0); 3589 3590 bool overflow; 3591 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3592 if (!overflow) 3593 return OFK_Never; 3594 } 3595 3596 // mulhi + 1 never overflow 3597 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3598 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3599 return OFK_Never; 3600 3601 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3602 KnownBits N0Known = computeKnownBits(N0); 3603 3604 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3605 return OFK_Never; 3606 } 3607 3608 return OFK_Sometime; 3609 } 3610 3611 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3612 EVT OpVT = Val.getValueType(); 3613 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3614 3615 // Is the constant a known power of 2? 3616 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3617 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3618 3619 // A left-shift of a constant one will have exactly one bit set because 3620 // shifting the bit off the end is undefined. 3621 if (Val.getOpcode() == ISD::SHL) { 3622 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3623 if (C && C->getAPIntValue() == 1) 3624 return true; 3625 } 3626 3627 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3628 // one bit set. 3629 if (Val.getOpcode() == ISD::SRL) { 3630 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3631 if (C && C->getAPIntValue().isSignMask()) 3632 return true; 3633 } 3634 3635 // Are all operands of a build vector constant powers of two? 3636 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3637 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3638 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3639 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3640 return false; 3641 })) 3642 return true; 3643 3644 // More could be done here, though the above checks are enough 3645 // to handle some common cases. 3646 3647 // Fall back to computeKnownBits to catch other known cases. 3648 KnownBits Known = computeKnownBits(Val); 3649 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3650 } 3651 3652 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3653 EVT VT = Op.getValueType(); 3654 3655 // TODO: Assume we don't know anything for now. 3656 if (VT.isScalableVector()) 3657 return 1; 3658 3659 APInt DemandedElts = VT.isVector() 3660 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 3661 : APInt(1, 1); 3662 return ComputeNumSignBits(Op, DemandedElts, Depth); 3663 } 3664 3665 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3666 unsigned Depth) const { 3667 EVT VT = Op.getValueType(); 3668 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3669 unsigned VTBits = VT.getScalarSizeInBits(); 3670 unsigned NumElts = DemandedElts.getBitWidth(); 3671 unsigned Tmp, Tmp2; 3672 unsigned FirstAnswer = 1; 3673 3674 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3675 const APInt &Val = C->getAPIntValue(); 3676 return Val.getNumSignBits(); 3677 } 3678 3679 if (Depth >= MaxRecursionDepth) 3680 return 1; // Limit search depth. 3681 3682 if (!DemandedElts || VT.isScalableVector()) 3683 return 1; // No demanded elts, better to assume we don't know anything. 3684 3685 unsigned Opcode = Op.getOpcode(); 3686 switch (Opcode) { 3687 default: break; 3688 case ISD::AssertSext: 3689 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3690 return VTBits-Tmp+1; 3691 case ISD::AssertZext: 3692 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3693 return VTBits-Tmp; 3694 3695 case ISD::BUILD_VECTOR: 3696 Tmp = VTBits; 3697 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3698 if (!DemandedElts[i]) 3699 continue; 3700 3701 SDValue SrcOp = Op.getOperand(i); 3702 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3703 3704 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3705 if (SrcOp.getValueSizeInBits() != VTBits) { 3706 assert(SrcOp.getValueSizeInBits() > VTBits && 3707 "Expected BUILD_VECTOR implicit truncation"); 3708 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3709 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3710 } 3711 Tmp = std::min(Tmp, Tmp2); 3712 } 3713 return Tmp; 3714 3715 case ISD::VECTOR_SHUFFLE: { 3716 // Collect the minimum number of sign bits that are shared by every vector 3717 // element referenced by the shuffle. 3718 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3719 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3720 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3721 for (unsigned i = 0; i != NumElts; ++i) { 3722 int M = SVN->getMaskElt(i); 3723 if (!DemandedElts[i]) 3724 continue; 3725 // For UNDEF elements, we don't know anything about the common state of 3726 // the shuffle result. 3727 if (M < 0) 3728 return 1; 3729 if ((unsigned)M < NumElts) 3730 DemandedLHS.setBit((unsigned)M % NumElts); 3731 else 3732 DemandedRHS.setBit((unsigned)M % NumElts); 3733 } 3734 Tmp = std::numeric_limits<unsigned>::max(); 3735 if (!!DemandedLHS) 3736 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3737 if (!!DemandedRHS) { 3738 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3739 Tmp = std::min(Tmp, Tmp2); 3740 } 3741 // If we don't know anything, early out and try computeKnownBits fall-back. 3742 if (Tmp == 1) 3743 break; 3744 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3745 return Tmp; 3746 } 3747 3748 case ISD::BITCAST: { 3749 SDValue N0 = Op.getOperand(0); 3750 EVT SrcVT = N0.getValueType(); 3751 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3752 3753 // Ignore bitcasts from unsupported types.. 3754 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3755 break; 3756 3757 // Fast handling of 'identity' bitcasts. 3758 if (VTBits == SrcBits) 3759 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3760 3761 bool IsLE = getDataLayout().isLittleEndian(); 3762 3763 // Bitcast 'large element' scalar/vector to 'small element' vector. 3764 if ((SrcBits % VTBits) == 0) { 3765 assert(VT.isVector() && "Expected bitcast to vector"); 3766 3767 unsigned Scale = SrcBits / VTBits; 3768 APInt SrcDemandedElts(NumElts / Scale, 0); 3769 for (unsigned i = 0; i != NumElts; ++i) 3770 if (DemandedElts[i]) 3771 SrcDemandedElts.setBit(i / Scale); 3772 3773 // Fast case - sign splat can be simply split across the small elements. 3774 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3775 if (Tmp == SrcBits) 3776 return VTBits; 3777 3778 // Slow case - determine how far the sign extends into each sub-element. 3779 Tmp2 = VTBits; 3780 for (unsigned i = 0; i != NumElts; ++i) 3781 if (DemandedElts[i]) { 3782 unsigned SubOffset = i % Scale; 3783 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3784 SubOffset = SubOffset * VTBits; 3785 if (Tmp <= SubOffset) 3786 return 1; 3787 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3788 } 3789 return Tmp2; 3790 } 3791 break; 3792 } 3793 3794 case ISD::SIGN_EXTEND: 3795 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3796 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3797 case ISD::SIGN_EXTEND_INREG: 3798 // Max of the input and what this extends. 3799 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3800 Tmp = VTBits-Tmp+1; 3801 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3802 return std::max(Tmp, Tmp2); 3803 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3804 SDValue Src = Op.getOperand(0); 3805 EVT SrcVT = Src.getValueType(); 3806 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3807 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3808 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3809 } 3810 case ISD::SRA: 3811 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3812 // SRA X, C -> adds C sign bits. 3813 if (const APInt *ShAmt = 3814 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3815 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3816 return Tmp; 3817 case ISD::SHL: 3818 if (const APInt *ShAmt = 3819 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3820 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3821 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3822 if (ShAmt->ult(Tmp)) 3823 return Tmp - ShAmt->getZExtValue(); 3824 } 3825 break; 3826 case ISD::AND: 3827 case ISD::OR: 3828 case ISD::XOR: // NOT is handled here. 3829 // Logical binary ops preserve the number of sign bits at the worst. 3830 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3831 if (Tmp != 1) { 3832 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3833 FirstAnswer = std::min(Tmp, Tmp2); 3834 // We computed what we know about the sign bits as our first 3835 // answer. Now proceed to the generic code that uses 3836 // computeKnownBits, and pick whichever answer is better. 3837 } 3838 break; 3839 3840 case ISD::SELECT: 3841 case ISD::VSELECT: 3842 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3843 if (Tmp == 1) return 1; // Early out. 3844 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3845 return std::min(Tmp, Tmp2); 3846 case ISD::SELECT_CC: 3847 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3848 if (Tmp == 1) return 1; // Early out. 3849 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3850 return std::min(Tmp, Tmp2); 3851 3852 case ISD::SMIN: 3853 case ISD::SMAX: { 3854 // If we have a clamp pattern, we know that the number of sign bits will be 3855 // the minimum of the clamp min/max range. 3856 bool IsMax = (Opcode == ISD::SMAX); 3857 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3858 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3859 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3860 CstHigh = 3861 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3862 if (CstLow && CstHigh) { 3863 if (!IsMax) 3864 std::swap(CstLow, CstHigh); 3865 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3866 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3867 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3868 return std::min(Tmp, Tmp2); 3869 } 3870 } 3871 3872 // Fallback - just get the minimum number of sign bits of the operands. 3873 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3874 if (Tmp == 1) 3875 return 1; // Early out. 3876 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3877 return std::min(Tmp, Tmp2); 3878 } 3879 case ISD::UMIN: 3880 case ISD::UMAX: 3881 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3882 if (Tmp == 1) 3883 return 1; // Early out. 3884 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3885 return std::min(Tmp, Tmp2); 3886 case ISD::SADDO: 3887 case ISD::UADDO: 3888 case ISD::SSUBO: 3889 case ISD::USUBO: 3890 case ISD::SMULO: 3891 case ISD::UMULO: 3892 if (Op.getResNo() != 1) 3893 break; 3894 // The boolean result conforms to getBooleanContents. Fall through. 3895 // If setcc returns 0/-1, all bits are sign bits. 3896 // We know that we have an integer-based boolean since these operations 3897 // are only available for integer. 3898 if (TLI->getBooleanContents(VT.isVector(), false) == 3899 TargetLowering::ZeroOrNegativeOneBooleanContent) 3900 return VTBits; 3901 break; 3902 case ISD::SETCC: 3903 case ISD::STRICT_FSETCC: 3904 case ISD::STRICT_FSETCCS: { 3905 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3906 // If setcc returns 0/-1, all bits are sign bits. 3907 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3908 TargetLowering::ZeroOrNegativeOneBooleanContent) 3909 return VTBits; 3910 break; 3911 } 3912 case ISD::ROTL: 3913 case ISD::ROTR: 3914 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3915 3916 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 3917 if (Tmp == VTBits) 3918 return VTBits; 3919 3920 if (ConstantSDNode *C = 3921 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 3922 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 3923 3924 // Handle rotate right by N like a rotate left by 32-N. 3925 if (Opcode == ISD::ROTR) 3926 RotAmt = (VTBits - RotAmt) % VTBits; 3927 3928 // If we aren't rotating out all of the known-in sign bits, return the 3929 // number that are left. This handles rotl(sext(x), 1) for example. 3930 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 3931 } 3932 break; 3933 case ISD::ADD: 3934 case ISD::ADDC: 3935 // Add can have at most one carry bit. Thus we know that the output 3936 // is, at worst, one more bit than the inputs. 3937 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3938 if (Tmp == 1) return 1; // Early out. 3939 3940 // Special case decrementing a value (ADD X, -1): 3941 if (ConstantSDNode *CRHS = 3942 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 3943 if (CRHS->isAllOnesValue()) { 3944 KnownBits Known = 3945 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3946 3947 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3948 // sign bits set. 3949 if ((Known.Zero | 1).isAllOnesValue()) 3950 return VTBits; 3951 3952 // If we are subtracting one from a positive number, there is no carry 3953 // out of the result. 3954 if (Known.isNonNegative()) 3955 return Tmp; 3956 } 3957 3958 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3959 if (Tmp2 == 1) return 1; // Early out. 3960 return std::min(Tmp, Tmp2) - 1; 3961 case ISD::SUB: 3962 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3963 if (Tmp2 == 1) return 1; // Early out. 3964 3965 // Handle NEG. 3966 if (ConstantSDNode *CLHS = 3967 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 3968 if (CLHS->isNullValue()) { 3969 KnownBits Known = 3970 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3971 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3972 // sign bits set. 3973 if ((Known.Zero | 1).isAllOnesValue()) 3974 return VTBits; 3975 3976 // If the input is known to be positive (the sign bit is known clear), 3977 // the output of the NEG has the same number of sign bits as the input. 3978 if (Known.isNonNegative()) 3979 return Tmp2; 3980 3981 // Otherwise, we treat this like a SUB. 3982 } 3983 3984 // Sub can have at most one carry bit. Thus we know that the output 3985 // is, at worst, one more bit than the inputs. 3986 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3987 if (Tmp == 1) return 1; // Early out. 3988 return std::min(Tmp, Tmp2) - 1; 3989 case ISD::MUL: { 3990 // The output of the Mul can be at most twice the valid bits in the inputs. 3991 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3992 if (SignBitsOp0 == 1) 3993 break; 3994 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 3995 if (SignBitsOp1 == 1) 3996 break; 3997 unsigned OutValidBits = 3998 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 3999 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4000 } 4001 case ISD::SREM: 4002 // The sign bit is the LHS's sign bit, except when the result of the 4003 // remainder is zero. The magnitude of the result should be less than or 4004 // equal to the magnitude of the LHS. Therefore, the result should have 4005 // at least as many sign bits as the left hand side. 4006 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4007 case ISD::TRUNCATE: { 4008 // Check if the sign bits of source go down as far as the truncated value. 4009 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4010 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4011 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4012 return NumSrcSignBits - (NumSrcBits - VTBits); 4013 break; 4014 } 4015 case ISD::EXTRACT_ELEMENT: { 4016 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4017 const int BitWidth = Op.getValueSizeInBits(); 4018 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4019 4020 // Get reverse index (starting from 1), Op1 value indexes elements from 4021 // little end. Sign starts at big end. 4022 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4023 4024 // If the sign portion ends in our element the subtraction gives correct 4025 // result. Otherwise it gives either negative or > bitwidth result 4026 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4027 } 4028 case ISD::INSERT_VECTOR_ELT: { 4029 // If we know the element index, split the demand between the 4030 // source vector and the inserted element, otherwise assume we need 4031 // the original demanded vector elements and the value. 4032 SDValue InVec = Op.getOperand(0); 4033 SDValue InVal = Op.getOperand(1); 4034 SDValue EltNo = Op.getOperand(2); 4035 bool DemandedVal = true; 4036 APInt DemandedVecElts = DemandedElts; 4037 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4038 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4039 unsigned EltIdx = CEltNo->getZExtValue(); 4040 DemandedVal = !!DemandedElts[EltIdx]; 4041 DemandedVecElts.clearBit(EltIdx); 4042 } 4043 Tmp = std::numeric_limits<unsigned>::max(); 4044 if (DemandedVal) { 4045 // TODO - handle implicit truncation of inserted elements. 4046 if (InVal.getScalarValueSizeInBits() != VTBits) 4047 break; 4048 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4049 Tmp = std::min(Tmp, Tmp2); 4050 } 4051 if (!!DemandedVecElts) { 4052 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4053 Tmp = std::min(Tmp, Tmp2); 4054 } 4055 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4056 return Tmp; 4057 } 4058 case ISD::EXTRACT_VECTOR_ELT: { 4059 SDValue InVec = Op.getOperand(0); 4060 SDValue EltNo = Op.getOperand(1); 4061 EVT VecVT = InVec.getValueType(); 4062 // ComputeNumSignBits not yet implemented for scalable vectors. 4063 if (VecVT.isScalableVector()) 4064 break; 4065 const unsigned BitWidth = Op.getValueSizeInBits(); 4066 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4067 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4068 4069 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4070 // anything about sign bits. But if the sizes match we can derive knowledge 4071 // about sign bits from the vector operand. 4072 if (BitWidth != EltBitWidth) 4073 break; 4074 4075 // If we know the element index, just demand that vector element, else for 4076 // an unknown element index, ignore DemandedElts and demand them all. 4077 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 4078 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4079 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4080 DemandedSrcElts = 4081 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4082 4083 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4084 } 4085 case ISD::EXTRACT_SUBVECTOR: { 4086 // Offset the demanded elts by the subvector index. 4087 SDValue Src = Op.getOperand(0); 4088 // Bail until we can represent demanded elements for scalable vectors. 4089 if (Src.getValueType().isScalableVector()) 4090 break; 4091 uint64_t Idx = Op.getConstantOperandVal(1); 4092 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4093 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4094 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4095 } 4096 case ISD::CONCAT_VECTORS: { 4097 // Determine the minimum number of sign bits across all demanded 4098 // elts of the input vectors. Early out if the result is already 1. 4099 Tmp = std::numeric_limits<unsigned>::max(); 4100 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4101 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4102 unsigned NumSubVectors = Op.getNumOperands(); 4103 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4104 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); 4105 DemandedSub = DemandedSub.trunc(NumSubVectorElts); 4106 if (!DemandedSub) 4107 continue; 4108 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4109 Tmp = std::min(Tmp, Tmp2); 4110 } 4111 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4112 return Tmp; 4113 } 4114 case ISD::INSERT_SUBVECTOR: { 4115 // Demand any elements from the subvector and the remainder from the src its 4116 // inserted into. 4117 SDValue Src = Op.getOperand(0); 4118 SDValue Sub = Op.getOperand(1); 4119 uint64_t Idx = Op.getConstantOperandVal(2); 4120 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4121 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4122 APInt DemandedSrcElts = DemandedElts; 4123 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 4124 4125 Tmp = std::numeric_limits<unsigned>::max(); 4126 if (!!DemandedSubElts) { 4127 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4128 if (Tmp == 1) 4129 return 1; // early-out 4130 } 4131 if (!!DemandedSrcElts) { 4132 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4133 Tmp = std::min(Tmp, Tmp2); 4134 } 4135 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4136 return Tmp; 4137 } 4138 case ISD::ATOMIC_CMP_SWAP: 4139 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4140 case ISD::ATOMIC_SWAP: 4141 case ISD::ATOMIC_LOAD_ADD: 4142 case ISD::ATOMIC_LOAD_SUB: 4143 case ISD::ATOMIC_LOAD_AND: 4144 case ISD::ATOMIC_LOAD_CLR: 4145 case ISD::ATOMIC_LOAD_OR: 4146 case ISD::ATOMIC_LOAD_XOR: 4147 case ISD::ATOMIC_LOAD_NAND: 4148 case ISD::ATOMIC_LOAD_MIN: 4149 case ISD::ATOMIC_LOAD_MAX: 4150 case ISD::ATOMIC_LOAD_UMIN: 4151 case ISD::ATOMIC_LOAD_UMAX: 4152 case ISD::ATOMIC_LOAD: { 4153 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4154 // If we are looking at the loaded value. 4155 if (Op.getResNo() == 0) { 4156 if (Tmp == VTBits) 4157 return 1; // early-out 4158 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4159 return VTBits - Tmp + 1; 4160 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4161 return VTBits - Tmp; 4162 } 4163 break; 4164 } 4165 } 4166 4167 // If we are looking at the loaded value of the SDNode. 4168 if (Op.getResNo() == 0) { 4169 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4170 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4171 unsigned ExtType = LD->getExtensionType(); 4172 switch (ExtType) { 4173 default: break; 4174 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4175 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4176 return VTBits - Tmp + 1; 4177 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4178 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4179 return VTBits - Tmp; 4180 case ISD::NON_EXTLOAD: 4181 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4182 // We only need to handle vectors - computeKnownBits should handle 4183 // scalar cases. 4184 Type *CstTy = Cst->getType(); 4185 if (CstTy->isVectorTy() && 4186 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) { 4187 Tmp = VTBits; 4188 for (unsigned i = 0; i != NumElts; ++i) { 4189 if (!DemandedElts[i]) 4190 continue; 4191 if (Constant *Elt = Cst->getAggregateElement(i)) { 4192 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4193 const APInt &Value = CInt->getValue(); 4194 Tmp = std::min(Tmp, Value.getNumSignBits()); 4195 continue; 4196 } 4197 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4198 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4199 Tmp = std::min(Tmp, Value.getNumSignBits()); 4200 continue; 4201 } 4202 } 4203 // Unknown type. Conservatively assume no bits match sign bit. 4204 return 1; 4205 } 4206 return Tmp; 4207 } 4208 } 4209 break; 4210 } 4211 } 4212 } 4213 4214 // Allow the target to implement this method for its nodes. 4215 if (Opcode >= ISD::BUILTIN_OP_END || 4216 Opcode == ISD::INTRINSIC_WO_CHAIN || 4217 Opcode == ISD::INTRINSIC_W_CHAIN || 4218 Opcode == ISD::INTRINSIC_VOID) { 4219 unsigned NumBits = 4220 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4221 if (NumBits > 1) 4222 FirstAnswer = std::max(FirstAnswer, NumBits); 4223 } 4224 4225 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4226 // use this information. 4227 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4228 4229 APInt Mask; 4230 if (Known.isNonNegative()) { // sign bit is 0 4231 Mask = Known.Zero; 4232 } else if (Known.isNegative()) { // sign bit is 1; 4233 Mask = Known.One; 4234 } else { 4235 // Nothing known. 4236 return FirstAnswer; 4237 } 4238 4239 // Okay, we know that the sign bit in Mask is set. Use CLO to determine 4240 // the number of identical bits in the top of the input value. 4241 Mask <<= Mask.getBitWidth()-VTBits; 4242 return std::max(FirstAnswer, Mask.countLeadingOnes()); 4243 } 4244 4245 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4246 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4247 !isa<ConstantSDNode>(Op.getOperand(1))) 4248 return false; 4249 4250 if (Op.getOpcode() == ISD::OR && 4251 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4252 return false; 4253 4254 return true; 4255 } 4256 4257 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4258 // If we're told that NaNs won't happen, assume they won't. 4259 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4260 return true; 4261 4262 if (Depth >= MaxRecursionDepth) 4263 return false; // Limit search depth. 4264 4265 // TODO: Handle vectors. 4266 // If the value is a constant, we can obviously see if it is a NaN or not. 4267 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4268 return !C->getValueAPF().isNaN() || 4269 (SNaN && !C->getValueAPF().isSignaling()); 4270 } 4271 4272 unsigned Opcode = Op.getOpcode(); 4273 switch (Opcode) { 4274 case ISD::FADD: 4275 case ISD::FSUB: 4276 case ISD::FMUL: 4277 case ISD::FDIV: 4278 case ISD::FREM: 4279 case ISD::FSIN: 4280 case ISD::FCOS: { 4281 if (SNaN) 4282 return true; 4283 // TODO: Need isKnownNeverInfinity 4284 return false; 4285 } 4286 case ISD::FCANONICALIZE: 4287 case ISD::FEXP: 4288 case ISD::FEXP2: 4289 case ISD::FTRUNC: 4290 case ISD::FFLOOR: 4291 case ISD::FCEIL: 4292 case ISD::FROUND: 4293 case ISD::FROUNDEVEN: 4294 case ISD::FRINT: 4295 case ISD::FNEARBYINT: { 4296 if (SNaN) 4297 return true; 4298 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4299 } 4300 case ISD::FABS: 4301 case ISD::FNEG: 4302 case ISD::FCOPYSIGN: { 4303 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4304 } 4305 case ISD::SELECT: 4306 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4307 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4308 case ISD::FP_EXTEND: 4309 case ISD::FP_ROUND: { 4310 if (SNaN) 4311 return true; 4312 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4313 } 4314 case ISD::SINT_TO_FP: 4315 case ISD::UINT_TO_FP: 4316 return true; 4317 case ISD::FMA: 4318 case ISD::FMAD: { 4319 if (SNaN) 4320 return true; 4321 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4322 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4323 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4324 } 4325 case ISD::FSQRT: // Need is known positive 4326 case ISD::FLOG: 4327 case ISD::FLOG2: 4328 case ISD::FLOG10: 4329 case ISD::FPOWI: 4330 case ISD::FPOW: { 4331 if (SNaN) 4332 return true; 4333 // TODO: Refine on operand 4334 return false; 4335 } 4336 case ISD::FMINNUM: 4337 case ISD::FMAXNUM: { 4338 // Only one needs to be known not-nan, since it will be returned if the 4339 // other ends up being one. 4340 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4341 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4342 } 4343 case ISD::FMINNUM_IEEE: 4344 case ISD::FMAXNUM_IEEE: { 4345 if (SNaN) 4346 return true; 4347 // This can return a NaN if either operand is an sNaN, or if both operands 4348 // are NaN. 4349 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4350 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4351 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4352 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4353 } 4354 case ISD::FMINIMUM: 4355 case ISD::FMAXIMUM: { 4356 // TODO: Does this quiet or return the origina NaN as-is? 4357 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4358 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4359 } 4360 case ISD::EXTRACT_VECTOR_ELT: { 4361 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4362 } 4363 default: 4364 if (Opcode >= ISD::BUILTIN_OP_END || 4365 Opcode == ISD::INTRINSIC_WO_CHAIN || 4366 Opcode == ISD::INTRINSIC_W_CHAIN || 4367 Opcode == ISD::INTRINSIC_VOID) { 4368 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4369 } 4370 4371 return false; 4372 } 4373 } 4374 4375 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4376 assert(Op.getValueType().isFloatingPoint() && 4377 "Floating point type expected"); 4378 4379 // If the value is a constant, we can obviously see if it is a zero or not. 4380 // TODO: Add BuildVector support. 4381 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4382 return !C->isZero(); 4383 return false; 4384 } 4385 4386 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4387 assert(!Op.getValueType().isFloatingPoint() && 4388 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4389 4390 // If the value is a constant, we can obviously see if it is a zero or not. 4391 if (ISD::matchUnaryPredicate( 4392 Op, [](ConstantSDNode *C) { return !C->isNullValue(); })) 4393 return true; 4394 4395 // TODO: Recognize more cases here. 4396 switch (Op.getOpcode()) { 4397 default: break; 4398 case ISD::OR: 4399 if (isKnownNeverZero(Op.getOperand(1)) || 4400 isKnownNeverZero(Op.getOperand(0))) 4401 return true; 4402 break; 4403 } 4404 4405 return false; 4406 } 4407 4408 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4409 // Check the obvious case. 4410 if (A == B) return true; 4411 4412 // For for negative and positive zero. 4413 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4414 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4415 if (CA->isZero() && CB->isZero()) return true; 4416 4417 // Otherwise they may not be equal. 4418 return false; 4419 } 4420 4421 // FIXME: unify with llvm::haveNoCommonBitsSet. 4422 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M) 4423 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4424 assert(A.getValueType() == B.getValueType() && 4425 "Values must have the same type"); 4426 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4427 computeKnownBits(B)); 4428 } 4429 4430 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4431 SelectionDAG &DAG) { 4432 if (cast<ConstantSDNode>(Step)->isNullValue()) 4433 return DAG.getConstant(0, DL, VT); 4434 4435 return SDValue(); 4436 } 4437 4438 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4439 ArrayRef<SDValue> Ops, 4440 SelectionDAG &DAG) { 4441 int NumOps = Ops.size(); 4442 assert(NumOps != 0 && "Can't build an empty vector!"); 4443 assert(!VT.isScalableVector() && 4444 "BUILD_VECTOR cannot be used with scalable types"); 4445 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4446 "Incorrect element count in BUILD_VECTOR!"); 4447 4448 // BUILD_VECTOR of UNDEFs is UNDEF. 4449 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4450 return DAG.getUNDEF(VT); 4451 4452 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4453 SDValue IdentitySrc; 4454 bool IsIdentity = true; 4455 for (int i = 0; i != NumOps; ++i) { 4456 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4457 Ops[i].getOperand(0).getValueType() != VT || 4458 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4459 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4460 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4461 IsIdentity = false; 4462 break; 4463 } 4464 IdentitySrc = Ops[i].getOperand(0); 4465 } 4466 if (IsIdentity) 4467 return IdentitySrc; 4468 4469 return SDValue(); 4470 } 4471 4472 /// Try to simplify vector concatenation to an input value, undef, or build 4473 /// vector. 4474 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4475 ArrayRef<SDValue> Ops, 4476 SelectionDAG &DAG) { 4477 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4478 assert(llvm::all_of(Ops, 4479 [Ops](SDValue Op) { 4480 return Ops[0].getValueType() == Op.getValueType(); 4481 }) && 4482 "Concatenation of vectors with inconsistent value types!"); 4483 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4484 VT.getVectorElementCount() && 4485 "Incorrect element count in vector concatenation!"); 4486 4487 if (Ops.size() == 1) 4488 return Ops[0]; 4489 4490 // Concat of UNDEFs is UNDEF. 4491 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4492 return DAG.getUNDEF(VT); 4493 4494 // Scan the operands and look for extract operations from a single source 4495 // that correspond to insertion at the same location via this concatenation: 4496 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4497 SDValue IdentitySrc; 4498 bool IsIdentity = true; 4499 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4500 SDValue Op = Ops[i]; 4501 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4502 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4503 Op.getOperand(0).getValueType() != VT || 4504 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4505 Op.getConstantOperandVal(1) != IdentityIndex) { 4506 IsIdentity = false; 4507 break; 4508 } 4509 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4510 "Unexpected identity source vector for concat of extracts"); 4511 IdentitySrc = Op.getOperand(0); 4512 } 4513 if (IsIdentity) { 4514 assert(IdentitySrc && "Failed to set source vector of extracts"); 4515 return IdentitySrc; 4516 } 4517 4518 // The code below this point is only designed to work for fixed width 4519 // vectors, so we bail out for now. 4520 if (VT.isScalableVector()) 4521 return SDValue(); 4522 4523 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4524 // simplified to one big BUILD_VECTOR. 4525 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4526 EVT SVT = VT.getScalarType(); 4527 SmallVector<SDValue, 16> Elts; 4528 for (SDValue Op : Ops) { 4529 EVT OpVT = Op.getValueType(); 4530 if (Op.isUndef()) 4531 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4532 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4533 Elts.append(Op->op_begin(), Op->op_end()); 4534 else 4535 return SDValue(); 4536 } 4537 4538 // BUILD_VECTOR requires all inputs to be of the same type, find the 4539 // maximum type and extend them all. 4540 for (SDValue Op : Elts) 4541 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4542 4543 if (SVT.bitsGT(VT.getScalarType())) { 4544 for (SDValue &Op : Elts) { 4545 if (Op.isUndef()) 4546 Op = DAG.getUNDEF(SVT); 4547 else 4548 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4549 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4550 : DAG.getSExtOrTrunc(Op, DL, SVT); 4551 } 4552 } 4553 4554 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4555 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4556 return V; 4557 } 4558 4559 /// Gets or creates the specified node. 4560 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4561 FoldingSetNodeID ID; 4562 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4563 void *IP = nullptr; 4564 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4565 return SDValue(E, 0); 4566 4567 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4568 getVTList(VT)); 4569 CSEMap.InsertNode(N, IP); 4570 4571 InsertNode(N); 4572 SDValue V = SDValue(N, 0); 4573 NewSDValueDbgMsg(V, "Creating new node: ", this); 4574 return V; 4575 } 4576 4577 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4578 SDValue Operand) { 4579 SDNodeFlags Flags; 4580 if (Inserter) 4581 Flags = Inserter->getFlags(); 4582 return getNode(Opcode, DL, VT, Operand, Flags); 4583 } 4584 4585 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4586 SDValue Operand, const SDNodeFlags Flags) { 4587 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4588 "Operand is DELETED_NODE!"); 4589 // Constant fold unary operations with an integer constant operand. Even 4590 // opaque constant will be folded, because the folding of unary operations 4591 // doesn't create new constants with different values. Nevertheless, the 4592 // opaque flag is preserved during folding to prevent future folding with 4593 // other constants. 4594 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4595 const APInt &Val = C->getAPIntValue(); 4596 switch (Opcode) { 4597 default: break; 4598 case ISD::SIGN_EXTEND: 4599 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4600 C->isTargetOpcode(), C->isOpaque()); 4601 case ISD::TRUNCATE: 4602 if (C->isOpaque()) 4603 break; 4604 LLVM_FALLTHROUGH; 4605 case ISD::ANY_EXTEND: 4606 case ISD::ZERO_EXTEND: 4607 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4608 C->isTargetOpcode(), C->isOpaque()); 4609 case ISD::UINT_TO_FP: 4610 case ISD::SINT_TO_FP: { 4611 APFloat apf(EVTToAPFloatSemantics(VT), 4612 APInt::getNullValue(VT.getSizeInBits())); 4613 (void)apf.convertFromAPInt(Val, 4614 Opcode==ISD::SINT_TO_FP, 4615 APFloat::rmNearestTiesToEven); 4616 return getConstantFP(apf, DL, VT); 4617 } 4618 case ISD::BITCAST: 4619 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4620 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4621 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4622 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4623 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4624 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4625 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4626 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4627 break; 4628 case ISD::ABS: 4629 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4630 C->isOpaque()); 4631 case ISD::BITREVERSE: 4632 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4633 C->isOpaque()); 4634 case ISD::BSWAP: 4635 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4636 C->isOpaque()); 4637 case ISD::CTPOP: 4638 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4639 C->isOpaque()); 4640 case ISD::CTLZ: 4641 case ISD::CTLZ_ZERO_UNDEF: 4642 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4643 C->isOpaque()); 4644 case ISD::CTTZ: 4645 case ISD::CTTZ_ZERO_UNDEF: 4646 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4647 C->isOpaque()); 4648 case ISD::FP16_TO_FP: { 4649 bool Ignored; 4650 APFloat FPV(APFloat::IEEEhalf(), 4651 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4652 4653 // This can return overflow, underflow, or inexact; we don't care. 4654 // FIXME need to be more flexible about rounding mode. 4655 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4656 APFloat::rmNearestTiesToEven, &Ignored); 4657 return getConstantFP(FPV, DL, VT); 4658 } 4659 case ISD::STEP_VECTOR: { 4660 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4661 return V; 4662 break; 4663 } 4664 } 4665 } 4666 4667 // Constant fold unary operations with a floating point constant operand. 4668 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4669 APFloat V = C->getValueAPF(); // make copy 4670 switch (Opcode) { 4671 case ISD::FNEG: 4672 V.changeSign(); 4673 return getConstantFP(V, DL, VT); 4674 case ISD::FABS: 4675 V.clearSign(); 4676 return getConstantFP(V, DL, VT); 4677 case ISD::FCEIL: { 4678 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4679 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4680 return getConstantFP(V, DL, VT); 4681 break; 4682 } 4683 case ISD::FTRUNC: { 4684 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4685 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4686 return getConstantFP(V, DL, VT); 4687 break; 4688 } 4689 case ISD::FFLOOR: { 4690 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4691 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4692 return getConstantFP(V, DL, VT); 4693 break; 4694 } 4695 case ISD::FP_EXTEND: { 4696 bool ignored; 4697 // This can return overflow, underflow, or inexact; we don't care. 4698 // FIXME need to be more flexible about rounding mode. 4699 (void)V.convert(EVTToAPFloatSemantics(VT), 4700 APFloat::rmNearestTiesToEven, &ignored); 4701 return getConstantFP(V, DL, VT); 4702 } 4703 case ISD::FP_TO_SINT: 4704 case ISD::FP_TO_UINT: { 4705 bool ignored; 4706 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4707 // FIXME need to be more flexible about rounding mode. 4708 APFloat::opStatus s = 4709 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4710 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4711 break; 4712 return getConstant(IntVal, DL, VT); 4713 } 4714 case ISD::BITCAST: 4715 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4716 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4717 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4718 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4719 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4720 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4721 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4722 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4723 break; 4724 case ISD::FP_TO_FP16: { 4725 bool Ignored; 4726 // This can return overflow, underflow, or inexact; we don't care. 4727 // FIXME need to be more flexible about rounding mode. 4728 (void)V.convert(APFloat::IEEEhalf(), 4729 APFloat::rmNearestTiesToEven, &Ignored); 4730 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4731 } 4732 } 4733 } 4734 4735 // Constant fold unary operations with a vector integer or float operand. 4736 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) { 4737 if (BV->isConstant()) { 4738 switch (Opcode) { 4739 default: 4740 // FIXME: Entirely reasonable to perform folding of other unary 4741 // operations here as the need arises. 4742 break; 4743 case ISD::FNEG: 4744 case ISD::FABS: 4745 case ISD::FCEIL: 4746 case ISD::FTRUNC: 4747 case ISD::FFLOOR: 4748 case ISD::FP_EXTEND: 4749 case ISD::FP_TO_SINT: 4750 case ISD::FP_TO_UINT: 4751 case ISD::TRUNCATE: 4752 case ISD::ANY_EXTEND: 4753 case ISD::ZERO_EXTEND: 4754 case ISD::SIGN_EXTEND: 4755 case ISD::UINT_TO_FP: 4756 case ISD::SINT_TO_FP: 4757 case ISD::ABS: 4758 case ISD::BITREVERSE: 4759 case ISD::BSWAP: 4760 case ISD::CTLZ: 4761 case ISD::CTLZ_ZERO_UNDEF: 4762 case ISD::CTTZ: 4763 case ISD::CTTZ_ZERO_UNDEF: 4764 case ISD::CTPOP: { 4765 SDValue Ops = { Operand }; 4766 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 4767 return Fold; 4768 } 4769 } 4770 } 4771 } 4772 4773 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4774 switch (Opcode) { 4775 case ISD::STEP_VECTOR: 4776 assert(VT.isScalableVector() && 4777 "STEP_VECTOR can only be used with scalable types"); 4778 assert(VT.getScalarSizeInBits() >= 8 && 4779 "STEP_VECTOR can only be used with vectors of integers that are at " 4780 "least 8 bits wide"); 4781 assert(isa<ConstantSDNode>(Operand) && 4782 cast<ConstantSDNode>(Operand)->getAPIntValue().isSignedIntN( 4783 VT.getScalarSizeInBits()) && 4784 "Expected STEP_VECTOR integer constant to fit in " 4785 "the vector element type"); 4786 break; 4787 case ISD::FREEZE: 4788 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4789 break; 4790 case ISD::TokenFactor: 4791 case ISD::MERGE_VALUES: 4792 case ISD::CONCAT_VECTORS: 4793 return Operand; // Factor, merge or concat of one node? No need. 4794 case ISD::BUILD_VECTOR: { 4795 // Attempt to simplify BUILD_VECTOR. 4796 SDValue Ops[] = {Operand}; 4797 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4798 return V; 4799 break; 4800 } 4801 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4802 case ISD::FP_EXTEND: 4803 assert(VT.isFloatingPoint() && 4804 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4805 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4806 assert((!VT.isVector() || 4807 VT.getVectorElementCount() == 4808 Operand.getValueType().getVectorElementCount()) && 4809 "Vector element count mismatch!"); 4810 assert(Operand.getValueType().bitsLT(VT) && 4811 "Invalid fpext node, dst < src!"); 4812 if (Operand.isUndef()) 4813 return getUNDEF(VT); 4814 break; 4815 case ISD::FP_TO_SINT: 4816 case ISD::FP_TO_UINT: 4817 if (Operand.isUndef()) 4818 return getUNDEF(VT); 4819 break; 4820 case ISD::SINT_TO_FP: 4821 case ISD::UINT_TO_FP: 4822 // [us]itofp(undef) = 0, because the result value is bounded. 4823 if (Operand.isUndef()) 4824 return getConstantFP(0.0, DL, VT); 4825 break; 4826 case ISD::SIGN_EXTEND: 4827 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4828 "Invalid SIGN_EXTEND!"); 4829 assert(VT.isVector() == Operand.getValueType().isVector() && 4830 "SIGN_EXTEND result type type should be vector iff the operand " 4831 "type is vector!"); 4832 if (Operand.getValueType() == VT) return Operand; // noop extension 4833 assert((!VT.isVector() || 4834 VT.getVectorElementCount() == 4835 Operand.getValueType().getVectorElementCount()) && 4836 "Vector element count mismatch!"); 4837 assert(Operand.getValueType().bitsLT(VT) && 4838 "Invalid sext node, dst < src!"); 4839 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 4840 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4841 if (OpOpcode == ISD::UNDEF) 4842 // sext(undef) = 0, because the top bits will all be the same. 4843 return getConstant(0, DL, VT); 4844 break; 4845 case ISD::ZERO_EXTEND: 4846 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4847 "Invalid ZERO_EXTEND!"); 4848 assert(VT.isVector() == Operand.getValueType().isVector() && 4849 "ZERO_EXTEND result type type should be vector iff the operand " 4850 "type is vector!"); 4851 if (Operand.getValueType() == VT) return Operand; // noop extension 4852 assert((!VT.isVector() || 4853 VT.getVectorElementCount() == 4854 Operand.getValueType().getVectorElementCount()) && 4855 "Vector element count mismatch!"); 4856 assert(Operand.getValueType().bitsLT(VT) && 4857 "Invalid zext node, dst < src!"); 4858 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 4859 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 4860 if (OpOpcode == ISD::UNDEF) 4861 // zext(undef) = 0, because the top bits will be zero. 4862 return getConstant(0, DL, VT); 4863 break; 4864 case ISD::ANY_EXTEND: 4865 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4866 "Invalid ANY_EXTEND!"); 4867 assert(VT.isVector() == Operand.getValueType().isVector() && 4868 "ANY_EXTEND result type type should be vector iff the operand " 4869 "type is vector!"); 4870 if (Operand.getValueType() == VT) return Operand; // noop extension 4871 assert((!VT.isVector() || 4872 VT.getVectorElementCount() == 4873 Operand.getValueType().getVectorElementCount()) && 4874 "Vector element count mismatch!"); 4875 assert(Operand.getValueType().bitsLT(VT) && 4876 "Invalid anyext node, dst < src!"); 4877 4878 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4879 OpOpcode == ISD::ANY_EXTEND) 4880 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 4881 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4882 if (OpOpcode == ISD::UNDEF) 4883 return getUNDEF(VT); 4884 4885 // (ext (trunc x)) -> x 4886 if (OpOpcode == ISD::TRUNCATE) { 4887 SDValue OpOp = Operand.getOperand(0); 4888 if (OpOp.getValueType() == VT) { 4889 transferDbgValues(Operand, OpOp); 4890 return OpOp; 4891 } 4892 } 4893 break; 4894 case ISD::TRUNCATE: 4895 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4896 "Invalid TRUNCATE!"); 4897 assert(VT.isVector() == Operand.getValueType().isVector() && 4898 "TRUNCATE result type type should be vector iff the operand " 4899 "type is vector!"); 4900 if (Operand.getValueType() == VT) return Operand; // noop truncate 4901 assert((!VT.isVector() || 4902 VT.getVectorElementCount() == 4903 Operand.getValueType().getVectorElementCount()) && 4904 "Vector element count mismatch!"); 4905 assert(Operand.getValueType().bitsGT(VT) && 4906 "Invalid truncate node, src < dst!"); 4907 if (OpOpcode == ISD::TRUNCATE) 4908 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4909 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4910 OpOpcode == ISD::ANY_EXTEND) { 4911 // If the source is smaller than the dest, we still need an extend. 4912 if (Operand.getOperand(0).getValueType().getScalarType() 4913 .bitsLT(VT.getScalarType())) 4914 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4915 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 4916 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4917 return Operand.getOperand(0); 4918 } 4919 if (OpOpcode == ISD::UNDEF) 4920 return getUNDEF(VT); 4921 break; 4922 case ISD::ANY_EXTEND_VECTOR_INREG: 4923 case ISD::ZERO_EXTEND_VECTOR_INREG: 4924 case ISD::SIGN_EXTEND_VECTOR_INREG: 4925 assert(VT.isVector() && "This DAG node is restricted to vector types."); 4926 assert(Operand.getValueType().bitsLE(VT) && 4927 "The input must be the same size or smaller than the result."); 4928 assert(VT.getVectorMinNumElements() < 4929 Operand.getValueType().getVectorMinNumElements() && 4930 "The destination vector type must have fewer lanes than the input."); 4931 break; 4932 case ISD::ABS: 4933 assert(VT.isInteger() && VT == Operand.getValueType() && 4934 "Invalid ABS!"); 4935 if (OpOpcode == ISD::UNDEF) 4936 return getUNDEF(VT); 4937 break; 4938 case ISD::BSWAP: 4939 assert(VT.isInteger() && VT == Operand.getValueType() && 4940 "Invalid BSWAP!"); 4941 assert((VT.getScalarSizeInBits() % 16 == 0) && 4942 "BSWAP types must be a multiple of 16 bits!"); 4943 if (OpOpcode == ISD::UNDEF) 4944 return getUNDEF(VT); 4945 break; 4946 case ISD::BITREVERSE: 4947 assert(VT.isInteger() && VT == Operand.getValueType() && 4948 "Invalid BITREVERSE!"); 4949 if (OpOpcode == ISD::UNDEF) 4950 return getUNDEF(VT); 4951 break; 4952 case ISD::BITCAST: 4953 // Basic sanity checking. 4954 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 4955 "Cannot BITCAST between types of different sizes!"); 4956 if (VT == Operand.getValueType()) return Operand; // noop conversion. 4957 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 4958 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 4959 if (OpOpcode == ISD::UNDEF) 4960 return getUNDEF(VT); 4961 break; 4962 case ISD::SCALAR_TO_VECTOR: 4963 assert(VT.isVector() && !Operand.getValueType().isVector() && 4964 (VT.getVectorElementType() == Operand.getValueType() || 4965 (VT.getVectorElementType().isInteger() && 4966 Operand.getValueType().isInteger() && 4967 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 4968 "Illegal SCALAR_TO_VECTOR node!"); 4969 if (OpOpcode == ISD::UNDEF) 4970 return getUNDEF(VT); 4971 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 4972 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 4973 isa<ConstantSDNode>(Operand.getOperand(1)) && 4974 Operand.getConstantOperandVal(1) == 0 && 4975 Operand.getOperand(0).getValueType() == VT) 4976 return Operand.getOperand(0); 4977 break; 4978 case ISD::FNEG: 4979 // Negation of an unknown bag of bits is still completely undefined. 4980 if (OpOpcode == ISD::UNDEF) 4981 return getUNDEF(VT); 4982 4983 if (OpOpcode == ISD::FNEG) // --X -> X 4984 return Operand.getOperand(0); 4985 break; 4986 case ISD::FABS: 4987 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 4988 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 4989 break; 4990 case ISD::VSCALE: 4991 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4992 break; 4993 case ISD::CTPOP: 4994 if (Operand.getValueType().getScalarType() == MVT::i1) 4995 return Operand; 4996 break; 4997 case ISD::CTLZ: 4998 case ISD::CTTZ: 4999 if (Operand.getValueType().getScalarType() == MVT::i1) 5000 return getNOT(DL, Operand, Operand.getValueType()); 5001 break; 5002 case ISD::VECREDUCE_SMIN: 5003 case ISD::VECREDUCE_UMAX: 5004 if (Operand.getValueType().getScalarType() == MVT::i1) 5005 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5006 break; 5007 case ISD::VECREDUCE_SMAX: 5008 case ISD::VECREDUCE_UMIN: 5009 if (Operand.getValueType().getScalarType() == MVT::i1) 5010 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5011 break; 5012 } 5013 5014 SDNode *N; 5015 SDVTList VTs = getVTList(VT); 5016 SDValue Ops[] = {Operand}; 5017 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5018 FoldingSetNodeID ID; 5019 AddNodeIDNode(ID, Opcode, VTs, Ops); 5020 void *IP = nullptr; 5021 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5022 E->intersectFlagsWith(Flags); 5023 return SDValue(E, 0); 5024 } 5025 5026 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5027 N->setFlags(Flags); 5028 createOperands(N, Ops); 5029 CSEMap.InsertNode(N, IP); 5030 } else { 5031 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5032 createOperands(N, Ops); 5033 } 5034 5035 InsertNode(N); 5036 SDValue V = SDValue(N, 0); 5037 NewSDValueDbgMsg(V, "Creating new node: ", this); 5038 return V; 5039 } 5040 5041 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5042 const APInt &C2) { 5043 switch (Opcode) { 5044 case ISD::ADD: return C1 + C2; 5045 case ISD::SUB: return C1 - C2; 5046 case ISD::MUL: return C1 * C2; 5047 case ISD::AND: return C1 & C2; 5048 case ISD::OR: return C1 | C2; 5049 case ISD::XOR: return C1 ^ C2; 5050 case ISD::SHL: return C1 << C2; 5051 case ISD::SRL: return C1.lshr(C2); 5052 case ISD::SRA: return C1.ashr(C2); 5053 case ISD::ROTL: return C1.rotl(C2); 5054 case ISD::ROTR: return C1.rotr(C2); 5055 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5056 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5057 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5058 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5059 case ISD::SADDSAT: return C1.sadd_sat(C2); 5060 case ISD::UADDSAT: return C1.uadd_sat(C2); 5061 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5062 case ISD::USUBSAT: return C1.usub_sat(C2); 5063 case ISD::UDIV: 5064 if (!C2.getBoolValue()) 5065 break; 5066 return C1.udiv(C2); 5067 case ISD::UREM: 5068 if (!C2.getBoolValue()) 5069 break; 5070 return C1.urem(C2); 5071 case ISD::SDIV: 5072 if (!C2.getBoolValue()) 5073 break; 5074 return C1.sdiv(C2); 5075 case ISD::SREM: 5076 if (!C2.getBoolValue()) 5077 break; 5078 return C1.srem(C2); 5079 } 5080 return llvm::None; 5081 } 5082 5083 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5084 const GlobalAddressSDNode *GA, 5085 const SDNode *N2) { 5086 if (GA->getOpcode() != ISD::GlobalAddress) 5087 return SDValue(); 5088 if (!TLI->isOffsetFoldingLegal(GA)) 5089 return SDValue(); 5090 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5091 if (!C2) 5092 return SDValue(); 5093 int64_t Offset = C2->getSExtValue(); 5094 switch (Opcode) { 5095 case ISD::ADD: break; 5096 case ISD::SUB: Offset = -uint64_t(Offset); break; 5097 default: return SDValue(); 5098 } 5099 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5100 GA->getOffset() + uint64_t(Offset)); 5101 } 5102 5103 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5104 switch (Opcode) { 5105 case ISD::SDIV: 5106 case ISD::UDIV: 5107 case ISD::SREM: 5108 case ISD::UREM: { 5109 // If a divisor is zero/undef or any element of a divisor vector is 5110 // zero/undef, the whole op is undef. 5111 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5112 SDValue Divisor = Ops[1]; 5113 if (Divisor.isUndef() || isNullConstant(Divisor)) 5114 return true; 5115 5116 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5117 llvm::any_of(Divisor->op_values(), 5118 [](SDValue V) { return V.isUndef() || 5119 isNullConstant(V); }); 5120 // TODO: Handle signed overflow. 5121 } 5122 // TODO: Handle oversized shifts. 5123 default: 5124 return false; 5125 } 5126 } 5127 5128 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5129 EVT VT, ArrayRef<SDValue> Ops) { 5130 // If the opcode is a target-specific ISD node, there's nothing we can 5131 // do here and the operand rules may not line up with the below, so 5132 // bail early. 5133 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5134 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5135 // foldCONCAT_VECTORS in getNode before this is called. 5136 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5137 return SDValue(); 5138 5139 // For now, the array Ops should only contain two values. 5140 // This enforcement will be removed once this function is merged with 5141 // FoldConstantVectorArithmetic 5142 if (Ops.size() != 2) 5143 return SDValue(); 5144 5145 if (isUndef(Opcode, Ops)) 5146 return getUNDEF(VT); 5147 5148 SDNode *N1 = Ops[0].getNode(); 5149 SDNode *N2 = Ops[1].getNode(); 5150 5151 // Handle the case of two scalars. 5152 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) { 5153 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) { 5154 if (C1->isOpaque() || C2->isOpaque()) 5155 return SDValue(); 5156 5157 Optional<APInt> FoldAttempt = 5158 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5159 if (!FoldAttempt) 5160 return SDValue(); 5161 5162 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5163 assert((!Folded || !VT.isVector()) && 5164 "Can't fold vectors ops with scalar operands"); 5165 return Folded; 5166 } 5167 } 5168 5169 // fold (add Sym, c) -> Sym+c 5170 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1)) 5171 return FoldSymbolOffset(Opcode, VT, GA, N2); 5172 if (TLI->isCommutativeBinOp(Opcode)) 5173 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2)) 5174 return FoldSymbolOffset(Opcode, VT, GA, N1); 5175 5176 // For fixed width vectors, extract each constant element and fold them 5177 // individually. Either input may be an undef value. 5178 bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR || 5179 N1->getOpcode() == ISD::SPLAT_VECTOR; 5180 if (!IsBVOrSV1 && !N1->isUndef()) 5181 return SDValue(); 5182 bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR || 5183 N2->getOpcode() == ISD::SPLAT_VECTOR; 5184 if (!IsBVOrSV2 && !N2->isUndef()) 5185 return SDValue(); 5186 // If both operands are undef, that's handled the same way as scalars. 5187 if (!IsBVOrSV1 && !IsBVOrSV2) 5188 return SDValue(); 5189 5190 EVT SVT = VT.getScalarType(); 5191 EVT LegalSVT = SVT; 5192 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5193 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5194 if (LegalSVT.bitsLT(SVT)) 5195 return SDValue(); 5196 } 5197 5198 SmallVector<SDValue, 4> Outputs; 5199 unsigned NumOps = 0; 5200 if (IsBVOrSV1) 5201 NumOps = std::max(NumOps, N1->getNumOperands()); 5202 if (IsBVOrSV2) 5203 NumOps = std::max(NumOps, N2->getNumOperands()); 5204 assert(NumOps != 0 && "Expected non-zero operands"); 5205 // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need 5206 // one iteration for that. 5207 assert((!VT.isScalableVector() || NumOps == 1) && 5208 "Scalar vector should only have one scalar"); 5209 5210 for (unsigned I = 0; I != NumOps; ++I) { 5211 // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need 5212 // to use operand 0 of the SPLAT_VECTOR for each fixed element. 5213 SDValue V1; 5214 if (N1->getOpcode() == ISD::BUILD_VECTOR) 5215 V1 = N1->getOperand(I); 5216 else if (N1->getOpcode() == ISD::SPLAT_VECTOR) 5217 V1 = N1->getOperand(0); 5218 else 5219 V1 = getUNDEF(SVT); 5220 5221 SDValue V2; 5222 if (N2->getOpcode() == ISD::BUILD_VECTOR) 5223 V2 = N2->getOperand(I); 5224 else if (N2->getOpcode() == ISD::SPLAT_VECTOR) 5225 V2 = N2->getOperand(0); 5226 else 5227 V2 = getUNDEF(SVT); 5228 5229 if (SVT.isInteger()) { 5230 if (V1.getValueType().bitsGT(SVT)) 5231 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1); 5232 if (V2.getValueType().bitsGT(SVT)) 5233 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2); 5234 } 5235 5236 if (V1.getValueType() != SVT || V2.getValueType() != SVT) 5237 return SDValue(); 5238 5239 // Fold one vector element. 5240 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2); 5241 if (LegalSVT != SVT) 5242 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5243 5244 // Scalar folding only succeeded if the result is a constant or UNDEF. 5245 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5246 ScalarResult.getOpcode() != ISD::ConstantFP) 5247 return SDValue(); 5248 Outputs.push_back(ScalarResult); 5249 } 5250 5251 if (N1->getOpcode() == ISD::BUILD_VECTOR || 5252 N2->getOpcode() == ISD::BUILD_VECTOR) { 5253 assert(VT.getVectorNumElements() == Outputs.size() && 5254 "Vector size mismatch!"); 5255 5256 // Build a big vector out of the scalar elements we generated. 5257 return getBuildVector(VT, SDLoc(), Outputs); 5258 } 5259 5260 assert((N1->getOpcode() == ISD::SPLAT_VECTOR || 5261 N2->getOpcode() == ISD::SPLAT_VECTOR) && 5262 "One operand should be a splat vector"); 5263 5264 assert(Outputs.size() == 1 && "Vector size mismatch!"); 5265 return getSplatVector(VT, SDLoc(), Outputs[0]); 5266 } 5267 5268 // TODO: Merge with FoldConstantArithmetic 5269 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 5270 const SDLoc &DL, EVT VT, 5271 ArrayRef<SDValue> Ops, 5272 const SDNodeFlags Flags) { 5273 // If the opcode is a target-specific ISD node, there's nothing we can 5274 // do here and the operand rules may not line up with the below, so 5275 // bail early. 5276 if (Opcode >= ISD::BUILTIN_OP_END) 5277 return SDValue(); 5278 5279 if (isUndef(Opcode, Ops)) 5280 return getUNDEF(VT); 5281 5282 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 5283 if (!VT.isVector()) 5284 return SDValue(); 5285 5286 // TODO: All the folds below are performed lane-by-lane and assume a fixed 5287 // vector width, however we should be able to do constant folds involving 5288 // splat vector nodes too. 5289 if (VT.isScalableVector()) 5290 return SDValue(); 5291 5292 // From this point onwards all vectors are assumed to be fixed width. 5293 unsigned NumElts = VT.getVectorNumElements(); 5294 5295 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) { 5296 return !Op.getValueType().isVector() || 5297 Op.getValueType().getVectorNumElements() == NumElts; 5298 }; 5299 5300 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) { 5301 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 5302 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) || 5303 (BV && BV->isConstant()); 5304 }; 5305 5306 // All operands must be vector types with the same number of elements as 5307 // the result type and must be either UNDEF or a build vector of constant 5308 // or UNDEF scalars. 5309 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) || 5310 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5311 return SDValue(); 5312 5313 // If we are comparing vectors, then the result needs to be a i1 boolean 5314 // that is then sign-extended back to the legal result type. 5315 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5316 5317 // Find legal integer scalar type for constant promotion and 5318 // ensure that its scalar size is at least as large as source. 5319 EVT LegalSVT = VT.getScalarType(); 5320 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5321 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5322 if (LegalSVT.bitsLT(VT.getScalarType())) 5323 return SDValue(); 5324 } 5325 5326 // Constant fold each scalar lane separately. 5327 SmallVector<SDValue, 4> ScalarResults; 5328 for (unsigned i = 0; i != NumElts; i++) { 5329 SmallVector<SDValue, 4> ScalarOps; 5330 for (SDValue Op : Ops) { 5331 EVT InSVT = Op.getValueType().getScalarType(); 5332 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op); 5333 if (!InBV) { 5334 // We've checked that this is UNDEF or a constant of some kind. 5335 if (Op.isUndef()) 5336 ScalarOps.push_back(getUNDEF(InSVT)); 5337 else 5338 ScalarOps.push_back(Op); 5339 continue; 5340 } 5341 5342 SDValue ScalarOp = InBV->getOperand(i); 5343 EVT ScalarVT = ScalarOp.getValueType(); 5344 5345 // Build vector (integer) scalar operands may need implicit 5346 // truncation - do this before constant folding. 5347 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5348 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5349 5350 ScalarOps.push_back(ScalarOp); 5351 } 5352 5353 // Constant fold the scalar operands. 5354 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 5355 5356 // Legalize the (integer) scalar constant if necessary. 5357 if (LegalSVT != SVT) 5358 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5359 5360 // Scalar folding only succeeded if the result is a constant or UNDEF. 5361 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5362 ScalarResult.getOpcode() != ISD::ConstantFP) 5363 return SDValue(); 5364 ScalarResults.push_back(ScalarResult); 5365 } 5366 5367 SDValue V = getBuildVector(VT, DL, ScalarResults); 5368 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5369 return V; 5370 } 5371 5372 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5373 EVT VT, SDValue N1, SDValue N2) { 5374 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5375 // should. That will require dealing with a potentially non-default 5376 // rounding mode, checking the "opStatus" return value from the APFloat 5377 // math calculations, and possibly other variations. 5378 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 5379 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 5380 if (N1CFP && N2CFP) { 5381 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF(); 5382 switch (Opcode) { 5383 case ISD::FADD: 5384 C1.add(C2, APFloat::rmNearestTiesToEven); 5385 return getConstantFP(C1, DL, VT); 5386 case ISD::FSUB: 5387 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5388 return getConstantFP(C1, DL, VT); 5389 case ISD::FMUL: 5390 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5391 return getConstantFP(C1, DL, VT); 5392 case ISD::FDIV: 5393 C1.divide(C2, APFloat::rmNearestTiesToEven); 5394 return getConstantFP(C1, DL, VT); 5395 case ISD::FREM: 5396 C1.mod(C2); 5397 return getConstantFP(C1, DL, VT); 5398 case ISD::FCOPYSIGN: 5399 C1.copySign(C2); 5400 return getConstantFP(C1, DL, VT); 5401 default: break; 5402 } 5403 } 5404 if (N1CFP && Opcode == ISD::FP_ROUND) { 5405 APFloat C1 = N1CFP->getValueAPF(); // make copy 5406 bool Unused; 5407 // This can return overflow, underflow, or inexact; we don't care. 5408 // FIXME need to be more flexible about rounding mode. 5409 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5410 &Unused); 5411 return getConstantFP(C1, DL, VT); 5412 } 5413 5414 switch (Opcode) { 5415 case ISD::FSUB: 5416 // -0.0 - undef --> undef (consistent with "fneg undef") 5417 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef()) 5418 return getUNDEF(VT); 5419 LLVM_FALLTHROUGH; 5420 5421 case ISD::FADD: 5422 case ISD::FMUL: 5423 case ISD::FDIV: 5424 case ISD::FREM: 5425 // If both operands are undef, the result is undef. If 1 operand is undef, 5426 // the result is NaN. This should match the behavior of the IR optimizer. 5427 if (N1.isUndef() && N2.isUndef()) 5428 return getUNDEF(VT); 5429 if (N1.isUndef() || N2.isUndef()) 5430 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5431 } 5432 return SDValue(); 5433 } 5434 5435 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5436 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5437 5438 // There's no need to assert on a byte-aligned pointer. All pointers are at 5439 // least byte aligned. 5440 if (A == Align(1)) 5441 return Val; 5442 5443 FoldingSetNodeID ID; 5444 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5445 ID.AddInteger(A.value()); 5446 5447 void *IP = nullptr; 5448 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5449 return SDValue(E, 0); 5450 5451 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5452 Val.getValueType(), A); 5453 createOperands(N, {Val}); 5454 5455 CSEMap.InsertNode(N, IP); 5456 InsertNode(N); 5457 5458 SDValue V(N, 0); 5459 NewSDValueDbgMsg(V, "Creating new node: ", this); 5460 return V; 5461 } 5462 5463 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5464 SDValue N1, SDValue N2) { 5465 SDNodeFlags Flags; 5466 if (Inserter) 5467 Flags = Inserter->getFlags(); 5468 return getNode(Opcode, DL, VT, N1, N2, Flags); 5469 } 5470 5471 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5472 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5473 assert(N1.getOpcode() != ISD::DELETED_NODE && 5474 N2.getOpcode() != ISD::DELETED_NODE && 5475 "Operand is DELETED_NODE!"); 5476 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5477 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5478 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5479 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5480 5481 // Canonicalize constant to RHS if commutative. 5482 if (TLI->isCommutativeBinOp(Opcode)) { 5483 if (N1C && !N2C) { 5484 std::swap(N1C, N2C); 5485 std::swap(N1, N2); 5486 } else if (N1CFP && !N2CFP) { 5487 std::swap(N1CFP, N2CFP); 5488 std::swap(N1, N2); 5489 } 5490 } 5491 5492 switch (Opcode) { 5493 default: break; 5494 case ISD::TokenFactor: 5495 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5496 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5497 // Fold trivial token factors. 5498 if (N1.getOpcode() == ISD::EntryToken) return N2; 5499 if (N2.getOpcode() == ISD::EntryToken) return N1; 5500 if (N1 == N2) return N1; 5501 break; 5502 case ISD::BUILD_VECTOR: { 5503 // Attempt to simplify BUILD_VECTOR. 5504 SDValue Ops[] = {N1, N2}; 5505 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5506 return V; 5507 break; 5508 } 5509 case ISD::CONCAT_VECTORS: { 5510 SDValue Ops[] = {N1, N2}; 5511 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5512 return V; 5513 break; 5514 } 5515 case ISD::AND: 5516 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5517 assert(N1.getValueType() == N2.getValueType() && 5518 N1.getValueType() == VT && "Binary operator types must match!"); 5519 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5520 // worth handling here. 5521 if (N2C && N2C->isNullValue()) 5522 return N2; 5523 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 5524 return N1; 5525 break; 5526 case ISD::OR: 5527 case ISD::XOR: 5528 case ISD::ADD: 5529 case ISD::SUB: 5530 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5531 assert(N1.getValueType() == N2.getValueType() && 5532 N1.getValueType() == VT && "Binary operator types must match!"); 5533 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5534 // it's worth handling here. 5535 if (N2C && N2C->isNullValue()) 5536 return N1; 5537 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5538 VT.getVectorElementType() == MVT::i1) 5539 return getNode(ISD::XOR, DL, VT, N1, N2); 5540 break; 5541 case ISD::MUL: 5542 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5543 assert(N1.getValueType() == N2.getValueType() && 5544 N1.getValueType() == VT && "Binary operator types must match!"); 5545 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5546 return getNode(ISD::AND, DL, VT, N1, N2); 5547 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5548 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5549 const APInt &N2CImm = N2C->getAPIntValue(); 5550 return getVScale(DL, VT, MulImm * N2CImm); 5551 } 5552 break; 5553 case ISD::UDIV: 5554 case ISD::UREM: 5555 case ISD::MULHU: 5556 case ISD::MULHS: 5557 case ISD::SDIV: 5558 case ISD::SREM: 5559 case ISD::SADDSAT: 5560 case ISD::SSUBSAT: 5561 case ISD::UADDSAT: 5562 case ISD::USUBSAT: 5563 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5564 assert(N1.getValueType() == N2.getValueType() && 5565 N1.getValueType() == VT && "Binary operator types must match!"); 5566 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5567 // fold (add_sat x, y) -> (or x, y) for bool types. 5568 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5569 return getNode(ISD::OR, DL, VT, N1, N2); 5570 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5571 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5572 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5573 } 5574 break; 5575 case ISD::SMIN: 5576 case ISD::UMAX: 5577 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5578 assert(N1.getValueType() == N2.getValueType() && 5579 N1.getValueType() == VT && "Binary operator types must match!"); 5580 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5581 return getNode(ISD::OR, DL, VT, N1, N2); 5582 break; 5583 case ISD::SMAX: 5584 case ISD::UMIN: 5585 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5586 assert(N1.getValueType() == N2.getValueType() && 5587 N1.getValueType() == VT && "Binary operator types must match!"); 5588 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5589 return getNode(ISD::AND, DL, VT, N1, N2); 5590 break; 5591 case ISD::FADD: 5592 case ISD::FSUB: 5593 case ISD::FMUL: 5594 case ISD::FDIV: 5595 case ISD::FREM: 5596 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5597 assert(N1.getValueType() == N2.getValueType() && 5598 N1.getValueType() == VT && "Binary operator types must match!"); 5599 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5600 return V; 5601 break; 5602 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5603 assert(N1.getValueType() == VT && 5604 N1.getValueType().isFloatingPoint() && 5605 N2.getValueType().isFloatingPoint() && 5606 "Invalid FCOPYSIGN!"); 5607 break; 5608 case ISD::SHL: 5609 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5610 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5611 const APInt &ShiftImm = N2C->getAPIntValue(); 5612 return getVScale(DL, VT, MulImm << ShiftImm); 5613 } 5614 LLVM_FALLTHROUGH; 5615 case ISD::SRA: 5616 case ISD::SRL: 5617 if (SDValue V = simplifyShift(N1, N2)) 5618 return V; 5619 LLVM_FALLTHROUGH; 5620 case ISD::ROTL: 5621 case ISD::ROTR: 5622 assert(VT == N1.getValueType() && 5623 "Shift operators return type must be the same as their first arg"); 5624 assert(VT.isInteger() && N2.getValueType().isInteger() && 5625 "Shifts only work on integers"); 5626 assert((!VT.isVector() || VT == N2.getValueType()) && 5627 "Vector shift amounts must be in the same as their first arg"); 5628 // Verify that the shift amount VT is big enough to hold valid shift 5629 // amounts. This catches things like trying to shift an i1024 value by an 5630 // i8, which is easy to fall into in generic code that uses 5631 // TLI.getShiftAmount(). 5632 assert(N2.getValueType().getScalarSizeInBits() >= 5633 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5634 "Invalid use of small shift amount with oversized value!"); 5635 5636 // Always fold shifts of i1 values so the code generator doesn't need to 5637 // handle them. Since we know the size of the shift has to be less than the 5638 // size of the value, the shift/rotate count is guaranteed to be zero. 5639 if (VT == MVT::i1) 5640 return N1; 5641 if (N2C && N2C->isNullValue()) 5642 return N1; 5643 break; 5644 case ISD::FP_ROUND: 5645 assert(VT.isFloatingPoint() && 5646 N1.getValueType().isFloatingPoint() && 5647 VT.bitsLE(N1.getValueType()) && 5648 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5649 "Invalid FP_ROUND!"); 5650 if (N1.getValueType() == VT) return N1; // noop conversion. 5651 break; 5652 case ISD::AssertSext: 5653 case ISD::AssertZext: { 5654 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5655 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5656 assert(VT.isInteger() && EVT.isInteger() && 5657 "Cannot *_EXTEND_INREG FP types"); 5658 assert(!EVT.isVector() && 5659 "AssertSExt/AssertZExt type should be the vector element type " 5660 "rather than the vector type!"); 5661 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5662 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5663 break; 5664 } 5665 case ISD::SIGN_EXTEND_INREG: { 5666 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5667 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5668 assert(VT.isInteger() && EVT.isInteger() && 5669 "Cannot *_EXTEND_INREG FP types"); 5670 assert(EVT.isVector() == VT.isVector() && 5671 "SIGN_EXTEND_INREG type should be vector iff the operand " 5672 "type is vector!"); 5673 assert((!EVT.isVector() || 5674 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5675 "Vector element counts must match in SIGN_EXTEND_INREG"); 5676 assert(EVT.bitsLE(VT) && "Not extending!"); 5677 if (EVT == VT) return N1; // Not actually extending 5678 5679 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5680 unsigned FromBits = EVT.getScalarSizeInBits(); 5681 Val <<= Val.getBitWidth() - FromBits; 5682 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5683 return getConstant(Val, DL, ConstantVT); 5684 }; 5685 5686 if (N1C) { 5687 const APInt &Val = N1C->getAPIntValue(); 5688 return SignExtendInReg(Val, VT); 5689 } 5690 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5691 SmallVector<SDValue, 8> Ops; 5692 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5693 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5694 SDValue Op = N1.getOperand(i); 5695 if (Op.isUndef()) { 5696 Ops.push_back(getUNDEF(OpVT)); 5697 continue; 5698 } 5699 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5700 APInt Val = C->getAPIntValue(); 5701 Ops.push_back(SignExtendInReg(Val, OpVT)); 5702 } 5703 return getBuildVector(VT, DL, Ops); 5704 } 5705 break; 5706 } 5707 case ISD::FP_TO_SINT_SAT: 5708 case ISD::FP_TO_UINT_SAT: { 5709 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 5710 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 5711 assert(N1.getValueType().isVector() == VT.isVector() && 5712 "FP_TO_*INT_SAT type should be vector iff the operand type is " 5713 "vector!"); 5714 assert((!VT.isVector() || VT.getVectorNumElements() == 5715 N1.getValueType().getVectorNumElements()) && 5716 "Vector element counts must match in FP_TO_*INT_SAT"); 5717 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 5718 "Type to saturate to must be a scalar."); 5719 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 5720 "Not extending!"); 5721 break; 5722 } 5723 case ISD::EXTRACT_VECTOR_ELT: 5724 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5725 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5726 element type of the vector."); 5727 5728 // Extract from an undefined value or using an undefined index is undefined. 5729 if (N1.isUndef() || N2.isUndef()) 5730 return getUNDEF(VT); 5731 5732 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5733 // vectors. For scalable vectors we will provide appropriate support for 5734 // dealing with arbitrary indices. 5735 if (N2C && N1.getValueType().isFixedLengthVector() && 5736 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5737 return getUNDEF(VT); 5738 5739 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5740 // expanding copies of large vectors from registers. This only works for 5741 // fixed length vectors, since we need to know the exact number of 5742 // elements. 5743 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5744 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5745 unsigned Factor = 5746 N1.getOperand(0).getValueType().getVectorNumElements(); 5747 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5748 N1.getOperand(N2C->getZExtValue() / Factor), 5749 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5750 } 5751 5752 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5753 // lowering is expanding large vector constants. 5754 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5755 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5756 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5757 N1.getValueType().isFixedLengthVector()) && 5758 "BUILD_VECTOR used for scalable vectors"); 5759 unsigned Index = 5760 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5761 SDValue Elt = N1.getOperand(Index); 5762 5763 if (VT != Elt.getValueType()) 5764 // If the vector element type is not legal, the BUILD_VECTOR operands 5765 // are promoted and implicitly truncated, and the result implicitly 5766 // extended. Make that explicit here. 5767 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5768 5769 return Elt; 5770 } 5771 5772 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5773 // operations are lowered to scalars. 5774 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5775 // If the indices are the same, return the inserted element else 5776 // if the indices are known different, extract the element from 5777 // the original vector. 5778 SDValue N1Op2 = N1.getOperand(2); 5779 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5780 5781 if (N1Op2C && N2C) { 5782 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5783 if (VT == N1.getOperand(1).getValueType()) 5784 return N1.getOperand(1); 5785 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5786 } 5787 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5788 } 5789 } 5790 5791 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5792 // when vector types are scalarized and v1iX is legal. 5793 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5794 // Here we are completely ignoring the extract element index (N2), 5795 // which is fine for fixed width vectors, since any index other than 0 5796 // is undefined anyway. However, this cannot be ignored for scalable 5797 // vectors - in theory we could support this, but we don't want to do this 5798 // without a profitability check. 5799 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5800 N1.getValueType().isFixedLengthVector() && 5801 N1.getValueType().getVectorNumElements() == 1) { 5802 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5803 N1.getOperand(1)); 5804 } 5805 break; 5806 case ISD::EXTRACT_ELEMENT: 5807 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5808 assert(!N1.getValueType().isVector() && !VT.isVector() && 5809 (N1.getValueType().isInteger() == VT.isInteger()) && 5810 N1.getValueType() != VT && 5811 "Wrong types for EXTRACT_ELEMENT!"); 5812 5813 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5814 // 64-bit integers into 32-bit parts. Instead of building the extract of 5815 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5816 if (N1.getOpcode() == ISD::BUILD_PAIR) 5817 return N1.getOperand(N2C->getZExtValue()); 5818 5819 // EXTRACT_ELEMENT of a constant int is also very common. 5820 if (N1C) { 5821 unsigned ElementSize = VT.getSizeInBits(); 5822 unsigned Shift = ElementSize * N2C->getZExtValue(); 5823 const APInt &Val = N1C->getAPIntValue(); 5824 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 5825 } 5826 break; 5827 case ISD::EXTRACT_SUBVECTOR: 5828 EVT N1VT = N1.getValueType(); 5829 assert(VT.isVector() && N1VT.isVector() && 5830 "Extract subvector VTs must be vectors!"); 5831 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5832 "Extract subvector VTs must have the same element type!"); 5833 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5834 "Cannot extract a scalable vector from a fixed length vector!"); 5835 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5836 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5837 "Extract subvector must be from larger vector to smaller vector!"); 5838 assert(N2C && "Extract subvector index must be a constant"); 5839 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5840 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5841 N1VT.getVectorMinNumElements()) && 5842 "Extract subvector overflow!"); 5843 assert(N2C->getAPIntValue().getBitWidth() == 5844 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5845 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 5846 5847 // Trivial extraction. 5848 if (VT == N1VT) 5849 return N1; 5850 5851 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 5852 if (N1.isUndef()) 5853 return getUNDEF(VT); 5854 5855 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 5856 // the concat have the same type as the extract. 5857 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 5858 VT == N1.getOperand(0).getValueType()) { 5859 unsigned Factor = VT.getVectorMinNumElements(); 5860 return N1.getOperand(N2C->getZExtValue() / Factor); 5861 } 5862 5863 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 5864 // during shuffle legalization. 5865 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 5866 VT == N1.getOperand(1).getValueType()) 5867 return N1.getOperand(1); 5868 break; 5869 } 5870 5871 // Perform trivial constant folding. 5872 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 5873 return SV; 5874 5875 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2)) 5876 return V; 5877 5878 // Canonicalize an UNDEF to the RHS, even over a constant. 5879 if (N1.isUndef()) { 5880 if (TLI->isCommutativeBinOp(Opcode)) { 5881 std::swap(N1, N2); 5882 } else { 5883 switch (Opcode) { 5884 case ISD::SIGN_EXTEND_INREG: 5885 case ISD::SUB: 5886 return getUNDEF(VT); // fold op(undef, arg2) -> undef 5887 case ISD::UDIV: 5888 case ISD::SDIV: 5889 case ISD::UREM: 5890 case ISD::SREM: 5891 case ISD::SSUBSAT: 5892 case ISD::USUBSAT: 5893 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 5894 } 5895 } 5896 } 5897 5898 // Fold a bunch of operators when the RHS is undef. 5899 if (N2.isUndef()) { 5900 switch (Opcode) { 5901 case ISD::XOR: 5902 if (N1.isUndef()) 5903 // Handle undef ^ undef -> 0 special case. This is a common 5904 // idiom (misuse). 5905 return getConstant(0, DL, VT); 5906 LLVM_FALLTHROUGH; 5907 case ISD::ADD: 5908 case ISD::SUB: 5909 case ISD::UDIV: 5910 case ISD::SDIV: 5911 case ISD::UREM: 5912 case ISD::SREM: 5913 return getUNDEF(VT); // fold op(arg1, undef) -> undef 5914 case ISD::MUL: 5915 case ISD::AND: 5916 case ISD::SSUBSAT: 5917 case ISD::USUBSAT: 5918 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 5919 case ISD::OR: 5920 case ISD::SADDSAT: 5921 case ISD::UADDSAT: 5922 return getAllOnesConstant(DL, VT); 5923 } 5924 } 5925 5926 // Memoize this node if possible. 5927 SDNode *N; 5928 SDVTList VTs = getVTList(VT); 5929 SDValue Ops[] = {N1, N2}; 5930 if (VT != MVT::Glue) { 5931 FoldingSetNodeID ID; 5932 AddNodeIDNode(ID, Opcode, VTs, Ops); 5933 void *IP = nullptr; 5934 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5935 E->intersectFlagsWith(Flags); 5936 return SDValue(E, 0); 5937 } 5938 5939 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5940 N->setFlags(Flags); 5941 createOperands(N, Ops); 5942 CSEMap.InsertNode(N, IP); 5943 } else { 5944 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5945 createOperands(N, Ops); 5946 } 5947 5948 InsertNode(N); 5949 SDValue V = SDValue(N, 0); 5950 NewSDValueDbgMsg(V, "Creating new node: ", this); 5951 return V; 5952 } 5953 5954 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5955 SDValue N1, SDValue N2, SDValue N3) { 5956 SDNodeFlags Flags; 5957 if (Inserter) 5958 Flags = Inserter->getFlags(); 5959 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 5960 } 5961 5962 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5963 SDValue N1, SDValue N2, SDValue N3, 5964 const SDNodeFlags Flags) { 5965 assert(N1.getOpcode() != ISD::DELETED_NODE && 5966 N2.getOpcode() != ISD::DELETED_NODE && 5967 N3.getOpcode() != ISD::DELETED_NODE && 5968 "Operand is DELETED_NODE!"); 5969 // Perform various simplifications. 5970 switch (Opcode) { 5971 case ISD::FMA: { 5972 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5973 assert(N1.getValueType() == VT && N2.getValueType() == VT && 5974 N3.getValueType() == VT && "FMA types must match!"); 5975 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5976 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5977 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 5978 if (N1CFP && N2CFP && N3CFP) { 5979 APFloat V1 = N1CFP->getValueAPF(); 5980 const APFloat &V2 = N2CFP->getValueAPF(); 5981 const APFloat &V3 = N3CFP->getValueAPF(); 5982 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 5983 return getConstantFP(V1, DL, VT); 5984 } 5985 break; 5986 } 5987 case ISD::BUILD_VECTOR: { 5988 // Attempt to simplify BUILD_VECTOR. 5989 SDValue Ops[] = {N1, N2, N3}; 5990 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5991 return V; 5992 break; 5993 } 5994 case ISD::CONCAT_VECTORS: { 5995 SDValue Ops[] = {N1, N2, N3}; 5996 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5997 return V; 5998 break; 5999 } 6000 case ISD::SETCC: { 6001 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6002 assert(N1.getValueType() == N2.getValueType() && 6003 "SETCC operands must have the same type!"); 6004 assert(VT.isVector() == N1.getValueType().isVector() && 6005 "SETCC type should be vector iff the operand type is vector!"); 6006 assert((!VT.isVector() || VT.getVectorElementCount() == 6007 N1.getValueType().getVectorElementCount()) && 6008 "SETCC vector element counts must match!"); 6009 // Use FoldSetCC to simplify SETCC's. 6010 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6011 return V; 6012 // Vector constant folding. 6013 SDValue Ops[] = {N1, N2, N3}; 6014 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) { 6015 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6016 return V; 6017 } 6018 break; 6019 } 6020 case ISD::SELECT: 6021 case ISD::VSELECT: 6022 if (SDValue V = simplifySelect(N1, N2, N3)) 6023 return V; 6024 break; 6025 case ISD::VECTOR_SHUFFLE: 6026 llvm_unreachable("should use getVectorShuffle constructor!"); 6027 case ISD::INSERT_VECTOR_ELT: { 6028 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6029 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6030 // for scalable vectors where we will generate appropriate code to 6031 // deal with out-of-bounds cases correctly. 6032 if (N3C && N1.getValueType().isFixedLengthVector() && 6033 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6034 return getUNDEF(VT); 6035 6036 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6037 if (N3.isUndef()) 6038 return getUNDEF(VT); 6039 6040 // If the inserted element is an UNDEF, just use the input vector. 6041 if (N2.isUndef()) 6042 return N1; 6043 6044 break; 6045 } 6046 case ISD::INSERT_SUBVECTOR: { 6047 // Inserting undef into undef is still undef. 6048 if (N1.isUndef() && N2.isUndef()) 6049 return getUNDEF(VT); 6050 6051 EVT N2VT = N2.getValueType(); 6052 assert(VT == N1.getValueType() && 6053 "Dest and insert subvector source types must match!"); 6054 assert(VT.isVector() && N2VT.isVector() && 6055 "Insert subvector VTs must be vectors!"); 6056 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6057 "Cannot insert a scalable vector into a fixed length vector!"); 6058 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6059 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6060 "Insert subvector must be from smaller vector to larger vector!"); 6061 assert(isa<ConstantSDNode>(N3) && 6062 "Insert subvector index must be constant"); 6063 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6064 (N2VT.getVectorMinNumElements() + 6065 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6066 VT.getVectorMinNumElements()) && 6067 "Insert subvector overflow!"); 6068 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6069 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6070 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6071 6072 // Trivial insertion. 6073 if (VT == N2VT) 6074 return N2; 6075 6076 // If this is an insert of an extracted vector into an undef vector, we 6077 // can just use the input to the extract. 6078 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6079 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6080 return N2.getOperand(0); 6081 break; 6082 } 6083 case ISD::BITCAST: 6084 // Fold bit_convert nodes from a type to themselves. 6085 if (N1.getValueType() == VT) 6086 return N1; 6087 break; 6088 } 6089 6090 // Memoize node if it doesn't produce a flag. 6091 SDNode *N; 6092 SDVTList VTs = getVTList(VT); 6093 SDValue Ops[] = {N1, N2, N3}; 6094 if (VT != MVT::Glue) { 6095 FoldingSetNodeID ID; 6096 AddNodeIDNode(ID, Opcode, VTs, Ops); 6097 void *IP = nullptr; 6098 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6099 E->intersectFlagsWith(Flags); 6100 return SDValue(E, 0); 6101 } 6102 6103 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6104 N->setFlags(Flags); 6105 createOperands(N, Ops); 6106 CSEMap.InsertNode(N, IP); 6107 } else { 6108 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6109 createOperands(N, Ops); 6110 } 6111 6112 InsertNode(N); 6113 SDValue V = SDValue(N, 0); 6114 NewSDValueDbgMsg(V, "Creating new node: ", this); 6115 return V; 6116 } 6117 6118 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6119 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6120 SDValue Ops[] = { N1, N2, N3, N4 }; 6121 return getNode(Opcode, DL, VT, Ops); 6122 } 6123 6124 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6125 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6126 SDValue N5) { 6127 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6128 return getNode(Opcode, DL, VT, Ops); 6129 } 6130 6131 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6132 /// the incoming stack arguments to be loaded from the stack. 6133 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6134 SmallVector<SDValue, 8> ArgChains; 6135 6136 // Include the original chain at the beginning of the list. When this is 6137 // used by target LowerCall hooks, this helps legalize find the 6138 // CALLSEQ_BEGIN node. 6139 ArgChains.push_back(Chain); 6140 6141 // Add a chain value for each stack argument. 6142 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 6143 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 6144 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 6145 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6146 if (FI->getIndex() < 0) 6147 ArgChains.push_back(SDValue(L, 1)); 6148 6149 // Build a tokenfactor for all the chains. 6150 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6151 } 6152 6153 /// getMemsetValue - Vectorized representation of the memset value 6154 /// operand. 6155 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6156 const SDLoc &dl) { 6157 assert(!Value.isUndef()); 6158 6159 unsigned NumBits = VT.getScalarSizeInBits(); 6160 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6161 assert(C->getAPIntValue().getBitWidth() == 8); 6162 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6163 if (VT.isInteger()) { 6164 bool IsOpaque = VT.getSizeInBits() > 64 || 6165 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6166 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6167 } 6168 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6169 VT); 6170 } 6171 6172 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6173 EVT IntVT = VT.getScalarType(); 6174 if (!IntVT.isInteger()) 6175 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6176 6177 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6178 if (NumBits > 8) { 6179 // Use a multiplication with 0x010101... to extend the input to the 6180 // required length. 6181 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6182 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6183 DAG.getConstant(Magic, dl, IntVT)); 6184 } 6185 6186 if (VT != Value.getValueType() && !VT.isInteger()) 6187 Value = DAG.getBitcast(VT.getScalarType(), Value); 6188 if (VT != Value.getValueType()) 6189 Value = DAG.getSplatBuildVector(VT, dl, Value); 6190 6191 return Value; 6192 } 6193 6194 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6195 /// used when a memcpy is turned into a memset when the source is a constant 6196 /// string ptr. 6197 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6198 const TargetLowering &TLI, 6199 const ConstantDataArraySlice &Slice) { 6200 // Handle vector with all elements zero. 6201 if (Slice.Array == nullptr) { 6202 if (VT.isInteger()) 6203 return DAG.getConstant(0, dl, VT); 6204 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6205 return DAG.getConstantFP(0.0, dl, VT); 6206 if (VT.isVector()) { 6207 unsigned NumElts = VT.getVectorNumElements(); 6208 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6209 return DAG.getNode(ISD::BITCAST, dl, VT, 6210 DAG.getConstant(0, dl, 6211 EVT::getVectorVT(*DAG.getContext(), 6212 EltVT, NumElts))); 6213 } 6214 llvm_unreachable("Expected type!"); 6215 } 6216 6217 assert(!VT.isVector() && "Can't handle vector type here!"); 6218 unsigned NumVTBits = VT.getSizeInBits(); 6219 unsigned NumVTBytes = NumVTBits / 8; 6220 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6221 6222 APInt Val(NumVTBits, 0); 6223 if (DAG.getDataLayout().isLittleEndian()) { 6224 for (unsigned i = 0; i != NumBytes; ++i) 6225 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6226 } else { 6227 for (unsigned i = 0; i != NumBytes; ++i) 6228 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6229 } 6230 6231 // If the "cost" of materializing the integer immediate is less than the cost 6232 // of a load, then it is cost effective to turn the load into the immediate. 6233 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6234 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6235 return DAG.getConstant(Val, dl, VT); 6236 return SDValue(nullptr, 0); 6237 } 6238 6239 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6240 const SDLoc &DL, 6241 const SDNodeFlags Flags) { 6242 EVT VT = Base.getValueType(); 6243 SDValue Index; 6244 6245 if (Offset.isScalable()) 6246 Index = getVScale(DL, Base.getValueType(), 6247 APInt(Base.getValueSizeInBits().getFixedSize(), 6248 Offset.getKnownMinSize())); 6249 else 6250 Index = getConstant(Offset.getFixedSize(), DL, VT); 6251 6252 return getMemBasePlusOffset(Base, Index, DL, Flags); 6253 } 6254 6255 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6256 const SDLoc &DL, 6257 const SDNodeFlags Flags) { 6258 assert(Offset.getValueType().isInteger()); 6259 EVT BasePtrVT = Ptr.getValueType(); 6260 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6261 } 6262 6263 /// Returns true if memcpy source is constant data. 6264 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6265 uint64_t SrcDelta = 0; 6266 GlobalAddressSDNode *G = nullptr; 6267 if (Src.getOpcode() == ISD::GlobalAddress) 6268 G = cast<GlobalAddressSDNode>(Src); 6269 else if (Src.getOpcode() == ISD::ADD && 6270 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6271 Src.getOperand(1).getOpcode() == ISD::Constant) { 6272 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6273 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6274 } 6275 if (!G) 6276 return false; 6277 6278 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6279 SrcDelta + G->getOffset()); 6280 } 6281 6282 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6283 SelectionDAG &DAG) { 6284 // On Darwin, -Os means optimize for size without hurting performance, so 6285 // only really optimize for size when -Oz (MinSize) is used. 6286 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6287 return MF.getFunction().hasMinSize(); 6288 return DAG.shouldOptForSize(); 6289 } 6290 6291 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6292 SmallVector<SDValue, 32> &OutChains, unsigned From, 6293 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6294 SmallVector<SDValue, 16> &OutStoreChains) { 6295 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6296 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6297 SmallVector<SDValue, 16> GluedLoadChains; 6298 for (unsigned i = From; i < To; ++i) { 6299 OutChains.push_back(OutLoadChains[i]); 6300 GluedLoadChains.push_back(OutLoadChains[i]); 6301 } 6302 6303 // Chain for all loads. 6304 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6305 GluedLoadChains); 6306 6307 for (unsigned i = From; i < To; ++i) { 6308 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6309 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6310 ST->getBasePtr(), ST->getMemoryVT(), 6311 ST->getMemOperand()); 6312 OutChains.push_back(NewStore); 6313 } 6314 } 6315 6316 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6317 SDValue Chain, SDValue Dst, SDValue Src, 6318 uint64_t Size, Align Alignment, 6319 bool isVol, bool AlwaysInline, 6320 MachinePointerInfo DstPtrInfo, 6321 MachinePointerInfo SrcPtrInfo) { 6322 // Turn a memcpy of undef to nop. 6323 // FIXME: We need to honor volatile even is Src is undef. 6324 if (Src.isUndef()) 6325 return Chain; 6326 6327 // Expand memcpy to a series of load and store ops if the size operand falls 6328 // below a certain threshold. 6329 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6330 // rather than maybe a humongous number of loads and stores. 6331 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6332 const DataLayout &DL = DAG.getDataLayout(); 6333 LLVMContext &C = *DAG.getContext(); 6334 std::vector<EVT> MemOps; 6335 bool DstAlignCanChange = false; 6336 MachineFunction &MF = DAG.getMachineFunction(); 6337 MachineFrameInfo &MFI = MF.getFrameInfo(); 6338 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6339 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6340 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6341 DstAlignCanChange = true; 6342 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6343 if (!SrcAlign || Alignment > *SrcAlign) 6344 SrcAlign = Alignment; 6345 assert(SrcAlign && "SrcAlign must be set"); 6346 ConstantDataArraySlice Slice; 6347 // If marked as volatile, perform a copy even when marked as constant. 6348 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6349 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6350 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6351 const MemOp Op = isZeroConstant 6352 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6353 /*IsZeroMemset*/ true, isVol) 6354 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6355 *SrcAlign, isVol, CopyFromConstant); 6356 if (!TLI.findOptimalMemOpLowering( 6357 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6358 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6359 return SDValue(); 6360 6361 if (DstAlignCanChange) { 6362 Type *Ty = MemOps[0].getTypeForEVT(C); 6363 Align NewAlign = DL.getABITypeAlign(Ty); 6364 6365 // Don't promote to an alignment that would require dynamic stack 6366 // realignment. 6367 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6368 if (!TRI->hasStackRealignment(MF)) 6369 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6370 NewAlign = NewAlign / 2; 6371 6372 if (NewAlign > Alignment) { 6373 // Give the stack frame object a larger alignment if needed. 6374 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6375 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6376 Alignment = NewAlign; 6377 } 6378 } 6379 6380 MachineMemOperand::Flags MMOFlags = 6381 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6382 SmallVector<SDValue, 16> OutLoadChains; 6383 SmallVector<SDValue, 16> OutStoreChains; 6384 SmallVector<SDValue, 32> OutChains; 6385 unsigned NumMemOps = MemOps.size(); 6386 uint64_t SrcOff = 0, DstOff = 0; 6387 for (unsigned i = 0; i != NumMemOps; ++i) { 6388 EVT VT = MemOps[i]; 6389 unsigned VTSize = VT.getSizeInBits() / 8; 6390 SDValue Value, Store; 6391 6392 if (VTSize > Size) { 6393 // Issuing an unaligned load / store pair that overlaps with the previous 6394 // pair. Adjust the offset accordingly. 6395 assert(i == NumMemOps-1 && i != 0); 6396 SrcOff -= VTSize - Size; 6397 DstOff -= VTSize - Size; 6398 } 6399 6400 if (CopyFromConstant && 6401 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6402 // It's unlikely a store of a vector immediate can be done in a single 6403 // instruction. It would require a load from a constantpool first. 6404 // We only handle zero vectors here. 6405 // FIXME: Handle other cases where store of vector immediate is done in 6406 // a single instruction. 6407 ConstantDataArraySlice SubSlice; 6408 if (SrcOff < Slice.Length) { 6409 SubSlice = Slice; 6410 SubSlice.move(SrcOff); 6411 } else { 6412 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6413 SubSlice.Array = nullptr; 6414 SubSlice.Offset = 0; 6415 SubSlice.Length = VTSize; 6416 } 6417 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6418 if (Value.getNode()) { 6419 Store = DAG.getStore( 6420 Chain, dl, Value, 6421 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6422 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6423 OutChains.push_back(Store); 6424 } 6425 } 6426 6427 if (!Store.getNode()) { 6428 // The type might not be legal for the target. This should only happen 6429 // if the type is smaller than a legal type, as on PPC, so the right 6430 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6431 // to Load/Store if NVT==VT. 6432 // FIXME does the case above also need this? 6433 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6434 assert(NVT.bitsGE(VT)); 6435 6436 bool isDereferenceable = 6437 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6438 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6439 if (isDereferenceable) 6440 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6441 6442 Value = DAG.getExtLoad( 6443 ISD::EXTLOAD, dl, NVT, Chain, 6444 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6445 SrcPtrInfo.getWithOffset(SrcOff), VT, 6446 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags); 6447 OutLoadChains.push_back(Value.getValue(1)); 6448 6449 Store = DAG.getTruncStore( 6450 Chain, dl, Value, 6451 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6452 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags); 6453 OutStoreChains.push_back(Store); 6454 } 6455 SrcOff += VTSize; 6456 DstOff += VTSize; 6457 Size -= VTSize; 6458 } 6459 6460 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6461 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6462 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6463 6464 if (NumLdStInMemcpy) { 6465 // It may be that memcpy might be converted to memset if it's memcpy 6466 // of constants. In such a case, we won't have loads and stores, but 6467 // just stores. In the absence of loads, there is nothing to gang up. 6468 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6469 // If target does not care, just leave as it. 6470 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6471 OutChains.push_back(OutLoadChains[i]); 6472 OutChains.push_back(OutStoreChains[i]); 6473 } 6474 } else { 6475 // Ld/St less than/equal limit set by target. 6476 if (NumLdStInMemcpy <= GluedLdStLimit) { 6477 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6478 NumLdStInMemcpy, OutLoadChains, 6479 OutStoreChains); 6480 } else { 6481 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6482 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6483 unsigned GlueIter = 0; 6484 6485 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6486 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6487 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6488 6489 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6490 OutLoadChains, OutStoreChains); 6491 GlueIter += GluedLdStLimit; 6492 } 6493 6494 // Residual ld/st. 6495 if (RemainingLdStInMemcpy) { 6496 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6497 RemainingLdStInMemcpy, OutLoadChains, 6498 OutStoreChains); 6499 } 6500 } 6501 } 6502 } 6503 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6504 } 6505 6506 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6507 SDValue Chain, SDValue Dst, SDValue Src, 6508 uint64_t Size, Align Alignment, 6509 bool isVol, bool AlwaysInline, 6510 MachinePointerInfo DstPtrInfo, 6511 MachinePointerInfo SrcPtrInfo) { 6512 // Turn a memmove of undef to nop. 6513 // FIXME: We need to honor volatile even is Src is undef. 6514 if (Src.isUndef()) 6515 return Chain; 6516 6517 // Expand memmove to a series of load and store ops if the size operand falls 6518 // below a certain threshold. 6519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6520 const DataLayout &DL = DAG.getDataLayout(); 6521 LLVMContext &C = *DAG.getContext(); 6522 std::vector<EVT> MemOps; 6523 bool DstAlignCanChange = false; 6524 MachineFunction &MF = DAG.getMachineFunction(); 6525 MachineFrameInfo &MFI = MF.getFrameInfo(); 6526 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6527 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6528 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6529 DstAlignCanChange = true; 6530 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6531 if (!SrcAlign || Alignment > *SrcAlign) 6532 SrcAlign = Alignment; 6533 assert(SrcAlign && "SrcAlign must be set"); 6534 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6535 if (!TLI.findOptimalMemOpLowering( 6536 MemOps, Limit, 6537 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6538 /*IsVolatile*/ true), 6539 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6540 MF.getFunction().getAttributes())) 6541 return SDValue(); 6542 6543 if (DstAlignCanChange) { 6544 Type *Ty = MemOps[0].getTypeForEVT(C); 6545 Align NewAlign = DL.getABITypeAlign(Ty); 6546 if (NewAlign > Alignment) { 6547 // Give the stack frame object a larger alignment if needed. 6548 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6549 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6550 Alignment = NewAlign; 6551 } 6552 } 6553 6554 MachineMemOperand::Flags MMOFlags = 6555 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6556 uint64_t SrcOff = 0, DstOff = 0; 6557 SmallVector<SDValue, 8> LoadValues; 6558 SmallVector<SDValue, 8> LoadChains; 6559 SmallVector<SDValue, 8> OutChains; 6560 unsigned NumMemOps = MemOps.size(); 6561 for (unsigned i = 0; i < NumMemOps; i++) { 6562 EVT VT = MemOps[i]; 6563 unsigned VTSize = VT.getSizeInBits() / 8; 6564 SDValue Value; 6565 6566 bool isDereferenceable = 6567 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6568 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6569 if (isDereferenceable) 6570 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6571 6572 Value = 6573 DAG.getLoad(VT, dl, Chain, 6574 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6575 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags); 6576 LoadValues.push_back(Value); 6577 LoadChains.push_back(Value.getValue(1)); 6578 SrcOff += VTSize; 6579 } 6580 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6581 OutChains.clear(); 6582 for (unsigned i = 0; i < NumMemOps; i++) { 6583 EVT VT = MemOps[i]; 6584 unsigned VTSize = VT.getSizeInBits() / 8; 6585 SDValue Store; 6586 6587 Store = 6588 DAG.getStore(Chain, dl, LoadValues[i], 6589 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6590 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6591 OutChains.push_back(Store); 6592 DstOff += VTSize; 6593 } 6594 6595 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6596 } 6597 6598 /// Lower the call to 'memset' intrinsic function into a series of store 6599 /// operations. 6600 /// 6601 /// \param DAG Selection DAG where lowered code is placed. 6602 /// \param dl Link to corresponding IR location. 6603 /// \param Chain Control flow dependency. 6604 /// \param Dst Pointer to destination memory location. 6605 /// \param Src Value of byte to write into the memory. 6606 /// \param Size Number of bytes to write. 6607 /// \param Alignment Alignment of the destination in bytes. 6608 /// \param isVol True if destination is volatile. 6609 /// \param DstPtrInfo IR information on the memory pointer. 6610 /// \returns New head in the control flow, if lowering was successful, empty 6611 /// SDValue otherwise. 6612 /// 6613 /// The function tries to replace 'llvm.memset' intrinsic with several store 6614 /// operations and value calculation code. This is usually profitable for small 6615 /// memory size. 6616 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6617 SDValue Chain, SDValue Dst, SDValue Src, 6618 uint64_t Size, Align Alignment, bool isVol, 6619 MachinePointerInfo DstPtrInfo) { 6620 // Turn a memset of undef to nop. 6621 // FIXME: We need to honor volatile even is Src is undef. 6622 if (Src.isUndef()) 6623 return Chain; 6624 6625 // Expand memset to a series of load/store ops if the size operand 6626 // falls below a certain threshold. 6627 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6628 std::vector<EVT> MemOps; 6629 bool DstAlignCanChange = false; 6630 MachineFunction &MF = DAG.getMachineFunction(); 6631 MachineFrameInfo &MFI = MF.getFrameInfo(); 6632 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6633 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6634 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6635 DstAlignCanChange = true; 6636 bool IsZeroVal = 6637 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 6638 if (!TLI.findOptimalMemOpLowering( 6639 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6640 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6641 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6642 return SDValue(); 6643 6644 if (DstAlignCanChange) { 6645 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6646 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6647 if (NewAlign > Alignment) { 6648 // Give the stack frame object a larger alignment if needed. 6649 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6650 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6651 Alignment = NewAlign; 6652 } 6653 } 6654 6655 SmallVector<SDValue, 8> OutChains; 6656 uint64_t DstOff = 0; 6657 unsigned NumMemOps = MemOps.size(); 6658 6659 // Find the largest store and generate the bit pattern for it. 6660 EVT LargestVT = MemOps[0]; 6661 for (unsigned i = 1; i < NumMemOps; i++) 6662 if (MemOps[i].bitsGT(LargestVT)) 6663 LargestVT = MemOps[i]; 6664 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6665 6666 for (unsigned i = 0; i < NumMemOps; i++) { 6667 EVT VT = MemOps[i]; 6668 unsigned VTSize = VT.getSizeInBits() / 8; 6669 if (VTSize > Size) { 6670 // Issuing an unaligned load / store pair that overlaps with the previous 6671 // pair. Adjust the offset accordingly. 6672 assert(i == NumMemOps-1 && i != 0); 6673 DstOff -= VTSize - Size; 6674 } 6675 6676 // If this store is smaller than the largest store see whether we can get 6677 // the smaller value for free with a truncate. 6678 SDValue Value = MemSetValue; 6679 if (VT.bitsLT(LargestVT)) { 6680 if (!LargestVT.isVector() && !VT.isVector() && 6681 TLI.isTruncateFree(LargestVT, VT)) 6682 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6683 else 6684 Value = getMemsetValue(Src, VT, DAG, dl); 6685 } 6686 assert(Value.getValueType() == VT && "Value with wrong type."); 6687 SDValue Store = DAG.getStore( 6688 Chain, dl, Value, 6689 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6690 DstPtrInfo.getWithOffset(DstOff), Alignment, 6691 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone); 6692 OutChains.push_back(Store); 6693 DstOff += VT.getSizeInBits() / 8; 6694 Size -= VTSize; 6695 } 6696 6697 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6698 } 6699 6700 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6701 unsigned AS) { 6702 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6703 // pointer operands can be losslessly bitcasted to pointers of address space 0 6704 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6705 report_fatal_error("cannot lower memory intrinsic in address space " + 6706 Twine(AS)); 6707 } 6708 } 6709 6710 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6711 SDValue Src, SDValue Size, Align Alignment, 6712 bool isVol, bool AlwaysInline, bool isTailCall, 6713 MachinePointerInfo DstPtrInfo, 6714 MachinePointerInfo SrcPtrInfo) { 6715 // Check to see if we should lower the memcpy to loads and stores first. 6716 // For cases within the target-specified limits, this is the best choice. 6717 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6718 if (ConstantSize) { 6719 // Memcpy with size zero? Just return the original chain. 6720 if (ConstantSize->isNullValue()) 6721 return Chain; 6722 6723 SDValue Result = getMemcpyLoadsAndStores( 6724 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6725 isVol, false, DstPtrInfo, SrcPtrInfo); 6726 if (Result.getNode()) 6727 return Result; 6728 } 6729 6730 // Then check to see if we should lower the memcpy with target-specific 6731 // code. If the target chooses to do this, this is the next best. 6732 if (TSI) { 6733 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6734 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6735 DstPtrInfo, SrcPtrInfo); 6736 if (Result.getNode()) 6737 return Result; 6738 } 6739 6740 // If we really need inline code and the target declined to provide it, 6741 // use a (potentially long) sequence of loads and stores. 6742 if (AlwaysInline) { 6743 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6744 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6745 ConstantSize->getZExtValue(), Alignment, 6746 isVol, true, DstPtrInfo, SrcPtrInfo); 6747 } 6748 6749 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6750 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6751 6752 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6753 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6754 // respect volatile, so they may do things like read or write memory 6755 // beyond the given memory regions. But fixing this isn't easy, and most 6756 // people don't care. 6757 6758 // Emit a library call. 6759 TargetLowering::ArgListTy Args; 6760 TargetLowering::ArgListEntry Entry; 6761 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6762 Entry.Node = Dst; Args.push_back(Entry); 6763 Entry.Node = Src; Args.push_back(Entry); 6764 6765 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6766 Entry.Node = Size; Args.push_back(Entry); 6767 // FIXME: pass in SDLoc 6768 TargetLowering::CallLoweringInfo CLI(*this); 6769 CLI.setDebugLoc(dl) 6770 .setChain(Chain) 6771 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6772 Dst.getValueType().getTypeForEVT(*getContext()), 6773 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6774 TLI->getPointerTy(getDataLayout())), 6775 std::move(Args)) 6776 .setDiscardResult() 6777 .setTailCall(isTailCall); 6778 6779 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6780 return CallResult.second; 6781 } 6782 6783 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6784 SDValue Dst, unsigned DstAlign, 6785 SDValue Src, unsigned SrcAlign, 6786 SDValue Size, Type *SizeTy, 6787 unsigned ElemSz, bool isTailCall, 6788 MachinePointerInfo DstPtrInfo, 6789 MachinePointerInfo SrcPtrInfo) { 6790 // Emit a library call. 6791 TargetLowering::ArgListTy Args; 6792 TargetLowering::ArgListEntry Entry; 6793 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6794 Entry.Node = Dst; 6795 Args.push_back(Entry); 6796 6797 Entry.Node = Src; 6798 Args.push_back(Entry); 6799 6800 Entry.Ty = SizeTy; 6801 Entry.Node = Size; 6802 Args.push_back(Entry); 6803 6804 RTLIB::Libcall LibraryCall = 6805 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6806 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6807 report_fatal_error("Unsupported element size"); 6808 6809 TargetLowering::CallLoweringInfo CLI(*this); 6810 CLI.setDebugLoc(dl) 6811 .setChain(Chain) 6812 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6813 Type::getVoidTy(*getContext()), 6814 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6815 TLI->getPointerTy(getDataLayout())), 6816 std::move(Args)) 6817 .setDiscardResult() 6818 .setTailCall(isTailCall); 6819 6820 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6821 return CallResult.second; 6822 } 6823 6824 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6825 SDValue Src, SDValue Size, Align Alignment, 6826 bool isVol, bool isTailCall, 6827 MachinePointerInfo DstPtrInfo, 6828 MachinePointerInfo SrcPtrInfo) { 6829 // Check to see if we should lower the memmove to loads and stores first. 6830 // For cases within the target-specified limits, this is the best choice. 6831 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6832 if (ConstantSize) { 6833 // Memmove with size zero? Just return the original chain. 6834 if (ConstantSize->isNullValue()) 6835 return Chain; 6836 6837 SDValue Result = getMemmoveLoadsAndStores( 6838 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6839 isVol, false, DstPtrInfo, SrcPtrInfo); 6840 if (Result.getNode()) 6841 return Result; 6842 } 6843 6844 // Then check to see if we should lower the memmove with target-specific 6845 // code. If the target chooses to do this, this is the next best. 6846 if (TSI) { 6847 SDValue Result = 6848 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 6849 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 6850 if (Result.getNode()) 6851 return Result; 6852 } 6853 6854 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6855 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6856 6857 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 6858 // not be safe. See memcpy above for more details. 6859 6860 // Emit a library call. 6861 TargetLowering::ArgListTy Args; 6862 TargetLowering::ArgListEntry Entry; 6863 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6864 Entry.Node = Dst; Args.push_back(Entry); 6865 Entry.Node = Src; Args.push_back(Entry); 6866 6867 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6868 Entry.Node = Size; Args.push_back(Entry); 6869 // FIXME: pass in SDLoc 6870 TargetLowering::CallLoweringInfo CLI(*this); 6871 CLI.setDebugLoc(dl) 6872 .setChain(Chain) 6873 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 6874 Dst.getValueType().getTypeForEVT(*getContext()), 6875 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 6876 TLI->getPointerTy(getDataLayout())), 6877 std::move(Args)) 6878 .setDiscardResult() 6879 .setTailCall(isTailCall); 6880 6881 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6882 return CallResult.second; 6883 } 6884 6885 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 6886 SDValue Dst, unsigned DstAlign, 6887 SDValue Src, unsigned SrcAlign, 6888 SDValue Size, Type *SizeTy, 6889 unsigned ElemSz, bool isTailCall, 6890 MachinePointerInfo DstPtrInfo, 6891 MachinePointerInfo SrcPtrInfo) { 6892 // Emit a library call. 6893 TargetLowering::ArgListTy Args; 6894 TargetLowering::ArgListEntry Entry; 6895 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6896 Entry.Node = Dst; 6897 Args.push_back(Entry); 6898 6899 Entry.Node = Src; 6900 Args.push_back(Entry); 6901 6902 Entry.Ty = SizeTy; 6903 Entry.Node = Size; 6904 Args.push_back(Entry); 6905 6906 RTLIB::Libcall LibraryCall = 6907 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6908 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6909 report_fatal_error("Unsupported element size"); 6910 6911 TargetLowering::CallLoweringInfo CLI(*this); 6912 CLI.setDebugLoc(dl) 6913 .setChain(Chain) 6914 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6915 Type::getVoidTy(*getContext()), 6916 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6917 TLI->getPointerTy(getDataLayout())), 6918 std::move(Args)) 6919 .setDiscardResult() 6920 .setTailCall(isTailCall); 6921 6922 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6923 return CallResult.second; 6924 } 6925 6926 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 6927 SDValue Src, SDValue Size, Align Alignment, 6928 bool isVol, bool isTailCall, 6929 MachinePointerInfo DstPtrInfo) { 6930 // Check to see if we should lower the memset to stores first. 6931 // For cases within the target-specified limits, this is the best choice. 6932 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6933 if (ConstantSize) { 6934 // Memset with size zero? Just return the original chain. 6935 if (ConstantSize->isNullValue()) 6936 return Chain; 6937 6938 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 6939 ConstantSize->getZExtValue(), Alignment, 6940 isVol, DstPtrInfo); 6941 6942 if (Result.getNode()) 6943 return Result; 6944 } 6945 6946 // Then check to see if we should lower the memset with target-specific 6947 // code. If the target chooses to do this, this is the next best. 6948 if (TSI) { 6949 SDValue Result = TSI->EmitTargetCodeForMemset( 6950 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 6951 if (Result.getNode()) 6952 return Result; 6953 } 6954 6955 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6956 6957 // Emit a library call. 6958 TargetLowering::ArgListTy Args; 6959 TargetLowering::ArgListEntry Entry; 6960 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 6961 Args.push_back(Entry); 6962 Entry.Node = Src; 6963 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 6964 Args.push_back(Entry); 6965 Entry.Node = Size; 6966 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6967 Args.push_back(Entry); 6968 6969 // FIXME: pass in SDLoc 6970 TargetLowering::CallLoweringInfo CLI(*this); 6971 CLI.setDebugLoc(dl) 6972 .setChain(Chain) 6973 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 6974 Dst.getValueType().getTypeForEVT(*getContext()), 6975 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 6976 TLI->getPointerTy(getDataLayout())), 6977 std::move(Args)) 6978 .setDiscardResult() 6979 .setTailCall(isTailCall); 6980 6981 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6982 return CallResult.second; 6983 } 6984 6985 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 6986 SDValue Dst, unsigned DstAlign, 6987 SDValue Value, SDValue Size, Type *SizeTy, 6988 unsigned ElemSz, bool isTailCall, 6989 MachinePointerInfo DstPtrInfo) { 6990 // Emit a library call. 6991 TargetLowering::ArgListTy Args; 6992 TargetLowering::ArgListEntry Entry; 6993 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6994 Entry.Node = Dst; 6995 Args.push_back(Entry); 6996 6997 Entry.Ty = Type::getInt8Ty(*getContext()); 6998 Entry.Node = Value; 6999 Args.push_back(Entry); 7000 7001 Entry.Ty = SizeTy; 7002 Entry.Node = Size; 7003 Args.push_back(Entry); 7004 7005 RTLIB::Libcall LibraryCall = 7006 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7007 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7008 report_fatal_error("Unsupported element size"); 7009 7010 TargetLowering::CallLoweringInfo CLI(*this); 7011 CLI.setDebugLoc(dl) 7012 .setChain(Chain) 7013 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7014 Type::getVoidTy(*getContext()), 7015 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7016 TLI->getPointerTy(getDataLayout())), 7017 std::move(Args)) 7018 .setDiscardResult() 7019 .setTailCall(isTailCall); 7020 7021 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7022 return CallResult.second; 7023 } 7024 7025 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7026 SDVTList VTList, ArrayRef<SDValue> Ops, 7027 MachineMemOperand *MMO) { 7028 FoldingSetNodeID ID; 7029 ID.AddInteger(MemVT.getRawBits()); 7030 AddNodeIDNode(ID, Opcode, VTList, Ops); 7031 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7032 void* IP = nullptr; 7033 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7034 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7035 return SDValue(E, 0); 7036 } 7037 7038 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7039 VTList, MemVT, MMO); 7040 createOperands(N, Ops); 7041 7042 CSEMap.InsertNode(N, IP); 7043 InsertNode(N); 7044 return SDValue(N, 0); 7045 } 7046 7047 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7048 EVT MemVT, SDVTList VTs, SDValue Chain, 7049 SDValue Ptr, SDValue Cmp, SDValue Swp, 7050 MachineMemOperand *MMO) { 7051 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7052 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7053 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7054 7055 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7056 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7057 } 7058 7059 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7060 SDValue Chain, SDValue Ptr, SDValue Val, 7061 MachineMemOperand *MMO) { 7062 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7063 Opcode == ISD::ATOMIC_LOAD_SUB || 7064 Opcode == ISD::ATOMIC_LOAD_AND || 7065 Opcode == ISD::ATOMIC_LOAD_CLR || 7066 Opcode == ISD::ATOMIC_LOAD_OR || 7067 Opcode == ISD::ATOMIC_LOAD_XOR || 7068 Opcode == ISD::ATOMIC_LOAD_NAND || 7069 Opcode == ISD::ATOMIC_LOAD_MIN || 7070 Opcode == ISD::ATOMIC_LOAD_MAX || 7071 Opcode == ISD::ATOMIC_LOAD_UMIN || 7072 Opcode == ISD::ATOMIC_LOAD_UMAX || 7073 Opcode == ISD::ATOMIC_LOAD_FADD || 7074 Opcode == ISD::ATOMIC_LOAD_FSUB || 7075 Opcode == ISD::ATOMIC_SWAP || 7076 Opcode == ISD::ATOMIC_STORE) && 7077 "Invalid Atomic Op"); 7078 7079 EVT VT = Val.getValueType(); 7080 7081 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7082 getVTList(VT, MVT::Other); 7083 SDValue Ops[] = {Chain, Ptr, Val}; 7084 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7085 } 7086 7087 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7088 EVT VT, SDValue Chain, SDValue Ptr, 7089 MachineMemOperand *MMO) { 7090 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7091 7092 SDVTList VTs = getVTList(VT, MVT::Other); 7093 SDValue Ops[] = {Chain, Ptr}; 7094 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7095 } 7096 7097 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7098 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7099 if (Ops.size() == 1) 7100 return Ops[0]; 7101 7102 SmallVector<EVT, 4> VTs; 7103 VTs.reserve(Ops.size()); 7104 for (const SDValue &Op : Ops) 7105 VTs.push_back(Op.getValueType()); 7106 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7107 } 7108 7109 SDValue SelectionDAG::getMemIntrinsicNode( 7110 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7111 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7112 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7113 if (!Size && MemVT.isScalableVector()) 7114 Size = MemoryLocation::UnknownSize; 7115 else if (!Size) 7116 Size = MemVT.getStoreSize(); 7117 7118 MachineFunction &MF = getMachineFunction(); 7119 MachineMemOperand *MMO = 7120 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7121 7122 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7123 } 7124 7125 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7126 SDVTList VTList, 7127 ArrayRef<SDValue> Ops, EVT MemVT, 7128 MachineMemOperand *MMO) { 7129 assert((Opcode == ISD::INTRINSIC_VOID || 7130 Opcode == ISD::INTRINSIC_W_CHAIN || 7131 Opcode == ISD::PREFETCH || 7132 ((int)Opcode <= std::numeric_limits<int>::max() && 7133 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7134 "Opcode is not a memory-accessing opcode!"); 7135 7136 // Memoize the node unless it returns a flag. 7137 MemIntrinsicSDNode *N; 7138 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7139 FoldingSetNodeID ID; 7140 AddNodeIDNode(ID, Opcode, VTList, Ops); 7141 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7142 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7143 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7144 void *IP = nullptr; 7145 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7146 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7147 return SDValue(E, 0); 7148 } 7149 7150 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7151 VTList, MemVT, MMO); 7152 createOperands(N, Ops); 7153 7154 CSEMap.InsertNode(N, IP); 7155 } else { 7156 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7157 VTList, MemVT, MMO); 7158 createOperands(N, Ops); 7159 } 7160 InsertNode(N); 7161 SDValue V(N, 0); 7162 NewSDValueDbgMsg(V, "Creating new node: ", this); 7163 return V; 7164 } 7165 7166 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7167 SDValue Chain, int FrameIndex, 7168 int64_t Size, int64_t Offset) { 7169 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7170 const auto VTs = getVTList(MVT::Other); 7171 SDValue Ops[2] = { 7172 Chain, 7173 getFrameIndex(FrameIndex, 7174 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7175 true)}; 7176 7177 FoldingSetNodeID ID; 7178 AddNodeIDNode(ID, Opcode, VTs, Ops); 7179 ID.AddInteger(FrameIndex); 7180 ID.AddInteger(Size); 7181 ID.AddInteger(Offset); 7182 void *IP = nullptr; 7183 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7184 return SDValue(E, 0); 7185 7186 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7187 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7188 createOperands(N, Ops); 7189 CSEMap.InsertNode(N, IP); 7190 InsertNode(N); 7191 SDValue V(N, 0); 7192 NewSDValueDbgMsg(V, "Creating new node: ", this); 7193 return V; 7194 } 7195 7196 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7197 uint64_t Guid, uint64_t Index, 7198 uint32_t Attr) { 7199 const unsigned Opcode = ISD::PSEUDO_PROBE; 7200 const auto VTs = getVTList(MVT::Other); 7201 SDValue Ops[] = {Chain}; 7202 FoldingSetNodeID ID; 7203 AddNodeIDNode(ID, Opcode, VTs, Ops); 7204 ID.AddInteger(Guid); 7205 ID.AddInteger(Index); 7206 void *IP = nullptr; 7207 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7208 return SDValue(E, 0); 7209 7210 auto *N = newSDNode<PseudoProbeSDNode>( 7211 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7212 createOperands(N, Ops); 7213 CSEMap.InsertNode(N, IP); 7214 InsertNode(N); 7215 SDValue V(N, 0); 7216 NewSDValueDbgMsg(V, "Creating new node: ", this); 7217 return V; 7218 } 7219 7220 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7221 /// MachinePointerInfo record from it. This is particularly useful because the 7222 /// code generator has many cases where it doesn't bother passing in a 7223 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7224 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7225 SelectionDAG &DAG, SDValue Ptr, 7226 int64_t Offset = 0) { 7227 // If this is FI+Offset, we can model it. 7228 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7229 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7230 FI->getIndex(), Offset); 7231 7232 // If this is (FI+Offset1)+Offset2, we can model it. 7233 if (Ptr.getOpcode() != ISD::ADD || 7234 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7235 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7236 return Info; 7237 7238 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7239 return MachinePointerInfo::getFixedStack( 7240 DAG.getMachineFunction(), FI, 7241 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7242 } 7243 7244 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7245 /// MachinePointerInfo record from it. This is particularly useful because the 7246 /// code generator has many cases where it doesn't bother passing in a 7247 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7248 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7249 SelectionDAG &DAG, SDValue Ptr, 7250 SDValue OffsetOp) { 7251 // If the 'Offset' value isn't a constant, we can't handle this. 7252 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7253 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7254 if (OffsetOp.isUndef()) 7255 return InferPointerInfo(Info, DAG, Ptr); 7256 return Info; 7257 } 7258 7259 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7260 EVT VT, const SDLoc &dl, SDValue Chain, 7261 SDValue Ptr, SDValue Offset, 7262 MachinePointerInfo PtrInfo, EVT MemVT, 7263 Align Alignment, 7264 MachineMemOperand::Flags MMOFlags, 7265 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7266 assert(Chain.getValueType() == MVT::Other && 7267 "Invalid chain type"); 7268 7269 MMOFlags |= MachineMemOperand::MOLoad; 7270 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7271 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7272 // clients. 7273 if (PtrInfo.V.isNull()) 7274 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7275 7276 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7277 MachineFunction &MF = getMachineFunction(); 7278 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7279 Alignment, AAInfo, Ranges); 7280 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7281 } 7282 7283 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7284 EVT VT, const SDLoc &dl, SDValue Chain, 7285 SDValue Ptr, SDValue Offset, EVT MemVT, 7286 MachineMemOperand *MMO) { 7287 if (VT == MemVT) { 7288 ExtType = ISD::NON_EXTLOAD; 7289 } else if (ExtType == ISD::NON_EXTLOAD) { 7290 assert(VT == MemVT && "Non-extending load from different memory type!"); 7291 } else { 7292 // Extending load. 7293 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7294 "Should only be an extending load, not truncating!"); 7295 assert(VT.isInteger() == MemVT.isInteger() && 7296 "Cannot convert from FP to Int or Int -> FP!"); 7297 assert(VT.isVector() == MemVT.isVector() && 7298 "Cannot use an ext load to convert to or from a vector!"); 7299 assert((!VT.isVector() || 7300 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7301 "Cannot use an ext load to change the number of vector elements!"); 7302 } 7303 7304 bool Indexed = AM != ISD::UNINDEXED; 7305 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7306 7307 SDVTList VTs = Indexed ? 7308 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7309 SDValue Ops[] = { Chain, Ptr, Offset }; 7310 FoldingSetNodeID ID; 7311 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7312 ID.AddInteger(MemVT.getRawBits()); 7313 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7314 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7315 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7316 void *IP = nullptr; 7317 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7318 cast<LoadSDNode>(E)->refineAlignment(MMO); 7319 return SDValue(E, 0); 7320 } 7321 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7322 ExtType, MemVT, MMO); 7323 createOperands(N, Ops); 7324 7325 CSEMap.InsertNode(N, IP); 7326 InsertNode(N); 7327 SDValue V(N, 0); 7328 NewSDValueDbgMsg(V, "Creating new node: ", this); 7329 return V; 7330 } 7331 7332 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7333 SDValue Ptr, MachinePointerInfo PtrInfo, 7334 MaybeAlign Alignment, 7335 MachineMemOperand::Flags MMOFlags, 7336 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7337 SDValue Undef = getUNDEF(Ptr.getValueType()); 7338 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7339 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7340 } 7341 7342 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7343 SDValue Ptr, MachineMemOperand *MMO) { 7344 SDValue Undef = getUNDEF(Ptr.getValueType()); 7345 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7346 VT, MMO); 7347 } 7348 7349 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7350 EVT VT, SDValue Chain, SDValue Ptr, 7351 MachinePointerInfo PtrInfo, EVT MemVT, 7352 MaybeAlign Alignment, 7353 MachineMemOperand::Flags MMOFlags, 7354 const AAMDNodes &AAInfo) { 7355 SDValue Undef = getUNDEF(Ptr.getValueType()); 7356 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7357 MemVT, Alignment, MMOFlags, AAInfo); 7358 } 7359 7360 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7361 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7362 MachineMemOperand *MMO) { 7363 SDValue Undef = getUNDEF(Ptr.getValueType()); 7364 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7365 MemVT, MMO); 7366 } 7367 7368 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7369 SDValue Base, SDValue Offset, 7370 ISD::MemIndexedMode AM) { 7371 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7372 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7373 // Don't propagate the invariant or dereferenceable flags. 7374 auto MMOFlags = 7375 LD->getMemOperand()->getFlags() & 7376 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7377 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7378 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7379 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7380 } 7381 7382 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7383 SDValue Ptr, MachinePointerInfo PtrInfo, 7384 Align Alignment, 7385 MachineMemOperand::Flags MMOFlags, 7386 const AAMDNodes &AAInfo) { 7387 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7388 7389 MMOFlags |= MachineMemOperand::MOStore; 7390 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7391 7392 if (PtrInfo.V.isNull()) 7393 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7394 7395 MachineFunction &MF = getMachineFunction(); 7396 uint64_t Size = 7397 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7398 MachineMemOperand *MMO = 7399 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7400 return getStore(Chain, dl, Val, Ptr, MMO); 7401 } 7402 7403 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7404 SDValue Ptr, MachineMemOperand *MMO) { 7405 assert(Chain.getValueType() == MVT::Other && 7406 "Invalid chain type"); 7407 EVT VT = Val.getValueType(); 7408 SDVTList VTs = getVTList(MVT::Other); 7409 SDValue Undef = getUNDEF(Ptr.getValueType()); 7410 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7411 FoldingSetNodeID ID; 7412 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7413 ID.AddInteger(VT.getRawBits()); 7414 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7415 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7416 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7417 void *IP = nullptr; 7418 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7419 cast<StoreSDNode>(E)->refineAlignment(MMO); 7420 return SDValue(E, 0); 7421 } 7422 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7423 ISD::UNINDEXED, false, VT, MMO); 7424 createOperands(N, Ops); 7425 7426 CSEMap.InsertNode(N, IP); 7427 InsertNode(N); 7428 SDValue V(N, 0); 7429 NewSDValueDbgMsg(V, "Creating new node: ", this); 7430 return V; 7431 } 7432 7433 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7434 SDValue Ptr, MachinePointerInfo PtrInfo, 7435 EVT SVT, Align Alignment, 7436 MachineMemOperand::Flags MMOFlags, 7437 const AAMDNodes &AAInfo) { 7438 assert(Chain.getValueType() == MVT::Other && 7439 "Invalid chain type"); 7440 7441 MMOFlags |= MachineMemOperand::MOStore; 7442 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7443 7444 if (PtrInfo.V.isNull()) 7445 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7446 7447 MachineFunction &MF = getMachineFunction(); 7448 MachineMemOperand *MMO = MF.getMachineMemOperand( 7449 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7450 Alignment, AAInfo); 7451 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7452 } 7453 7454 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7455 SDValue Ptr, EVT SVT, 7456 MachineMemOperand *MMO) { 7457 EVT VT = Val.getValueType(); 7458 7459 assert(Chain.getValueType() == MVT::Other && 7460 "Invalid chain type"); 7461 if (VT == SVT) 7462 return getStore(Chain, dl, Val, Ptr, MMO); 7463 7464 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7465 "Should only be a truncating store, not extending!"); 7466 assert(VT.isInteger() == SVT.isInteger() && 7467 "Can't do FP-INT conversion!"); 7468 assert(VT.isVector() == SVT.isVector() && 7469 "Cannot use trunc store to convert to or from a vector!"); 7470 assert((!VT.isVector() || 7471 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7472 "Cannot use trunc store to change the number of vector elements!"); 7473 7474 SDVTList VTs = getVTList(MVT::Other); 7475 SDValue Undef = getUNDEF(Ptr.getValueType()); 7476 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7477 FoldingSetNodeID ID; 7478 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7479 ID.AddInteger(SVT.getRawBits()); 7480 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7481 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7482 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7483 void *IP = nullptr; 7484 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7485 cast<StoreSDNode>(E)->refineAlignment(MMO); 7486 return SDValue(E, 0); 7487 } 7488 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7489 ISD::UNINDEXED, true, SVT, MMO); 7490 createOperands(N, Ops); 7491 7492 CSEMap.InsertNode(N, IP); 7493 InsertNode(N); 7494 SDValue V(N, 0); 7495 NewSDValueDbgMsg(V, "Creating new node: ", this); 7496 return V; 7497 } 7498 7499 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7500 SDValue Base, SDValue Offset, 7501 ISD::MemIndexedMode AM) { 7502 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7503 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7504 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7505 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7506 FoldingSetNodeID ID; 7507 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7508 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7509 ID.AddInteger(ST->getRawSubclassData()); 7510 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7511 void *IP = nullptr; 7512 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7513 return SDValue(E, 0); 7514 7515 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7516 ST->isTruncatingStore(), ST->getMemoryVT(), 7517 ST->getMemOperand()); 7518 createOperands(N, Ops); 7519 7520 CSEMap.InsertNode(N, IP); 7521 InsertNode(N); 7522 SDValue V(N, 0); 7523 NewSDValueDbgMsg(V, "Creating new node: ", this); 7524 return V; 7525 } 7526 7527 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7528 SDValue Base, SDValue Offset, SDValue Mask, 7529 SDValue PassThru, EVT MemVT, 7530 MachineMemOperand *MMO, 7531 ISD::MemIndexedMode AM, 7532 ISD::LoadExtType ExtTy, bool isExpanding) { 7533 bool Indexed = AM != ISD::UNINDEXED; 7534 assert((Indexed || Offset.isUndef()) && 7535 "Unindexed masked load with an offset!"); 7536 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 7537 : getVTList(VT, MVT::Other); 7538 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 7539 FoldingSetNodeID ID; 7540 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 7541 ID.AddInteger(MemVT.getRawBits()); 7542 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 7543 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 7544 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7545 void *IP = nullptr; 7546 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7547 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 7548 return SDValue(E, 0); 7549 } 7550 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7551 AM, ExtTy, isExpanding, MemVT, MMO); 7552 createOperands(N, Ops); 7553 7554 CSEMap.InsertNode(N, IP); 7555 InsertNode(N); 7556 SDValue V(N, 0); 7557 NewSDValueDbgMsg(V, "Creating new node: ", this); 7558 return V; 7559 } 7560 7561 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 7562 SDValue Base, SDValue Offset, 7563 ISD::MemIndexedMode AM) { 7564 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 7565 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 7566 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 7567 Offset, LD->getMask(), LD->getPassThru(), 7568 LD->getMemoryVT(), LD->getMemOperand(), AM, 7569 LD->getExtensionType(), LD->isExpandingLoad()); 7570 } 7571 7572 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 7573 SDValue Val, SDValue Base, SDValue Offset, 7574 SDValue Mask, EVT MemVT, 7575 MachineMemOperand *MMO, 7576 ISD::MemIndexedMode AM, bool IsTruncating, 7577 bool IsCompressing) { 7578 assert(Chain.getValueType() == MVT::Other && 7579 "Invalid chain type"); 7580 bool Indexed = AM != ISD::UNINDEXED; 7581 assert((Indexed || Offset.isUndef()) && 7582 "Unindexed masked store with an offset!"); 7583 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 7584 : getVTList(MVT::Other); 7585 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 7586 FoldingSetNodeID ID; 7587 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 7588 ID.AddInteger(MemVT.getRawBits()); 7589 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 7590 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7591 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7592 void *IP = nullptr; 7593 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7594 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 7595 return SDValue(E, 0); 7596 } 7597 auto *N = 7598 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7599 IsTruncating, IsCompressing, MemVT, MMO); 7600 createOperands(N, Ops); 7601 7602 CSEMap.InsertNode(N, IP); 7603 InsertNode(N); 7604 SDValue V(N, 0); 7605 NewSDValueDbgMsg(V, "Creating new node: ", this); 7606 return V; 7607 } 7608 7609 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 7610 SDValue Base, SDValue Offset, 7611 ISD::MemIndexedMode AM) { 7612 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 7613 assert(ST->getOffset().isUndef() && 7614 "Masked store is already a indexed store!"); 7615 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 7616 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 7617 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 7618 } 7619 7620 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl, 7621 ArrayRef<SDValue> Ops, 7622 MachineMemOperand *MMO, 7623 ISD::MemIndexType IndexType, 7624 ISD::LoadExtType ExtTy) { 7625 assert(Ops.size() == 6 && "Incompatible number of operands"); 7626 7627 FoldingSetNodeID ID; 7628 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 7629 ID.AddInteger(VT.getRawBits()); 7630 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 7631 dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy)); 7632 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7633 void *IP = nullptr; 7634 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7635 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 7636 return SDValue(E, 0); 7637 } 7638 7639 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7640 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7641 VTs, VT, MMO, IndexType, ExtTy); 7642 createOperands(N, Ops); 7643 7644 assert(N->getPassThru().getValueType() == N->getValueType(0) && 7645 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 7646 assert(N->getMask().getValueType().getVectorElementCount() == 7647 N->getValueType(0).getVectorElementCount() && 7648 "Vector width mismatch between mask and data"); 7649 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7650 N->getValueType(0).getVectorElementCount().isScalable() && 7651 "Scalable flags of index and data do not match"); 7652 assert(ElementCount::isKnownGE( 7653 N->getIndex().getValueType().getVectorElementCount(), 7654 N->getValueType(0).getVectorElementCount()) && 7655 "Vector width mismatch between index and data"); 7656 assert(isa<ConstantSDNode>(N->getScale()) && 7657 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7658 "Scale should be a constant power of 2"); 7659 7660 CSEMap.InsertNode(N, IP); 7661 InsertNode(N); 7662 SDValue V(N, 0); 7663 NewSDValueDbgMsg(V, "Creating new node: ", this); 7664 return V; 7665 } 7666 7667 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl, 7668 ArrayRef<SDValue> Ops, 7669 MachineMemOperand *MMO, 7670 ISD::MemIndexType IndexType, 7671 bool IsTrunc) { 7672 assert(Ops.size() == 6 && "Incompatible number of operands"); 7673 7674 FoldingSetNodeID ID; 7675 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 7676 ID.AddInteger(VT.getRawBits()); 7677 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 7678 dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc)); 7679 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7680 void *IP = nullptr; 7681 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7682 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 7683 return SDValue(E, 0); 7684 } 7685 7686 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7687 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7688 VTs, VT, MMO, IndexType, IsTrunc); 7689 createOperands(N, Ops); 7690 7691 assert(N->getMask().getValueType().getVectorElementCount() == 7692 N->getValue().getValueType().getVectorElementCount() && 7693 "Vector width mismatch between mask and data"); 7694 assert( 7695 N->getIndex().getValueType().getVectorElementCount().isScalable() == 7696 N->getValue().getValueType().getVectorElementCount().isScalable() && 7697 "Scalable flags of index and data do not match"); 7698 assert(ElementCount::isKnownGE( 7699 N->getIndex().getValueType().getVectorElementCount(), 7700 N->getValue().getValueType().getVectorElementCount()) && 7701 "Vector width mismatch between index and data"); 7702 assert(isa<ConstantSDNode>(N->getScale()) && 7703 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7704 "Scale should be a constant power of 2"); 7705 7706 CSEMap.InsertNode(N, IP); 7707 InsertNode(N); 7708 SDValue V(N, 0); 7709 NewSDValueDbgMsg(V, "Creating new node: ", this); 7710 return V; 7711 } 7712 7713 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 7714 // select undef, T, F --> T (if T is a constant), otherwise F 7715 // select, ?, undef, F --> F 7716 // select, ?, T, undef --> T 7717 if (Cond.isUndef()) 7718 return isConstantValueOfAnyType(T) ? T : F; 7719 if (T.isUndef()) 7720 return F; 7721 if (F.isUndef()) 7722 return T; 7723 7724 // select true, T, F --> T 7725 // select false, T, F --> F 7726 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 7727 return CondC->isNullValue() ? F : T; 7728 7729 // TODO: This should simplify VSELECT with constant condition using something 7730 // like this (but check boolean contents to be complete?): 7731 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 7732 // return T; 7733 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 7734 // return F; 7735 7736 // select ?, T, T --> T 7737 if (T == F) 7738 return T; 7739 7740 return SDValue(); 7741 } 7742 7743 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 7744 // shift undef, Y --> 0 (can always assume that the undef value is 0) 7745 if (X.isUndef()) 7746 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 7747 // shift X, undef --> undef (because it may shift by the bitwidth) 7748 if (Y.isUndef()) 7749 return getUNDEF(X.getValueType()); 7750 7751 // shift 0, Y --> 0 7752 // shift X, 0 --> X 7753 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 7754 return X; 7755 7756 // shift X, C >= bitwidth(X) --> undef 7757 // All vector elements must be too big (or undef) to avoid partial undefs. 7758 auto isShiftTooBig = [X](ConstantSDNode *Val) { 7759 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 7760 }; 7761 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 7762 return getUNDEF(X.getValueType()); 7763 7764 return SDValue(); 7765 } 7766 7767 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 7768 SDNodeFlags Flags) { 7769 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 7770 // (an undef operand can be chosen to be Nan/Inf), then the result of this 7771 // operation is poison. That result can be relaxed to undef. 7772 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 7773 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 7774 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 7775 (YC && YC->getValueAPF().isNaN()); 7776 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 7777 (YC && YC->getValueAPF().isInfinity()); 7778 7779 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 7780 return getUNDEF(X.getValueType()); 7781 7782 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 7783 return getUNDEF(X.getValueType()); 7784 7785 if (!YC) 7786 return SDValue(); 7787 7788 // X + -0.0 --> X 7789 if (Opcode == ISD::FADD) 7790 if (YC->getValueAPF().isNegZero()) 7791 return X; 7792 7793 // X - +0.0 --> X 7794 if (Opcode == ISD::FSUB) 7795 if (YC->getValueAPF().isPosZero()) 7796 return X; 7797 7798 // X * 1.0 --> X 7799 // X / 1.0 --> X 7800 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 7801 if (YC->getValueAPF().isExactlyValue(1.0)) 7802 return X; 7803 7804 // X * 0.0 --> 0.0 7805 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 7806 if (YC->getValueAPF().isZero()) 7807 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 7808 7809 return SDValue(); 7810 } 7811 7812 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 7813 SDValue Ptr, SDValue SV, unsigned Align) { 7814 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 7815 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 7816 } 7817 7818 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7819 ArrayRef<SDUse> Ops) { 7820 switch (Ops.size()) { 7821 case 0: return getNode(Opcode, DL, VT); 7822 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 7823 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 7824 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 7825 default: break; 7826 } 7827 7828 // Copy from an SDUse array into an SDValue array for use with 7829 // the regular getNode logic. 7830 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 7831 return getNode(Opcode, DL, VT, NewOps); 7832 } 7833 7834 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7835 ArrayRef<SDValue> Ops) { 7836 SDNodeFlags Flags; 7837 if (Inserter) 7838 Flags = Inserter->getFlags(); 7839 return getNode(Opcode, DL, VT, Ops, Flags); 7840 } 7841 7842 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7843 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7844 unsigned NumOps = Ops.size(); 7845 switch (NumOps) { 7846 case 0: return getNode(Opcode, DL, VT); 7847 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 7848 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 7849 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 7850 default: break; 7851 } 7852 7853 #ifndef NDEBUG 7854 for (auto &Op : Ops) 7855 assert(Op.getOpcode() != ISD::DELETED_NODE && 7856 "Operand is DELETED_NODE!"); 7857 #endif 7858 7859 switch (Opcode) { 7860 default: break; 7861 case ISD::BUILD_VECTOR: 7862 // Attempt to simplify BUILD_VECTOR. 7863 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 7864 return V; 7865 break; 7866 case ISD::CONCAT_VECTORS: 7867 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 7868 return V; 7869 break; 7870 case ISD::SELECT_CC: 7871 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 7872 assert(Ops[0].getValueType() == Ops[1].getValueType() && 7873 "LHS and RHS of condition must have same type!"); 7874 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7875 "True and False arms of SelectCC must have same type!"); 7876 assert(Ops[2].getValueType() == VT && 7877 "select_cc node must be of same type as true and false value!"); 7878 break; 7879 case ISD::BR_CC: 7880 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 7881 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7882 "LHS/RHS of comparison should match types!"); 7883 break; 7884 } 7885 7886 // Memoize nodes. 7887 SDNode *N; 7888 SDVTList VTs = getVTList(VT); 7889 7890 if (VT != MVT::Glue) { 7891 FoldingSetNodeID ID; 7892 AddNodeIDNode(ID, Opcode, VTs, Ops); 7893 void *IP = nullptr; 7894 7895 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7896 return SDValue(E, 0); 7897 7898 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7899 createOperands(N, Ops); 7900 7901 CSEMap.InsertNode(N, IP); 7902 } else { 7903 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7904 createOperands(N, Ops); 7905 } 7906 7907 N->setFlags(Flags); 7908 InsertNode(N); 7909 SDValue V(N, 0); 7910 NewSDValueDbgMsg(V, "Creating new node: ", this); 7911 return V; 7912 } 7913 7914 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7915 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 7916 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 7917 } 7918 7919 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7920 ArrayRef<SDValue> Ops) { 7921 SDNodeFlags Flags; 7922 if (Inserter) 7923 Flags = Inserter->getFlags(); 7924 return getNode(Opcode, DL, VTList, Ops, Flags); 7925 } 7926 7927 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7928 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7929 if (VTList.NumVTs == 1) 7930 return getNode(Opcode, DL, VTList.VTs[0], Ops); 7931 7932 #ifndef NDEBUG 7933 for (auto &Op : Ops) 7934 assert(Op.getOpcode() != ISD::DELETED_NODE && 7935 "Operand is DELETED_NODE!"); 7936 #endif 7937 7938 switch (Opcode) { 7939 case ISD::STRICT_FP_EXTEND: 7940 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 7941 "Invalid STRICT_FP_EXTEND!"); 7942 assert(VTList.VTs[0].isFloatingPoint() && 7943 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 7944 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7945 "STRICT_FP_EXTEND result type should be vector iff the operand " 7946 "type is vector!"); 7947 assert((!VTList.VTs[0].isVector() || 7948 VTList.VTs[0].getVectorNumElements() == 7949 Ops[1].getValueType().getVectorNumElements()) && 7950 "Vector element count mismatch!"); 7951 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 7952 "Invalid fpext node, dst <= src!"); 7953 break; 7954 case ISD::STRICT_FP_ROUND: 7955 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 7956 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7957 "STRICT_FP_ROUND result type should be vector iff the operand " 7958 "type is vector!"); 7959 assert((!VTList.VTs[0].isVector() || 7960 VTList.VTs[0].getVectorNumElements() == 7961 Ops[1].getValueType().getVectorNumElements()) && 7962 "Vector element count mismatch!"); 7963 assert(VTList.VTs[0].isFloatingPoint() && 7964 Ops[1].getValueType().isFloatingPoint() && 7965 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 7966 isa<ConstantSDNode>(Ops[2]) && 7967 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 7968 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 7969 "Invalid STRICT_FP_ROUND!"); 7970 break; 7971 #if 0 7972 // FIXME: figure out how to safely handle things like 7973 // int foo(int x) { return 1 << (x & 255); } 7974 // int bar() { return foo(256); } 7975 case ISD::SRA_PARTS: 7976 case ISD::SRL_PARTS: 7977 case ISD::SHL_PARTS: 7978 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 7979 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 7980 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7981 else if (N3.getOpcode() == ISD::AND) 7982 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 7983 // If the and is only masking out bits that cannot effect the shift, 7984 // eliminate the and. 7985 unsigned NumBits = VT.getScalarSizeInBits()*2; 7986 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 7987 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7988 } 7989 break; 7990 #endif 7991 } 7992 7993 // Memoize the node unless it returns a flag. 7994 SDNode *N; 7995 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7996 FoldingSetNodeID ID; 7997 AddNodeIDNode(ID, Opcode, VTList, Ops); 7998 void *IP = nullptr; 7999 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8000 return SDValue(E, 0); 8001 8002 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8003 createOperands(N, Ops); 8004 CSEMap.InsertNode(N, IP); 8005 } else { 8006 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8007 createOperands(N, Ops); 8008 } 8009 8010 N->setFlags(Flags); 8011 InsertNode(N); 8012 SDValue V(N, 0); 8013 NewSDValueDbgMsg(V, "Creating new node: ", this); 8014 return V; 8015 } 8016 8017 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8018 SDVTList VTList) { 8019 return getNode(Opcode, DL, VTList, None); 8020 } 8021 8022 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8023 SDValue N1) { 8024 SDValue Ops[] = { N1 }; 8025 return getNode(Opcode, DL, VTList, Ops); 8026 } 8027 8028 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8029 SDValue N1, SDValue N2) { 8030 SDValue Ops[] = { N1, N2 }; 8031 return getNode(Opcode, DL, VTList, Ops); 8032 } 8033 8034 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8035 SDValue N1, SDValue N2, SDValue N3) { 8036 SDValue Ops[] = { N1, N2, N3 }; 8037 return getNode(Opcode, DL, VTList, Ops); 8038 } 8039 8040 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8041 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8042 SDValue Ops[] = { N1, N2, N3, N4 }; 8043 return getNode(Opcode, DL, VTList, Ops); 8044 } 8045 8046 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8047 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8048 SDValue N5) { 8049 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8050 return getNode(Opcode, DL, VTList, Ops); 8051 } 8052 8053 SDVTList SelectionDAG::getVTList(EVT VT) { 8054 return makeVTList(SDNode::getValueTypeList(VT), 1); 8055 } 8056 8057 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8058 FoldingSetNodeID ID; 8059 ID.AddInteger(2U); 8060 ID.AddInteger(VT1.getRawBits()); 8061 ID.AddInteger(VT2.getRawBits()); 8062 8063 void *IP = nullptr; 8064 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8065 if (!Result) { 8066 EVT *Array = Allocator.Allocate<EVT>(2); 8067 Array[0] = VT1; 8068 Array[1] = VT2; 8069 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8070 VTListMap.InsertNode(Result, IP); 8071 } 8072 return Result->getSDVTList(); 8073 } 8074 8075 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 8076 FoldingSetNodeID ID; 8077 ID.AddInteger(3U); 8078 ID.AddInteger(VT1.getRawBits()); 8079 ID.AddInteger(VT2.getRawBits()); 8080 ID.AddInteger(VT3.getRawBits()); 8081 8082 void *IP = nullptr; 8083 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8084 if (!Result) { 8085 EVT *Array = Allocator.Allocate<EVT>(3); 8086 Array[0] = VT1; 8087 Array[1] = VT2; 8088 Array[2] = VT3; 8089 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 8090 VTListMap.InsertNode(Result, IP); 8091 } 8092 return Result->getSDVTList(); 8093 } 8094 8095 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 8096 FoldingSetNodeID ID; 8097 ID.AddInteger(4U); 8098 ID.AddInteger(VT1.getRawBits()); 8099 ID.AddInteger(VT2.getRawBits()); 8100 ID.AddInteger(VT3.getRawBits()); 8101 ID.AddInteger(VT4.getRawBits()); 8102 8103 void *IP = nullptr; 8104 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8105 if (!Result) { 8106 EVT *Array = Allocator.Allocate<EVT>(4); 8107 Array[0] = VT1; 8108 Array[1] = VT2; 8109 Array[2] = VT3; 8110 Array[3] = VT4; 8111 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 8112 VTListMap.InsertNode(Result, IP); 8113 } 8114 return Result->getSDVTList(); 8115 } 8116 8117 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 8118 unsigned NumVTs = VTs.size(); 8119 FoldingSetNodeID ID; 8120 ID.AddInteger(NumVTs); 8121 for (unsigned index = 0; index < NumVTs; index++) { 8122 ID.AddInteger(VTs[index].getRawBits()); 8123 } 8124 8125 void *IP = nullptr; 8126 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8127 if (!Result) { 8128 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 8129 llvm::copy(VTs, Array); 8130 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 8131 VTListMap.InsertNode(Result, IP); 8132 } 8133 return Result->getSDVTList(); 8134 } 8135 8136 8137 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 8138 /// specified operands. If the resultant node already exists in the DAG, 8139 /// this does not modify the specified node, instead it returns the node that 8140 /// already exists. If the resultant node does not exist in the DAG, the 8141 /// input node is returned. As a degenerate case, if you specify the same 8142 /// input operands as the node already has, the input node is returned. 8143 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 8144 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 8145 8146 // Check to see if there is no change. 8147 if (Op == N->getOperand(0)) return N; 8148 8149 // See if the modified node already exists. 8150 void *InsertPos = nullptr; 8151 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 8152 return Existing; 8153 8154 // Nope it doesn't. Remove the node from its current place in the maps. 8155 if (InsertPos) 8156 if (!RemoveNodeFromCSEMaps(N)) 8157 InsertPos = nullptr; 8158 8159 // Now we update the operands. 8160 N->OperandList[0].set(Op); 8161 8162 updateDivergence(N); 8163 // If this gets put into a CSE map, add it. 8164 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8165 return N; 8166 } 8167 8168 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 8169 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 8170 8171 // Check to see if there is no change. 8172 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 8173 return N; // No operands changed, just return the input node. 8174 8175 // See if the modified node already exists. 8176 void *InsertPos = nullptr; 8177 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 8178 return Existing; 8179 8180 // Nope it doesn't. Remove the node from its current place in the maps. 8181 if (InsertPos) 8182 if (!RemoveNodeFromCSEMaps(N)) 8183 InsertPos = nullptr; 8184 8185 // Now we update the operands. 8186 if (N->OperandList[0] != Op1) 8187 N->OperandList[0].set(Op1); 8188 if (N->OperandList[1] != Op2) 8189 N->OperandList[1].set(Op2); 8190 8191 updateDivergence(N); 8192 // If this gets put into a CSE map, add it. 8193 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8194 return N; 8195 } 8196 8197 SDNode *SelectionDAG:: 8198 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 8199 SDValue Ops[] = { Op1, Op2, Op3 }; 8200 return UpdateNodeOperands(N, Ops); 8201 } 8202 8203 SDNode *SelectionDAG:: 8204 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8205 SDValue Op3, SDValue Op4) { 8206 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 8207 return UpdateNodeOperands(N, Ops); 8208 } 8209 8210 SDNode *SelectionDAG:: 8211 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8212 SDValue Op3, SDValue Op4, SDValue Op5) { 8213 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 8214 return UpdateNodeOperands(N, Ops); 8215 } 8216 8217 SDNode *SelectionDAG:: 8218 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 8219 unsigned NumOps = Ops.size(); 8220 assert(N->getNumOperands() == NumOps && 8221 "Update with wrong number of operands"); 8222 8223 // If no operands changed just return the input node. 8224 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 8225 return N; 8226 8227 // See if the modified node already exists. 8228 void *InsertPos = nullptr; 8229 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8230 return Existing; 8231 8232 // Nope it doesn't. Remove the node from its current place in the maps. 8233 if (InsertPos) 8234 if (!RemoveNodeFromCSEMaps(N)) 8235 InsertPos = nullptr; 8236 8237 // Now we update the operands. 8238 for (unsigned i = 0; i != NumOps; ++i) 8239 if (N->OperandList[i] != Ops[i]) 8240 N->OperandList[i].set(Ops[i]); 8241 8242 updateDivergence(N); 8243 // If this gets put into a CSE map, add it. 8244 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8245 return N; 8246 } 8247 8248 /// DropOperands - Release the operands and set this node to have 8249 /// zero operands. 8250 void SDNode::DropOperands() { 8251 // Unlike the code in MorphNodeTo that does this, we don't need to 8252 // watch for dead nodes here. 8253 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8254 SDUse &Use = *I++; 8255 Use.set(SDValue()); 8256 } 8257 } 8258 8259 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8260 ArrayRef<MachineMemOperand *> NewMemRefs) { 8261 if (NewMemRefs.empty()) { 8262 N->clearMemRefs(); 8263 return; 8264 } 8265 8266 // Check if we can avoid allocating by storing a single reference directly. 8267 if (NewMemRefs.size() == 1) { 8268 N->MemRefs = NewMemRefs[0]; 8269 N->NumMemRefs = 1; 8270 return; 8271 } 8272 8273 MachineMemOperand **MemRefsBuffer = 8274 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8275 llvm::copy(NewMemRefs, MemRefsBuffer); 8276 N->MemRefs = MemRefsBuffer; 8277 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8278 } 8279 8280 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8281 /// machine opcode. 8282 /// 8283 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8284 EVT VT) { 8285 SDVTList VTs = getVTList(VT); 8286 return SelectNodeTo(N, MachineOpc, VTs, None); 8287 } 8288 8289 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8290 EVT VT, SDValue Op1) { 8291 SDVTList VTs = getVTList(VT); 8292 SDValue Ops[] = { Op1 }; 8293 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8294 } 8295 8296 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8297 EVT VT, SDValue Op1, 8298 SDValue Op2) { 8299 SDVTList VTs = getVTList(VT); 8300 SDValue Ops[] = { Op1, Op2 }; 8301 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8302 } 8303 8304 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8305 EVT VT, SDValue Op1, 8306 SDValue Op2, SDValue Op3) { 8307 SDVTList VTs = getVTList(VT); 8308 SDValue Ops[] = { Op1, Op2, Op3 }; 8309 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8310 } 8311 8312 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8313 EVT VT, ArrayRef<SDValue> Ops) { 8314 SDVTList VTs = getVTList(VT); 8315 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8316 } 8317 8318 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8319 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8320 SDVTList VTs = getVTList(VT1, VT2); 8321 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8322 } 8323 8324 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8325 EVT VT1, EVT VT2) { 8326 SDVTList VTs = getVTList(VT1, VT2); 8327 return SelectNodeTo(N, MachineOpc, VTs, None); 8328 } 8329 8330 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8331 EVT VT1, EVT VT2, EVT VT3, 8332 ArrayRef<SDValue> Ops) { 8333 SDVTList VTs = getVTList(VT1, VT2, VT3); 8334 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8335 } 8336 8337 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8338 EVT VT1, EVT VT2, 8339 SDValue Op1, SDValue Op2) { 8340 SDVTList VTs = getVTList(VT1, VT2); 8341 SDValue Ops[] = { Op1, Op2 }; 8342 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8343 } 8344 8345 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8346 SDVTList VTs,ArrayRef<SDValue> Ops) { 8347 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8348 // Reset the NodeID to -1. 8349 New->setNodeId(-1); 8350 if (New != N) { 8351 ReplaceAllUsesWith(N, New); 8352 RemoveDeadNode(N); 8353 } 8354 return New; 8355 } 8356 8357 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8358 /// the line number information on the merged node since it is not possible to 8359 /// preserve the information that operation is associated with multiple lines. 8360 /// This will make the debugger working better at -O0, were there is a higher 8361 /// probability having other instructions associated with that line. 8362 /// 8363 /// For IROrder, we keep the smaller of the two 8364 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8365 DebugLoc NLoc = N->getDebugLoc(); 8366 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8367 N->setDebugLoc(DebugLoc()); 8368 } 8369 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8370 N->setIROrder(Order); 8371 return N; 8372 } 8373 8374 /// MorphNodeTo - This *mutates* the specified node to have the specified 8375 /// return type, opcode, and operands. 8376 /// 8377 /// Note that MorphNodeTo returns the resultant node. If there is already a 8378 /// node of the specified opcode and operands, it returns that node instead of 8379 /// the current one. Note that the SDLoc need not be the same. 8380 /// 8381 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8382 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8383 /// node, and because it doesn't require CSE recalculation for any of 8384 /// the node's users. 8385 /// 8386 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8387 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8388 /// the legalizer which maintain worklists that would need to be updated when 8389 /// deleting things. 8390 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8391 SDVTList VTs, ArrayRef<SDValue> Ops) { 8392 // If an identical node already exists, use it. 8393 void *IP = nullptr; 8394 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8395 FoldingSetNodeID ID; 8396 AddNodeIDNode(ID, Opc, VTs, Ops); 8397 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8398 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8399 } 8400 8401 if (!RemoveNodeFromCSEMaps(N)) 8402 IP = nullptr; 8403 8404 // Start the morphing. 8405 N->NodeType = Opc; 8406 N->ValueList = VTs.VTs; 8407 N->NumValues = VTs.NumVTs; 8408 8409 // Clear the operands list, updating used nodes to remove this from their 8410 // use list. Keep track of any operands that become dead as a result. 8411 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8412 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8413 SDUse &Use = *I++; 8414 SDNode *Used = Use.getNode(); 8415 Use.set(SDValue()); 8416 if (Used->use_empty()) 8417 DeadNodeSet.insert(Used); 8418 } 8419 8420 // For MachineNode, initialize the memory references information. 8421 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8422 MN->clearMemRefs(); 8423 8424 // Swap for an appropriately sized array from the recycler. 8425 removeOperands(N); 8426 createOperands(N, Ops); 8427 8428 // Delete any nodes that are still dead after adding the uses for the 8429 // new operands. 8430 if (!DeadNodeSet.empty()) { 8431 SmallVector<SDNode *, 16> DeadNodes; 8432 for (SDNode *N : DeadNodeSet) 8433 if (N->use_empty()) 8434 DeadNodes.push_back(N); 8435 RemoveDeadNodes(DeadNodes); 8436 } 8437 8438 if (IP) 8439 CSEMap.InsertNode(N, IP); // Memoize the new node. 8440 return N; 8441 } 8442 8443 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8444 unsigned OrigOpc = Node->getOpcode(); 8445 unsigned NewOpc; 8446 switch (OrigOpc) { 8447 default: 8448 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8449 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8450 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8451 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8452 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8453 #include "llvm/IR/ConstrainedOps.def" 8454 } 8455 8456 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8457 8458 // We're taking this node out of the chain, so we need to re-link things. 8459 SDValue InputChain = Node->getOperand(0); 8460 SDValue OutputChain = SDValue(Node, 1); 8461 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8462 8463 SmallVector<SDValue, 3> Ops; 8464 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8465 Ops.push_back(Node->getOperand(i)); 8466 8467 SDVTList VTs = getVTList(Node->getValueType(0)); 8468 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8469 8470 // MorphNodeTo can operate in two ways: if an existing node with the 8471 // specified operands exists, it can just return it. Otherwise, it 8472 // updates the node in place to have the requested operands. 8473 if (Res == Node) { 8474 // If we updated the node in place, reset the node ID. To the isel, 8475 // this should be just like a newly allocated machine node. 8476 Res->setNodeId(-1); 8477 } else { 8478 ReplaceAllUsesWith(Node, Res); 8479 RemoveDeadNode(Node); 8480 } 8481 8482 return Res; 8483 } 8484 8485 /// getMachineNode - These are used for target selectors to create a new node 8486 /// with specified return type(s), MachineInstr opcode, and operands. 8487 /// 8488 /// Note that getMachineNode returns the resultant node. If there is already a 8489 /// node of the specified opcode and operands, it returns that node instead of 8490 /// the current one. 8491 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8492 EVT VT) { 8493 SDVTList VTs = getVTList(VT); 8494 return getMachineNode(Opcode, dl, VTs, None); 8495 } 8496 8497 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8498 EVT VT, SDValue Op1) { 8499 SDVTList VTs = getVTList(VT); 8500 SDValue Ops[] = { Op1 }; 8501 return getMachineNode(Opcode, dl, VTs, Ops); 8502 } 8503 8504 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8505 EVT VT, SDValue Op1, SDValue Op2) { 8506 SDVTList VTs = getVTList(VT); 8507 SDValue Ops[] = { Op1, Op2 }; 8508 return getMachineNode(Opcode, dl, VTs, Ops); 8509 } 8510 8511 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8512 EVT VT, SDValue Op1, SDValue Op2, 8513 SDValue Op3) { 8514 SDVTList VTs = getVTList(VT); 8515 SDValue Ops[] = { Op1, Op2, Op3 }; 8516 return getMachineNode(Opcode, dl, VTs, Ops); 8517 } 8518 8519 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8520 EVT VT, ArrayRef<SDValue> Ops) { 8521 SDVTList VTs = getVTList(VT); 8522 return getMachineNode(Opcode, dl, VTs, Ops); 8523 } 8524 8525 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8526 EVT VT1, EVT VT2, SDValue Op1, 8527 SDValue Op2) { 8528 SDVTList VTs = getVTList(VT1, VT2); 8529 SDValue Ops[] = { Op1, Op2 }; 8530 return getMachineNode(Opcode, dl, VTs, Ops); 8531 } 8532 8533 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8534 EVT VT1, EVT VT2, SDValue Op1, 8535 SDValue Op2, SDValue Op3) { 8536 SDVTList VTs = getVTList(VT1, VT2); 8537 SDValue Ops[] = { Op1, Op2, Op3 }; 8538 return getMachineNode(Opcode, dl, VTs, Ops); 8539 } 8540 8541 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8542 EVT VT1, EVT VT2, 8543 ArrayRef<SDValue> Ops) { 8544 SDVTList VTs = getVTList(VT1, VT2); 8545 return getMachineNode(Opcode, dl, VTs, Ops); 8546 } 8547 8548 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8549 EVT VT1, EVT VT2, EVT VT3, 8550 SDValue Op1, SDValue Op2) { 8551 SDVTList VTs = getVTList(VT1, VT2, VT3); 8552 SDValue Ops[] = { Op1, Op2 }; 8553 return getMachineNode(Opcode, dl, VTs, Ops); 8554 } 8555 8556 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8557 EVT VT1, EVT VT2, EVT VT3, 8558 SDValue Op1, SDValue Op2, 8559 SDValue Op3) { 8560 SDVTList VTs = getVTList(VT1, VT2, VT3); 8561 SDValue Ops[] = { Op1, Op2, Op3 }; 8562 return getMachineNode(Opcode, dl, VTs, Ops); 8563 } 8564 8565 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8566 EVT VT1, EVT VT2, EVT VT3, 8567 ArrayRef<SDValue> Ops) { 8568 SDVTList VTs = getVTList(VT1, VT2, VT3); 8569 return getMachineNode(Opcode, dl, VTs, Ops); 8570 } 8571 8572 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8573 ArrayRef<EVT> ResultTys, 8574 ArrayRef<SDValue> Ops) { 8575 SDVTList VTs = getVTList(ResultTys); 8576 return getMachineNode(Opcode, dl, VTs, Ops); 8577 } 8578 8579 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 8580 SDVTList VTs, 8581 ArrayRef<SDValue> Ops) { 8582 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 8583 MachineSDNode *N; 8584 void *IP = nullptr; 8585 8586 if (DoCSE) { 8587 FoldingSetNodeID ID; 8588 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 8589 IP = nullptr; 8590 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8591 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 8592 } 8593 } 8594 8595 // Allocate a new MachineSDNode. 8596 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8597 createOperands(N, Ops); 8598 8599 if (DoCSE) 8600 CSEMap.InsertNode(N, IP); 8601 8602 InsertNode(N); 8603 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 8604 return N; 8605 } 8606 8607 /// getTargetExtractSubreg - A convenience function for creating 8608 /// TargetOpcode::EXTRACT_SUBREG nodes. 8609 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8610 SDValue Operand) { 8611 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8612 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 8613 VT, Operand, SRIdxVal); 8614 return SDValue(Subreg, 0); 8615 } 8616 8617 /// getTargetInsertSubreg - A convenience function for creating 8618 /// TargetOpcode::INSERT_SUBREG nodes. 8619 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8620 SDValue Operand, SDValue Subreg) { 8621 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8622 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 8623 VT, Operand, Subreg, SRIdxVal); 8624 return SDValue(Result, 0); 8625 } 8626 8627 /// getNodeIfExists - Get the specified node if it's already available, or 8628 /// else return NULL. 8629 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8630 ArrayRef<SDValue> Ops) { 8631 SDNodeFlags Flags; 8632 if (Inserter) 8633 Flags = Inserter->getFlags(); 8634 return getNodeIfExists(Opcode, VTList, Ops, Flags); 8635 } 8636 8637 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8638 ArrayRef<SDValue> Ops, 8639 const SDNodeFlags Flags) { 8640 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8641 FoldingSetNodeID ID; 8642 AddNodeIDNode(ID, Opcode, VTList, Ops); 8643 void *IP = nullptr; 8644 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 8645 E->intersectFlagsWith(Flags); 8646 return E; 8647 } 8648 } 8649 return nullptr; 8650 } 8651 8652 /// doesNodeExist - Check if a node exists without modifying its flags. 8653 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 8654 ArrayRef<SDValue> Ops) { 8655 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8656 FoldingSetNodeID ID; 8657 AddNodeIDNode(ID, Opcode, VTList, Ops); 8658 void *IP = nullptr; 8659 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 8660 return true; 8661 } 8662 return false; 8663 } 8664 8665 /// getDbgValue - Creates a SDDbgValue node. 8666 /// 8667 /// SDNode 8668 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 8669 SDNode *N, unsigned R, bool IsIndirect, 8670 const DebugLoc &DL, unsigned O) { 8671 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8672 "Expected inlined-at fields to agree"); 8673 return new (DbgInfo->getAlloc()) 8674 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 8675 {}, IsIndirect, DL, O, 8676 /*IsVariadic=*/false); 8677 } 8678 8679 /// Constant 8680 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 8681 DIExpression *Expr, 8682 const Value *C, 8683 const DebugLoc &DL, unsigned O) { 8684 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8685 "Expected inlined-at fields to agree"); 8686 return new (DbgInfo->getAlloc()) 8687 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 8688 /*IsIndirect=*/false, DL, O, 8689 /*IsVariadic=*/false); 8690 } 8691 8692 /// FrameIndex 8693 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8694 DIExpression *Expr, unsigned FI, 8695 bool IsIndirect, 8696 const DebugLoc &DL, 8697 unsigned O) { 8698 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8699 "Expected inlined-at fields to agree"); 8700 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 8701 } 8702 8703 /// FrameIndex with dependencies 8704 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8705 DIExpression *Expr, unsigned FI, 8706 ArrayRef<SDNode *> Dependencies, 8707 bool IsIndirect, 8708 const DebugLoc &DL, 8709 unsigned O) { 8710 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8711 "Expected inlined-at fields to agree"); 8712 return new (DbgInfo->getAlloc()) 8713 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 8714 Dependencies, IsIndirect, DL, O, 8715 /*IsVariadic=*/false); 8716 } 8717 8718 /// VReg 8719 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 8720 unsigned VReg, bool IsIndirect, 8721 const DebugLoc &DL, unsigned O) { 8722 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8723 "Expected inlined-at fields to agree"); 8724 return new (DbgInfo->getAlloc()) 8725 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 8726 {}, IsIndirect, DL, O, 8727 /*IsVariadic=*/false); 8728 } 8729 8730 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 8731 ArrayRef<SDDbgOperand> Locs, 8732 ArrayRef<SDNode *> Dependencies, 8733 bool IsIndirect, const DebugLoc &DL, 8734 unsigned O, bool IsVariadic) { 8735 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8736 "Expected inlined-at fields to agree"); 8737 return new (DbgInfo->getAlloc()) 8738 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 8739 DL, O, IsVariadic); 8740 } 8741 8742 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 8743 unsigned OffsetInBits, unsigned SizeInBits, 8744 bool InvalidateDbg) { 8745 SDNode *FromNode = From.getNode(); 8746 SDNode *ToNode = To.getNode(); 8747 assert(FromNode && ToNode && "Can't modify dbg values"); 8748 8749 // PR35338 8750 // TODO: assert(From != To && "Redundant dbg value transfer"); 8751 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 8752 if (From == To || FromNode == ToNode) 8753 return; 8754 8755 if (!FromNode->getHasDebugValue()) 8756 return; 8757 8758 SDDbgOperand FromLocOp = 8759 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 8760 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 8761 8762 SmallVector<SDDbgValue *, 2> ClonedDVs; 8763 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 8764 if (Dbg->isInvalidated()) 8765 continue; 8766 8767 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 8768 8769 // Create a new location ops vector that is equal to the old vector, but 8770 // with each instance of FromLocOp replaced with ToLocOp. 8771 bool Changed = false; 8772 auto NewLocOps = Dbg->copyLocationOps(); 8773 std::replace_if( 8774 NewLocOps.begin(), NewLocOps.end(), 8775 [&Changed, FromLocOp](const SDDbgOperand &Op) { 8776 bool Match = Op == FromLocOp; 8777 Changed |= Match; 8778 return Match; 8779 }, 8780 ToLocOp); 8781 // Ignore this SDDbgValue if we didn't find a matching location. 8782 if (!Changed) 8783 continue; 8784 8785 DIVariable *Var = Dbg->getVariable(); 8786 auto *Expr = Dbg->getExpression(); 8787 // If a fragment is requested, update the expression. 8788 if (SizeInBits) { 8789 // When splitting a larger (e.g., sign-extended) value whose 8790 // lower bits are described with an SDDbgValue, do not attempt 8791 // to transfer the SDDbgValue to the upper bits. 8792 if (auto FI = Expr->getFragmentInfo()) 8793 if (OffsetInBits + SizeInBits > FI->SizeInBits) 8794 continue; 8795 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 8796 SizeInBits); 8797 if (!Fragment) 8798 continue; 8799 Expr = *Fragment; 8800 } 8801 8802 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 8803 // Clone the SDDbgValue and move it to To. 8804 SDDbgValue *Clone = getDbgValueList( 8805 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 8806 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 8807 Dbg->isVariadic()); 8808 ClonedDVs.push_back(Clone); 8809 8810 if (InvalidateDbg) { 8811 // Invalidate value and indicate the SDDbgValue should not be emitted. 8812 Dbg->setIsInvalidated(); 8813 Dbg->setIsEmitted(); 8814 } 8815 } 8816 8817 for (SDDbgValue *Dbg : ClonedDVs) { 8818 assert(is_contained(Dbg->getSDNodes(), ToNode) && 8819 "Transferred DbgValues should depend on the new SDNode"); 8820 AddDbgValue(Dbg, false); 8821 } 8822 } 8823 8824 void SelectionDAG::salvageDebugInfo(SDNode &N) { 8825 if (!N.getHasDebugValue()) 8826 return; 8827 8828 SmallVector<SDDbgValue *, 2> ClonedDVs; 8829 for (auto DV : GetDbgValues(&N)) { 8830 if (DV->isInvalidated()) 8831 continue; 8832 switch (N.getOpcode()) { 8833 default: 8834 break; 8835 case ISD::ADD: 8836 SDValue N0 = N.getOperand(0); 8837 SDValue N1 = N.getOperand(1); 8838 if (!isConstantIntBuildVectorOrConstantInt(N0) && 8839 isConstantIntBuildVectorOrConstantInt(N1)) { 8840 uint64_t Offset = N.getConstantOperandVal(1); 8841 8842 // Rewrite an ADD constant node into a DIExpression. Since we are 8843 // performing arithmetic to compute the variable's *value* in the 8844 // DIExpression, we need to mark the expression with a 8845 // DW_OP_stack_value. 8846 auto *DIExpr = DV->getExpression(); 8847 auto NewLocOps = DV->copyLocationOps(); 8848 bool Changed = false; 8849 for (size_t i = 0; i < NewLocOps.size(); ++i) { 8850 // We're not given a ResNo to compare against because the whole 8851 // node is going away. We know that any ISD::ADD only has one 8852 // result, so we can assume any node match is using the result. 8853 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 8854 NewLocOps[i].getSDNode() != &N) 8855 continue; 8856 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 8857 SmallVector<uint64_t, 3> ExprOps; 8858 DIExpression::appendOffset(ExprOps, Offset); 8859 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 8860 Changed = true; 8861 } 8862 (void)Changed; 8863 assert(Changed && "Salvage target doesn't use N"); 8864 8865 auto AdditionalDependencies = DV->getAdditionalDependencies(); 8866 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 8867 NewLocOps, AdditionalDependencies, 8868 DV->isIndirect(), DV->getDebugLoc(), 8869 DV->getOrder(), DV->isVariadic()); 8870 ClonedDVs.push_back(Clone); 8871 DV->setIsInvalidated(); 8872 DV->setIsEmitted(); 8873 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 8874 N0.getNode()->dumprFull(this); 8875 dbgs() << " into " << *DIExpr << '\n'); 8876 } 8877 } 8878 } 8879 8880 for (SDDbgValue *Dbg : ClonedDVs) { 8881 assert(!Dbg->getSDNodes().empty() && 8882 "Salvaged DbgValue should depend on a new SDNode"); 8883 AddDbgValue(Dbg, false); 8884 } 8885 } 8886 8887 /// Creates a SDDbgLabel node. 8888 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 8889 const DebugLoc &DL, unsigned O) { 8890 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 8891 "Expected inlined-at fields to agree"); 8892 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 8893 } 8894 8895 namespace { 8896 8897 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 8898 /// pointed to by a use iterator is deleted, increment the use iterator 8899 /// so that it doesn't dangle. 8900 /// 8901 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 8902 SDNode::use_iterator &UI; 8903 SDNode::use_iterator &UE; 8904 8905 void NodeDeleted(SDNode *N, SDNode *E) override { 8906 // Increment the iterator as needed. 8907 while (UI != UE && N == *UI) 8908 ++UI; 8909 } 8910 8911 public: 8912 RAUWUpdateListener(SelectionDAG &d, 8913 SDNode::use_iterator &ui, 8914 SDNode::use_iterator &ue) 8915 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 8916 }; 8917 8918 } // end anonymous namespace 8919 8920 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8921 /// This can cause recursive merging of nodes in the DAG. 8922 /// 8923 /// This version assumes From has a single result value. 8924 /// 8925 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 8926 SDNode *From = FromN.getNode(); 8927 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 8928 "Cannot replace with this method!"); 8929 assert(From != To.getNode() && "Cannot replace uses of with self"); 8930 8931 // Preserve Debug Values 8932 transferDbgValues(FromN, To); 8933 8934 // Iterate over all the existing uses of From. New uses will be added 8935 // to the beginning of the use list, which we avoid visiting. 8936 // This specifically avoids visiting uses of From that arise while the 8937 // replacement is happening, because any such uses would be the result 8938 // of CSE: If an existing node looks like From after one of its operands 8939 // is replaced by To, we don't want to replace of all its users with To 8940 // too. See PR3018 for more info. 8941 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8942 RAUWUpdateListener Listener(*this, UI, UE); 8943 while (UI != UE) { 8944 SDNode *User = *UI; 8945 8946 // This node is about to morph, remove its old self from the CSE maps. 8947 RemoveNodeFromCSEMaps(User); 8948 8949 // A user can appear in a use list multiple times, and when this 8950 // happens the uses are usually next to each other in the list. 8951 // To help reduce the number of CSE recomputations, process all 8952 // the uses of this user that we can find this way. 8953 do { 8954 SDUse &Use = UI.getUse(); 8955 ++UI; 8956 Use.set(To); 8957 if (To->isDivergent() != From->isDivergent()) 8958 updateDivergence(User); 8959 } while (UI != UE && *UI == User); 8960 // Now that we have modified User, add it back to the CSE maps. If it 8961 // already exists there, recursively merge the results together. 8962 AddModifiedNodeToCSEMaps(User); 8963 } 8964 8965 // If we just RAUW'd the root, take note. 8966 if (FromN == getRoot()) 8967 setRoot(To); 8968 } 8969 8970 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8971 /// This can cause recursive merging of nodes in the DAG. 8972 /// 8973 /// This version assumes that for each value of From, there is a 8974 /// corresponding value in To in the same position with the same type. 8975 /// 8976 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 8977 #ifndef NDEBUG 8978 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8979 assert((!From->hasAnyUseOfValue(i) || 8980 From->getValueType(i) == To->getValueType(i)) && 8981 "Cannot use this version of ReplaceAllUsesWith!"); 8982 #endif 8983 8984 // Handle the trivial case. 8985 if (From == To) 8986 return; 8987 8988 // Preserve Debug Info. Only do this if there's a use. 8989 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8990 if (From->hasAnyUseOfValue(i)) { 8991 assert((i < To->getNumValues()) && "Invalid To location"); 8992 transferDbgValues(SDValue(From, i), SDValue(To, i)); 8993 } 8994 8995 // Iterate over just the existing users of From. See the comments in 8996 // the ReplaceAllUsesWith above. 8997 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8998 RAUWUpdateListener Listener(*this, UI, UE); 8999 while (UI != UE) { 9000 SDNode *User = *UI; 9001 9002 // This node is about to morph, remove its old self from the CSE maps. 9003 RemoveNodeFromCSEMaps(User); 9004 9005 // A user can appear in a use list multiple times, and when this 9006 // happens the uses are usually next to each other in the list. 9007 // To help reduce the number of CSE recomputations, process all 9008 // the uses of this user that we can find this way. 9009 do { 9010 SDUse &Use = UI.getUse(); 9011 ++UI; 9012 Use.setNode(To); 9013 if (To->isDivergent() != From->isDivergent()) 9014 updateDivergence(User); 9015 } while (UI != UE && *UI == User); 9016 9017 // Now that we have modified User, add it back to the CSE maps. If it 9018 // already exists there, recursively merge the results together. 9019 AddModifiedNodeToCSEMaps(User); 9020 } 9021 9022 // If we just RAUW'd the root, take note. 9023 if (From == getRoot().getNode()) 9024 setRoot(SDValue(To, getRoot().getResNo())); 9025 } 9026 9027 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9028 /// This can cause recursive merging of nodes in the DAG. 9029 /// 9030 /// This version can replace From with any result values. To must match the 9031 /// number and types of values returned by From. 9032 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9033 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9034 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9035 9036 // Preserve Debug Info. 9037 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9038 transferDbgValues(SDValue(From, i), To[i]); 9039 9040 // Iterate over just the existing users of From. See the comments in 9041 // the ReplaceAllUsesWith above. 9042 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9043 RAUWUpdateListener Listener(*this, UI, UE); 9044 while (UI != UE) { 9045 SDNode *User = *UI; 9046 9047 // This node is about to morph, remove its old self from the CSE maps. 9048 RemoveNodeFromCSEMaps(User); 9049 9050 // A user can appear in a use list multiple times, and when this happens the 9051 // uses are usually next to each other in the list. To help reduce the 9052 // number of CSE and divergence recomputations, process all the uses of this 9053 // user that we can find this way. 9054 bool To_IsDivergent = false; 9055 do { 9056 SDUse &Use = UI.getUse(); 9057 const SDValue &ToOp = To[Use.getResNo()]; 9058 ++UI; 9059 Use.set(ToOp); 9060 To_IsDivergent |= ToOp->isDivergent(); 9061 } while (UI != UE && *UI == User); 9062 9063 if (To_IsDivergent != From->isDivergent()) 9064 updateDivergence(User); 9065 9066 // Now that we have modified User, add it back to the CSE maps. If it 9067 // already exists there, recursively merge the results together. 9068 AddModifiedNodeToCSEMaps(User); 9069 } 9070 9071 // If we just RAUW'd the root, take note. 9072 if (From == getRoot().getNode()) 9073 setRoot(SDValue(To[getRoot().getResNo()])); 9074 } 9075 9076 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 9077 /// uses of other values produced by From.getNode() alone. The Deleted 9078 /// vector is handled the same way as for ReplaceAllUsesWith. 9079 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 9080 // Handle the really simple, really trivial case efficiently. 9081 if (From == To) return; 9082 9083 // Handle the simple, trivial, case efficiently. 9084 if (From.getNode()->getNumValues() == 1) { 9085 ReplaceAllUsesWith(From, To); 9086 return; 9087 } 9088 9089 // Preserve Debug Info. 9090 transferDbgValues(From, To); 9091 9092 // Iterate over just the existing users of From. See the comments in 9093 // the ReplaceAllUsesWith above. 9094 SDNode::use_iterator UI = From.getNode()->use_begin(), 9095 UE = From.getNode()->use_end(); 9096 RAUWUpdateListener Listener(*this, UI, UE); 9097 while (UI != UE) { 9098 SDNode *User = *UI; 9099 bool UserRemovedFromCSEMaps = false; 9100 9101 // A user can appear in a use list multiple times, and when this 9102 // happens the uses are usually next to each other in the list. 9103 // To help reduce the number of CSE recomputations, process all 9104 // the uses of this user that we can find this way. 9105 do { 9106 SDUse &Use = UI.getUse(); 9107 9108 // Skip uses of different values from the same node. 9109 if (Use.getResNo() != From.getResNo()) { 9110 ++UI; 9111 continue; 9112 } 9113 9114 // If this node hasn't been modified yet, it's still in the CSE maps, 9115 // so remove its old self from the CSE maps. 9116 if (!UserRemovedFromCSEMaps) { 9117 RemoveNodeFromCSEMaps(User); 9118 UserRemovedFromCSEMaps = true; 9119 } 9120 9121 ++UI; 9122 Use.set(To); 9123 if (To->isDivergent() != From->isDivergent()) 9124 updateDivergence(User); 9125 } while (UI != UE && *UI == User); 9126 // We are iterating over all uses of the From node, so if a use 9127 // doesn't use the specific value, no changes are made. 9128 if (!UserRemovedFromCSEMaps) 9129 continue; 9130 9131 // Now that we have modified User, add it back to the CSE maps. If it 9132 // already exists there, recursively merge the results together. 9133 AddModifiedNodeToCSEMaps(User); 9134 } 9135 9136 // If we just RAUW'd the root, take note. 9137 if (From == getRoot()) 9138 setRoot(To); 9139 } 9140 9141 namespace { 9142 9143 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 9144 /// to record information about a use. 9145 struct UseMemo { 9146 SDNode *User; 9147 unsigned Index; 9148 SDUse *Use; 9149 }; 9150 9151 /// operator< - Sort Memos by User. 9152 bool operator<(const UseMemo &L, const UseMemo &R) { 9153 return (intptr_t)L.User < (intptr_t)R.User; 9154 } 9155 9156 } // end anonymous namespace 9157 9158 bool SelectionDAG::calculateDivergence(SDNode *N) { 9159 if (TLI->isSDNodeAlwaysUniform(N)) { 9160 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 9161 "Conflicting divergence information!"); 9162 return false; 9163 } 9164 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 9165 return true; 9166 for (auto &Op : N->ops()) { 9167 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 9168 return true; 9169 } 9170 return false; 9171 } 9172 9173 void SelectionDAG::updateDivergence(SDNode *N) { 9174 SmallVector<SDNode *, 16> Worklist(1, N); 9175 do { 9176 N = Worklist.pop_back_val(); 9177 bool IsDivergent = calculateDivergence(N); 9178 if (N->SDNodeBits.IsDivergent != IsDivergent) { 9179 N->SDNodeBits.IsDivergent = IsDivergent; 9180 llvm::append_range(Worklist, N->uses()); 9181 } 9182 } while (!Worklist.empty()); 9183 } 9184 9185 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 9186 DenseMap<SDNode *, unsigned> Degree; 9187 Order.reserve(AllNodes.size()); 9188 for (auto &N : allnodes()) { 9189 unsigned NOps = N.getNumOperands(); 9190 Degree[&N] = NOps; 9191 if (0 == NOps) 9192 Order.push_back(&N); 9193 } 9194 for (size_t I = 0; I != Order.size(); ++I) { 9195 SDNode *N = Order[I]; 9196 for (auto U : N->uses()) { 9197 unsigned &UnsortedOps = Degree[U]; 9198 if (0 == --UnsortedOps) 9199 Order.push_back(U); 9200 } 9201 } 9202 } 9203 9204 #ifndef NDEBUG 9205 void SelectionDAG::VerifyDAGDiverence() { 9206 std::vector<SDNode *> TopoOrder; 9207 CreateTopologicalOrder(TopoOrder); 9208 for (auto *N : TopoOrder) { 9209 assert(calculateDivergence(N) == N->isDivergent() && 9210 "Divergence bit inconsistency detected"); 9211 } 9212 } 9213 #endif 9214 9215 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 9216 /// uses of other values produced by From.getNode() alone. The same value 9217 /// may appear in both the From and To list. The Deleted vector is 9218 /// handled the same way as for ReplaceAllUsesWith. 9219 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 9220 const SDValue *To, 9221 unsigned Num){ 9222 // Handle the simple, trivial case efficiently. 9223 if (Num == 1) 9224 return ReplaceAllUsesOfValueWith(*From, *To); 9225 9226 transferDbgValues(*From, *To); 9227 9228 // Read up all the uses and make records of them. This helps 9229 // processing new uses that are introduced during the 9230 // replacement process. 9231 SmallVector<UseMemo, 4> Uses; 9232 for (unsigned i = 0; i != Num; ++i) { 9233 unsigned FromResNo = From[i].getResNo(); 9234 SDNode *FromNode = From[i].getNode(); 9235 for (SDNode::use_iterator UI = FromNode->use_begin(), 9236 E = FromNode->use_end(); UI != E; ++UI) { 9237 SDUse &Use = UI.getUse(); 9238 if (Use.getResNo() == FromResNo) { 9239 UseMemo Memo = { *UI, i, &Use }; 9240 Uses.push_back(Memo); 9241 } 9242 } 9243 } 9244 9245 // Sort the uses, so that all the uses from a given User are together. 9246 llvm::sort(Uses); 9247 9248 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 9249 UseIndex != UseIndexEnd; ) { 9250 // We know that this user uses some value of From. If it is the right 9251 // value, update it. 9252 SDNode *User = Uses[UseIndex].User; 9253 9254 // This node is about to morph, remove its old self from the CSE maps. 9255 RemoveNodeFromCSEMaps(User); 9256 9257 // The Uses array is sorted, so all the uses for a given User 9258 // are next to each other in the list. 9259 // To help reduce the number of CSE recomputations, process all 9260 // the uses of this user that we can find this way. 9261 do { 9262 unsigned i = Uses[UseIndex].Index; 9263 SDUse &Use = *Uses[UseIndex].Use; 9264 ++UseIndex; 9265 9266 Use.set(To[i]); 9267 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 9268 9269 // Now that we have modified User, add it back to the CSE maps. If it 9270 // already exists there, recursively merge the results together. 9271 AddModifiedNodeToCSEMaps(User); 9272 } 9273 } 9274 9275 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 9276 /// based on their topological order. It returns the maximum id and a vector 9277 /// of the SDNodes* in assigned order by reference. 9278 unsigned SelectionDAG::AssignTopologicalOrder() { 9279 unsigned DAGSize = 0; 9280 9281 // SortedPos tracks the progress of the algorithm. Nodes before it are 9282 // sorted, nodes after it are unsorted. When the algorithm completes 9283 // it is at the end of the list. 9284 allnodes_iterator SortedPos = allnodes_begin(); 9285 9286 // Visit all the nodes. Move nodes with no operands to the front of 9287 // the list immediately. Annotate nodes that do have operands with their 9288 // operand count. Before we do this, the Node Id fields of the nodes 9289 // may contain arbitrary values. After, the Node Id fields for nodes 9290 // before SortedPos will contain the topological sort index, and the 9291 // Node Id fields for nodes At SortedPos and after will contain the 9292 // count of outstanding operands. 9293 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 9294 SDNode *N = &*I++; 9295 checkForCycles(N, this); 9296 unsigned Degree = N->getNumOperands(); 9297 if (Degree == 0) { 9298 // A node with no uses, add it to the result array immediately. 9299 N->setNodeId(DAGSize++); 9300 allnodes_iterator Q(N); 9301 if (Q != SortedPos) 9302 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 9303 assert(SortedPos != AllNodes.end() && "Overran node list"); 9304 ++SortedPos; 9305 } else { 9306 // Temporarily use the Node Id as scratch space for the degree count. 9307 N->setNodeId(Degree); 9308 } 9309 } 9310 9311 // Visit all the nodes. As we iterate, move nodes into sorted order, 9312 // such that by the time the end is reached all nodes will be sorted. 9313 for (SDNode &Node : allnodes()) { 9314 SDNode *N = &Node; 9315 checkForCycles(N, this); 9316 // N is in sorted position, so all its uses have one less operand 9317 // that needs to be sorted. 9318 for (SDNode *P : N->uses()) { 9319 unsigned Degree = P->getNodeId(); 9320 assert(Degree != 0 && "Invalid node degree"); 9321 --Degree; 9322 if (Degree == 0) { 9323 // All of P's operands are sorted, so P may sorted now. 9324 P->setNodeId(DAGSize++); 9325 if (P->getIterator() != SortedPos) 9326 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9327 assert(SortedPos != AllNodes.end() && "Overran node list"); 9328 ++SortedPos; 9329 } else { 9330 // Update P's outstanding operand count. 9331 P->setNodeId(Degree); 9332 } 9333 } 9334 if (Node.getIterator() == SortedPos) { 9335 #ifndef NDEBUG 9336 allnodes_iterator I(N); 9337 SDNode *S = &*++I; 9338 dbgs() << "Overran sorted position:\n"; 9339 S->dumprFull(this); dbgs() << "\n"; 9340 dbgs() << "Checking if this is due to cycles\n"; 9341 checkForCycles(this, true); 9342 #endif 9343 llvm_unreachable(nullptr); 9344 } 9345 } 9346 9347 assert(SortedPos == AllNodes.end() && 9348 "Topological sort incomplete!"); 9349 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9350 "First node in topological sort is not the entry token!"); 9351 assert(AllNodes.front().getNodeId() == 0 && 9352 "First node in topological sort has non-zero id!"); 9353 assert(AllNodes.front().getNumOperands() == 0 && 9354 "First node in topological sort has operands!"); 9355 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9356 "Last node in topologic sort has unexpected id!"); 9357 assert(AllNodes.back().use_empty() && 9358 "Last node in topologic sort has users!"); 9359 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9360 return DAGSize; 9361 } 9362 9363 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9364 /// value is produced by SD. 9365 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 9366 for (SDNode *SD : DB->getSDNodes()) { 9367 if (!SD) 9368 continue; 9369 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9370 SD->setHasDebugValue(true); 9371 } 9372 DbgInfo->add(DB, isParameter); 9373 } 9374 9375 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 9376 9377 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9378 SDValue NewMemOpChain) { 9379 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9380 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9381 // The new memory operation must have the same position as the old load in 9382 // terms of memory dependency. Create a TokenFactor for the old load and new 9383 // memory operation and update uses of the old load's output chain to use that 9384 // TokenFactor. 9385 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9386 return NewMemOpChain; 9387 9388 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9389 OldChain, NewMemOpChain); 9390 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9391 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9392 return TokenFactor; 9393 } 9394 9395 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9396 SDValue NewMemOp) { 9397 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9398 SDValue OldChain = SDValue(OldLoad, 1); 9399 SDValue NewMemOpChain = NewMemOp.getValue(1); 9400 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9401 } 9402 9403 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9404 Function **OutFunction) { 9405 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9406 9407 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9408 auto *Module = MF->getFunction().getParent(); 9409 auto *Function = Module->getFunction(Symbol); 9410 9411 if (OutFunction != nullptr) 9412 *OutFunction = Function; 9413 9414 if (Function != nullptr) { 9415 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9416 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9417 } 9418 9419 std::string ErrorStr; 9420 raw_string_ostream ErrorFormatter(ErrorStr); 9421 9422 ErrorFormatter << "Undefined external symbol "; 9423 ErrorFormatter << '"' << Symbol << '"'; 9424 ErrorFormatter.flush(); 9425 9426 report_fatal_error(ErrorStr); 9427 } 9428 9429 //===----------------------------------------------------------------------===// 9430 // SDNode Class 9431 //===----------------------------------------------------------------------===// 9432 9433 bool llvm::isNullConstant(SDValue V) { 9434 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9435 return Const != nullptr && Const->isNullValue(); 9436 } 9437 9438 bool llvm::isNullFPConstant(SDValue V) { 9439 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9440 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9441 } 9442 9443 bool llvm::isAllOnesConstant(SDValue V) { 9444 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9445 return Const != nullptr && Const->isAllOnesValue(); 9446 } 9447 9448 bool llvm::isOneConstant(SDValue V) { 9449 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9450 return Const != nullptr && Const->isOne(); 9451 } 9452 9453 SDValue llvm::peekThroughBitcasts(SDValue V) { 9454 while (V.getOpcode() == ISD::BITCAST) 9455 V = V.getOperand(0); 9456 return V; 9457 } 9458 9459 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9460 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9461 V = V.getOperand(0); 9462 return V; 9463 } 9464 9465 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9466 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9467 V = V.getOperand(0); 9468 return V; 9469 } 9470 9471 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9472 if (V.getOpcode() != ISD::XOR) 9473 return false; 9474 V = peekThroughBitcasts(V.getOperand(1)); 9475 unsigned NumBits = V.getScalarValueSizeInBits(); 9476 ConstantSDNode *C = 9477 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 9478 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 9479 } 9480 9481 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 9482 bool AllowTruncation) { 9483 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9484 return CN; 9485 9486 // SplatVectors can truncate their operands. Ignore that case here unless 9487 // AllowTruncation is set. 9488 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 9489 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 9490 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9491 EVT CVT = CN->getValueType(0); 9492 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 9493 if (AllowTruncation || CVT == VecEltVT) 9494 return CN; 9495 } 9496 } 9497 9498 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9499 BitVector UndefElements; 9500 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 9501 9502 // BuildVectors can truncate their operands. Ignore that case here unless 9503 // AllowTruncation is set. 9504 if (CN && (UndefElements.none() || AllowUndefs)) { 9505 EVT CVT = CN->getValueType(0); 9506 EVT NSVT = N.getValueType().getScalarType(); 9507 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9508 if (AllowTruncation || (CVT == NSVT)) 9509 return CN; 9510 } 9511 } 9512 9513 return nullptr; 9514 } 9515 9516 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 9517 bool AllowUndefs, 9518 bool AllowTruncation) { 9519 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9520 return CN; 9521 9522 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9523 BitVector UndefElements; 9524 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 9525 9526 // BuildVectors can truncate their operands. Ignore that case here unless 9527 // AllowTruncation is set. 9528 if (CN && (UndefElements.none() || AllowUndefs)) { 9529 EVT CVT = CN->getValueType(0); 9530 EVT NSVT = N.getValueType().getScalarType(); 9531 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9532 if (AllowTruncation || (CVT == NSVT)) 9533 return CN; 9534 } 9535 } 9536 9537 return nullptr; 9538 } 9539 9540 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 9541 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9542 return CN; 9543 9544 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9545 BitVector UndefElements; 9546 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 9547 if (CN && (UndefElements.none() || AllowUndefs)) 9548 return CN; 9549 } 9550 9551 if (N.getOpcode() == ISD::SPLAT_VECTOR) 9552 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 9553 return CN; 9554 9555 return nullptr; 9556 } 9557 9558 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 9559 const APInt &DemandedElts, 9560 bool AllowUndefs) { 9561 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9562 return CN; 9563 9564 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9565 BitVector UndefElements; 9566 ConstantFPSDNode *CN = 9567 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 9568 if (CN && (UndefElements.none() || AllowUndefs)) 9569 return CN; 9570 } 9571 9572 return nullptr; 9573 } 9574 9575 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 9576 // TODO: may want to use peekThroughBitcast() here. 9577 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9578 return C && C->isNullValue(); 9579 } 9580 9581 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 9582 // TODO: may want to use peekThroughBitcast() here. 9583 unsigned BitWidth = N.getScalarValueSizeInBits(); 9584 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9585 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 9586 } 9587 9588 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 9589 N = peekThroughBitcasts(N); 9590 unsigned BitWidth = N.getScalarValueSizeInBits(); 9591 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9592 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth; 9593 } 9594 9595 HandleSDNode::~HandleSDNode() { 9596 DropOperands(); 9597 } 9598 9599 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 9600 const DebugLoc &DL, 9601 const GlobalValue *GA, EVT VT, 9602 int64_t o, unsigned TF) 9603 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 9604 TheGlobal = GA; 9605 } 9606 9607 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 9608 EVT VT, unsigned SrcAS, 9609 unsigned DestAS) 9610 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 9611 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 9612 9613 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 9614 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 9615 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 9616 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 9617 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 9618 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 9619 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 9620 9621 // We check here that the size of the memory operand fits within the size of 9622 // the MMO. This is because the MMO might indicate only a possible address 9623 // range instead of specifying the affected memory addresses precisely. 9624 // TODO: Make MachineMemOperands aware of scalable vectors. 9625 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 9626 "Size mismatch!"); 9627 } 9628 9629 /// Profile - Gather unique data for the node. 9630 /// 9631 void SDNode::Profile(FoldingSetNodeID &ID) const { 9632 AddNodeIDNode(ID, this); 9633 } 9634 9635 namespace { 9636 9637 struct EVTArray { 9638 std::vector<EVT> VTs; 9639 9640 EVTArray() { 9641 VTs.reserve(MVT::LAST_VALUETYPE); 9642 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 9643 VTs.push_back(MVT((MVT::SimpleValueType)i)); 9644 } 9645 }; 9646 9647 } // end anonymous namespace 9648 9649 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 9650 static ManagedStatic<EVTArray> SimpleVTArray; 9651 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 9652 9653 /// getValueTypeList - Return a pointer to the specified value type. 9654 /// 9655 const EVT *SDNode::getValueTypeList(EVT VT) { 9656 if (VT.isExtended()) { 9657 sys::SmartScopedLock<true> Lock(*VTMutex); 9658 return &(*EVTs->insert(VT).first); 9659 } 9660 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && "Value type out of range!"); 9661 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 9662 } 9663 9664 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 9665 /// indicated value. This method ignores uses of other values defined by this 9666 /// operation. 9667 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 9668 assert(Value < getNumValues() && "Bad value!"); 9669 9670 // TODO: Only iterate over uses of a given value of the node 9671 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 9672 if (UI.getUse().getResNo() == Value) { 9673 if (NUses == 0) 9674 return false; 9675 --NUses; 9676 } 9677 } 9678 9679 // Found exactly the right number of uses? 9680 return NUses == 0; 9681 } 9682 9683 /// hasAnyUseOfValue - Return true if there are any use of the indicated 9684 /// value. This method ignores uses of other values defined by this operation. 9685 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 9686 assert(Value < getNumValues() && "Bad value!"); 9687 9688 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 9689 if (UI.getUse().getResNo() == Value) 9690 return true; 9691 9692 return false; 9693 } 9694 9695 /// isOnlyUserOf - Return true if this node is the only use of N. 9696 bool SDNode::isOnlyUserOf(const SDNode *N) const { 9697 bool Seen = false; 9698 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9699 SDNode *User = *I; 9700 if (User == this) 9701 Seen = true; 9702 else 9703 return false; 9704 } 9705 9706 return Seen; 9707 } 9708 9709 /// Return true if the only users of N are contained in Nodes. 9710 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 9711 bool Seen = false; 9712 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9713 SDNode *User = *I; 9714 if (llvm::is_contained(Nodes, User)) 9715 Seen = true; 9716 else 9717 return false; 9718 } 9719 9720 return Seen; 9721 } 9722 9723 /// isOperand - Return true if this node is an operand of N. 9724 bool SDValue::isOperandOf(const SDNode *N) const { 9725 return is_contained(N->op_values(), *this); 9726 } 9727 9728 bool SDNode::isOperandOf(const SDNode *N) const { 9729 return any_of(N->op_values(), 9730 [this](SDValue Op) { return this == Op.getNode(); }); 9731 } 9732 9733 /// reachesChainWithoutSideEffects - Return true if this operand (which must 9734 /// be a chain) reaches the specified operand without crossing any 9735 /// side-effecting instructions on any chain path. In practice, this looks 9736 /// through token factors and non-volatile loads. In order to remain efficient, 9737 /// this only looks a couple of nodes in, it does not do an exhaustive search. 9738 /// 9739 /// Note that we only need to examine chains when we're searching for 9740 /// side-effects; SelectionDAG requires that all side-effects are represented 9741 /// by chains, even if another operand would force a specific ordering. This 9742 /// constraint is necessary to allow transformations like splitting loads. 9743 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 9744 unsigned Depth) const { 9745 if (*this == Dest) return true; 9746 9747 // Don't search too deeply, we just want to be able to see through 9748 // TokenFactor's etc. 9749 if (Depth == 0) return false; 9750 9751 // If this is a token factor, all inputs to the TF happen in parallel. 9752 if (getOpcode() == ISD::TokenFactor) { 9753 // First, try a shallow search. 9754 if (is_contained((*this)->ops(), Dest)) { 9755 // We found the chain we want as an operand of this TokenFactor. 9756 // Essentially, we reach the chain without side-effects if we could 9757 // serialize the TokenFactor into a simple chain of operations with 9758 // Dest as the last operation. This is automatically true if the 9759 // chain has one use: there are no other ordering constraints. 9760 // If the chain has more than one use, we give up: some other 9761 // use of Dest might force a side-effect between Dest and the current 9762 // node. 9763 if (Dest.hasOneUse()) 9764 return true; 9765 } 9766 // Next, try a deep search: check whether every operand of the TokenFactor 9767 // reaches Dest. 9768 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 9769 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 9770 }); 9771 } 9772 9773 // Loads don't have side effects, look through them. 9774 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 9775 if (Ld->isUnordered()) 9776 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 9777 } 9778 return false; 9779 } 9780 9781 bool SDNode::hasPredecessor(const SDNode *N) const { 9782 SmallPtrSet<const SDNode *, 32> Visited; 9783 SmallVector<const SDNode *, 16> Worklist; 9784 Worklist.push_back(this); 9785 return hasPredecessorHelper(N, Visited, Worklist); 9786 } 9787 9788 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 9789 this->Flags.intersectWith(Flags); 9790 } 9791 9792 SDValue 9793 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 9794 ArrayRef<ISD::NodeType> CandidateBinOps, 9795 bool AllowPartials) { 9796 // The pattern must end in an extract from index 0. 9797 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9798 !isNullConstant(Extract->getOperand(1))) 9799 return SDValue(); 9800 9801 // Match against one of the candidate binary ops. 9802 SDValue Op = Extract->getOperand(0); 9803 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 9804 return Op.getOpcode() == unsigned(BinOp); 9805 })) 9806 return SDValue(); 9807 9808 // Floating-point reductions may require relaxed constraints on the final step 9809 // of the reduction because they may reorder intermediate operations. 9810 unsigned CandidateBinOp = Op.getOpcode(); 9811 if (Op.getValueType().isFloatingPoint()) { 9812 SDNodeFlags Flags = Op->getFlags(); 9813 switch (CandidateBinOp) { 9814 case ISD::FADD: 9815 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 9816 return SDValue(); 9817 break; 9818 default: 9819 llvm_unreachable("Unhandled FP opcode for binop reduction"); 9820 } 9821 } 9822 9823 // Matching failed - attempt to see if we did enough stages that a partial 9824 // reduction from a subvector is possible. 9825 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 9826 if (!AllowPartials || !Op) 9827 return SDValue(); 9828 EVT OpVT = Op.getValueType(); 9829 EVT OpSVT = OpVT.getScalarType(); 9830 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 9831 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 9832 return SDValue(); 9833 BinOp = (ISD::NodeType)CandidateBinOp; 9834 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 9835 getVectorIdxConstant(0, SDLoc(Op))); 9836 }; 9837 9838 // At each stage, we're looking for something that looks like: 9839 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 9840 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 9841 // i32 undef, i32 undef, i32 undef, i32 undef> 9842 // %a = binop <8 x i32> %op, %s 9843 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 9844 // we expect something like: 9845 // <4,5,6,7,u,u,u,u> 9846 // <2,3,u,u,u,u,u,u> 9847 // <1,u,u,u,u,u,u,u> 9848 // While a partial reduction match would be: 9849 // <2,3,u,u,u,u,u,u> 9850 // <1,u,u,u,u,u,u,u> 9851 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 9852 SDValue PrevOp; 9853 for (unsigned i = 0; i < Stages; ++i) { 9854 unsigned MaskEnd = (1 << i); 9855 9856 if (Op.getOpcode() != CandidateBinOp) 9857 return PartialReduction(PrevOp, MaskEnd); 9858 9859 SDValue Op0 = Op.getOperand(0); 9860 SDValue Op1 = Op.getOperand(1); 9861 9862 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 9863 if (Shuffle) { 9864 Op = Op1; 9865 } else { 9866 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 9867 Op = Op0; 9868 } 9869 9870 // The first operand of the shuffle should be the same as the other operand 9871 // of the binop. 9872 if (!Shuffle || Shuffle->getOperand(0) != Op) 9873 return PartialReduction(PrevOp, MaskEnd); 9874 9875 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 9876 for (int Index = 0; Index < (int)MaskEnd; ++Index) 9877 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 9878 return PartialReduction(PrevOp, MaskEnd); 9879 9880 PrevOp = Op; 9881 } 9882 9883 // Handle subvector reductions, which tend to appear after the shuffle 9884 // reduction stages. 9885 while (Op.getOpcode() == CandidateBinOp) { 9886 unsigned NumElts = Op.getValueType().getVectorNumElements(); 9887 SDValue Op0 = Op.getOperand(0); 9888 SDValue Op1 = Op.getOperand(1); 9889 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9890 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9891 Op0.getOperand(0) != Op1.getOperand(0)) 9892 break; 9893 SDValue Src = Op0.getOperand(0); 9894 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 9895 if (NumSrcElts != (2 * NumElts)) 9896 break; 9897 if (!(Op0.getConstantOperandAPInt(1) == 0 && 9898 Op1.getConstantOperandAPInt(1) == NumElts) && 9899 !(Op1.getConstantOperandAPInt(1) == 0 && 9900 Op0.getConstantOperandAPInt(1) == NumElts)) 9901 break; 9902 Op = Src; 9903 } 9904 9905 BinOp = (ISD::NodeType)CandidateBinOp; 9906 return Op; 9907 } 9908 9909 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 9910 assert(N->getNumValues() == 1 && 9911 "Can't unroll a vector with multiple results!"); 9912 9913 EVT VT = N->getValueType(0); 9914 unsigned NE = VT.getVectorNumElements(); 9915 EVT EltVT = VT.getVectorElementType(); 9916 SDLoc dl(N); 9917 9918 SmallVector<SDValue, 8> Scalars; 9919 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 9920 9921 // If ResNE is 0, fully unroll the vector op. 9922 if (ResNE == 0) 9923 ResNE = NE; 9924 else if (NE > ResNE) 9925 NE = ResNE; 9926 9927 unsigned i; 9928 for (i= 0; i != NE; ++i) { 9929 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 9930 SDValue Operand = N->getOperand(j); 9931 EVT OperandVT = Operand.getValueType(); 9932 if (OperandVT.isVector()) { 9933 // A vector operand; extract a single element. 9934 EVT OperandEltVT = OperandVT.getVectorElementType(); 9935 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 9936 Operand, getVectorIdxConstant(i, dl)); 9937 } else { 9938 // A scalar operand; just use it as is. 9939 Operands[j] = Operand; 9940 } 9941 } 9942 9943 switch (N->getOpcode()) { 9944 default: { 9945 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 9946 N->getFlags())); 9947 break; 9948 } 9949 case ISD::VSELECT: 9950 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 9951 break; 9952 case ISD::SHL: 9953 case ISD::SRA: 9954 case ISD::SRL: 9955 case ISD::ROTL: 9956 case ISD::ROTR: 9957 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 9958 getShiftAmountOperand(Operands[0].getValueType(), 9959 Operands[1]))); 9960 break; 9961 case ISD::SIGN_EXTEND_INREG: { 9962 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 9963 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 9964 Operands[0], 9965 getValueType(ExtVT))); 9966 } 9967 } 9968 } 9969 9970 for (; i < ResNE; ++i) 9971 Scalars.push_back(getUNDEF(EltVT)); 9972 9973 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 9974 return getBuildVector(VecVT, dl, Scalars); 9975 } 9976 9977 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 9978 SDNode *N, unsigned ResNE) { 9979 unsigned Opcode = N->getOpcode(); 9980 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 9981 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 9982 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 9983 "Expected an overflow opcode"); 9984 9985 EVT ResVT = N->getValueType(0); 9986 EVT OvVT = N->getValueType(1); 9987 EVT ResEltVT = ResVT.getVectorElementType(); 9988 EVT OvEltVT = OvVT.getVectorElementType(); 9989 SDLoc dl(N); 9990 9991 // If ResNE is 0, fully unroll the vector op. 9992 unsigned NE = ResVT.getVectorNumElements(); 9993 if (ResNE == 0) 9994 ResNE = NE; 9995 else if (NE > ResNE) 9996 NE = ResNE; 9997 9998 SmallVector<SDValue, 8> LHSScalars; 9999 SmallVector<SDValue, 8> RHSScalars; 10000 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10001 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10002 10003 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10004 SDVTList VTs = getVTList(ResEltVT, SVT); 10005 SmallVector<SDValue, 8> ResScalars; 10006 SmallVector<SDValue, 8> OvScalars; 10007 for (unsigned i = 0; i < NE; ++i) { 10008 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10009 SDValue Ov = 10010 getSelect(dl, OvEltVT, Res.getValue(1), 10011 getBoolConstant(true, dl, OvEltVT, ResVT), 10012 getConstant(0, dl, OvEltVT)); 10013 10014 ResScalars.push_back(Res); 10015 OvScalars.push_back(Ov); 10016 } 10017 10018 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10019 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10020 10021 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10022 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10023 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10024 getBuildVector(NewOvVT, dl, OvScalars)); 10025 } 10026 10027 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10028 LoadSDNode *Base, 10029 unsigned Bytes, 10030 int Dist) const { 10031 if (LD->isVolatile() || Base->isVolatile()) 10032 return false; 10033 // TODO: probably too restrictive for atomics, revisit 10034 if (!LD->isSimple()) 10035 return false; 10036 if (LD->isIndexed() || Base->isIndexed()) 10037 return false; 10038 if (LD->getChain() != Base->getChain()) 10039 return false; 10040 EVT VT = LD->getValueType(0); 10041 if (VT.getSizeInBits() / 8 != Bytes) 10042 return false; 10043 10044 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10045 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10046 10047 int64_t Offset = 0; 10048 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 10049 return (Dist * Bytes == Offset); 10050 return false; 10051 } 10052 10053 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 10054 /// if it cannot be inferred. 10055 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 10056 // If this is a GlobalAddress + cst, return the alignment. 10057 const GlobalValue *GV = nullptr; 10058 int64_t GVOffset = 0; 10059 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 10060 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 10061 KnownBits Known(PtrWidth); 10062 llvm::computeKnownBits(GV, Known, getDataLayout()); 10063 unsigned AlignBits = Known.countMinTrailingZeros(); 10064 if (AlignBits) 10065 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 10066 } 10067 10068 // If this is a direct reference to a stack slot, use information about the 10069 // stack slot's alignment. 10070 int FrameIdx = INT_MIN; 10071 int64_t FrameOffset = 0; 10072 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 10073 FrameIdx = FI->getIndex(); 10074 } else if (isBaseWithConstantOffset(Ptr) && 10075 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 10076 // Handle FI+Cst 10077 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 10078 FrameOffset = Ptr.getConstantOperandVal(1); 10079 } 10080 10081 if (FrameIdx != INT_MIN) { 10082 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 10083 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 10084 } 10085 10086 return None; 10087 } 10088 10089 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 10090 /// which is split (or expanded) into two not necessarily identical pieces. 10091 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 10092 // Currently all types are split in half. 10093 EVT LoVT, HiVT; 10094 if (!VT.isVector()) 10095 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 10096 else 10097 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 10098 10099 return std::make_pair(LoVT, HiVT); 10100 } 10101 10102 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 10103 /// type, dependent on an enveloping VT that has been split into two identical 10104 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 10105 std::pair<EVT, EVT> 10106 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 10107 bool *HiIsEmpty) const { 10108 EVT EltTp = VT.getVectorElementType(); 10109 // Examples: 10110 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 10111 // custom VL=9 with enveloping VL=8/8 yields 8/1 10112 // custom VL=10 with enveloping VL=8/8 yields 8/2 10113 // etc. 10114 ElementCount VTNumElts = VT.getVectorElementCount(); 10115 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 10116 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 10117 "Mixing fixed width and scalable vectors when enveloping a type"); 10118 EVT LoVT, HiVT; 10119 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 10120 LoVT = EnvVT; 10121 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 10122 *HiIsEmpty = false; 10123 } else { 10124 // Flag that hi type has zero storage size, but return split envelop type 10125 // (this would be easier if vector types with zero elements were allowed). 10126 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 10127 HiVT = EnvVT; 10128 *HiIsEmpty = true; 10129 } 10130 return std::make_pair(LoVT, HiVT); 10131 } 10132 10133 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 10134 /// low/high part. 10135 std::pair<SDValue, SDValue> 10136 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 10137 const EVT &HiVT) { 10138 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 10139 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 10140 "Splitting vector with an invalid mixture of fixed and scalable " 10141 "vector types"); 10142 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 10143 N.getValueType().getVectorMinNumElements() && 10144 "More vector elements requested than available!"); 10145 SDValue Lo, Hi; 10146 Lo = 10147 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 10148 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 10149 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 10150 // IDX with the runtime scaling factor of the result vector type. For 10151 // fixed-width result vectors, that runtime scaling factor is 1. 10152 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 10153 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 10154 return std::make_pair(Lo, Hi); 10155 } 10156 10157 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 10158 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 10159 EVT VT = N.getValueType(); 10160 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 10161 NextPowerOf2(VT.getVectorNumElements())); 10162 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 10163 getVectorIdxConstant(0, DL)); 10164 } 10165 10166 void SelectionDAG::ExtractVectorElements(SDValue Op, 10167 SmallVectorImpl<SDValue> &Args, 10168 unsigned Start, unsigned Count, 10169 EVT EltVT) { 10170 EVT VT = Op.getValueType(); 10171 if (Count == 0) 10172 Count = VT.getVectorNumElements(); 10173 if (EltVT == EVT()) 10174 EltVT = VT.getVectorElementType(); 10175 SDLoc SL(Op); 10176 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 10177 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 10178 getVectorIdxConstant(i, SL))); 10179 } 10180 } 10181 10182 // getAddressSpace - Return the address space this GlobalAddress belongs to. 10183 unsigned GlobalAddressSDNode::getAddressSpace() const { 10184 return getGlobal()->getType()->getAddressSpace(); 10185 } 10186 10187 Type *ConstantPoolSDNode::getType() const { 10188 if (isMachineConstantPoolEntry()) 10189 return Val.MachineCPVal->getType(); 10190 return Val.ConstVal->getType(); 10191 } 10192 10193 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 10194 unsigned &SplatBitSize, 10195 bool &HasAnyUndefs, 10196 unsigned MinSplatBits, 10197 bool IsBigEndian) const { 10198 EVT VT = getValueType(0); 10199 assert(VT.isVector() && "Expected a vector type"); 10200 unsigned VecWidth = VT.getSizeInBits(); 10201 if (MinSplatBits > VecWidth) 10202 return false; 10203 10204 // FIXME: The widths are based on this node's type, but build vectors can 10205 // truncate their operands. 10206 SplatValue = APInt(VecWidth, 0); 10207 SplatUndef = APInt(VecWidth, 0); 10208 10209 // Get the bits. Bits with undefined values (when the corresponding element 10210 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 10211 // in SplatValue. If any of the values are not constant, give up and return 10212 // false. 10213 unsigned int NumOps = getNumOperands(); 10214 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 10215 unsigned EltWidth = VT.getScalarSizeInBits(); 10216 10217 for (unsigned j = 0; j < NumOps; ++j) { 10218 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 10219 SDValue OpVal = getOperand(i); 10220 unsigned BitPos = j * EltWidth; 10221 10222 if (OpVal.isUndef()) 10223 SplatUndef.setBits(BitPos, BitPos + EltWidth); 10224 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 10225 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 10226 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 10227 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 10228 else 10229 return false; 10230 } 10231 10232 // The build_vector is all constants or undefs. Find the smallest element 10233 // size that splats the vector. 10234 HasAnyUndefs = (SplatUndef != 0); 10235 10236 // FIXME: This does not work for vectors with elements less than 8 bits. 10237 while (VecWidth > 8) { 10238 unsigned HalfSize = VecWidth / 2; 10239 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 10240 APInt LowValue = SplatValue.trunc(HalfSize); 10241 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 10242 APInt LowUndef = SplatUndef.trunc(HalfSize); 10243 10244 // If the two halves do not match (ignoring undef bits), stop here. 10245 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 10246 MinSplatBits > HalfSize) 10247 break; 10248 10249 SplatValue = HighValue | LowValue; 10250 SplatUndef = HighUndef & LowUndef; 10251 10252 VecWidth = HalfSize; 10253 } 10254 10255 SplatBitSize = VecWidth; 10256 return true; 10257 } 10258 10259 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 10260 BitVector *UndefElements) const { 10261 unsigned NumOps = getNumOperands(); 10262 if (UndefElements) { 10263 UndefElements->clear(); 10264 UndefElements->resize(NumOps); 10265 } 10266 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10267 if (!DemandedElts) 10268 return SDValue(); 10269 SDValue Splatted; 10270 for (unsigned i = 0; i != NumOps; ++i) { 10271 if (!DemandedElts[i]) 10272 continue; 10273 SDValue Op = getOperand(i); 10274 if (Op.isUndef()) { 10275 if (UndefElements) 10276 (*UndefElements)[i] = true; 10277 } else if (!Splatted) { 10278 Splatted = Op; 10279 } else if (Splatted != Op) { 10280 return SDValue(); 10281 } 10282 } 10283 10284 if (!Splatted) { 10285 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 10286 assert(getOperand(FirstDemandedIdx).isUndef() && 10287 "Can only have a splat without a constant for all undefs."); 10288 return getOperand(FirstDemandedIdx); 10289 } 10290 10291 return Splatted; 10292 } 10293 10294 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 10295 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 10296 return getSplatValue(DemandedElts, UndefElements); 10297 } 10298 10299 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 10300 SmallVectorImpl<SDValue> &Sequence, 10301 BitVector *UndefElements) const { 10302 unsigned NumOps = getNumOperands(); 10303 Sequence.clear(); 10304 if (UndefElements) { 10305 UndefElements->clear(); 10306 UndefElements->resize(NumOps); 10307 } 10308 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10309 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10310 return false; 10311 10312 // Set the undefs even if we don't find a sequence (like getSplatValue). 10313 if (UndefElements) 10314 for (unsigned I = 0; I != NumOps; ++I) 10315 if (DemandedElts[I] && getOperand(I).isUndef()) 10316 (*UndefElements)[I] = true; 10317 10318 // Iteratively widen the sequence length looking for repetitions. 10319 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10320 Sequence.append(SeqLen, SDValue()); 10321 for (unsigned I = 0; I != NumOps; ++I) { 10322 if (!DemandedElts[I]) 10323 continue; 10324 SDValue &SeqOp = Sequence[I % SeqLen]; 10325 SDValue Op = getOperand(I); 10326 if (Op.isUndef()) { 10327 if (!SeqOp) 10328 SeqOp = Op; 10329 continue; 10330 } 10331 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10332 Sequence.clear(); 10333 break; 10334 } 10335 SeqOp = Op; 10336 } 10337 if (!Sequence.empty()) 10338 return true; 10339 } 10340 10341 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10342 return false; 10343 } 10344 10345 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10346 BitVector *UndefElements) const { 10347 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 10348 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10349 } 10350 10351 ConstantSDNode * 10352 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10353 BitVector *UndefElements) const { 10354 return dyn_cast_or_null<ConstantSDNode>( 10355 getSplatValue(DemandedElts, UndefElements)); 10356 } 10357 10358 ConstantSDNode * 10359 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10360 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10361 } 10362 10363 ConstantFPSDNode * 10364 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10365 BitVector *UndefElements) const { 10366 return dyn_cast_or_null<ConstantFPSDNode>( 10367 getSplatValue(DemandedElts, UndefElements)); 10368 } 10369 10370 ConstantFPSDNode * 10371 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10372 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10373 } 10374 10375 int32_t 10376 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10377 uint32_t BitWidth) const { 10378 if (ConstantFPSDNode *CN = 10379 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10380 bool IsExact; 10381 APSInt IntVal(BitWidth); 10382 const APFloat &APF = CN->getValueAPF(); 10383 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10384 APFloat::opOK || 10385 !IsExact) 10386 return -1; 10387 10388 return IntVal.exactLogBase2(); 10389 } 10390 return -1; 10391 } 10392 10393 bool BuildVectorSDNode::isConstant() const { 10394 for (const SDValue &Op : op_values()) { 10395 unsigned Opc = Op.getOpcode(); 10396 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 10397 return false; 10398 } 10399 return true; 10400 } 10401 10402 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 10403 // Find the first non-undef value in the shuffle mask. 10404 unsigned i, e; 10405 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 10406 /* search */; 10407 10408 // If all elements are undefined, this shuffle can be considered a splat 10409 // (although it should eventually get simplified away completely). 10410 if (i == e) 10411 return true; 10412 10413 // Make sure all remaining elements are either undef or the same as the first 10414 // non-undef value. 10415 for (int Idx = Mask[i]; i != e; ++i) 10416 if (Mask[i] >= 0 && Mask[i] != Idx) 10417 return false; 10418 return true; 10419 } 10420 10421 // Returns the SDNode if it is a constant integer BuildVector 10422 // or constant integer. 10423 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 10424 if (isa<ConstantSDNode>(N)) 10425 return N.getNode(); 10426 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 10427 return N.getNode(); 10428 // Treat a GlobalAddress supporting constant offset folding as a 10429 // constant integer. 10430 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 10431 if (GA->getOpcode() == ISD::GlobalAddress && 10432 TLI->isOffsetFoldingLegal(GA)) 10433 return GA; 10434 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 10435 isa<ConstantSDNode>(N.getOperand(0))) 10436 return N.getNode(); 10437 return nullptr; 10438 } 10439 10440 // Returns the SDNode if it is a constant float BuildVector 10441 // or constant float. 10442 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 10443 if (isa<ConstantFPSDNode>(N)) 10444 return N.getNode(); 10445 10446 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 10447 return N.getNode(); 10448 10449 return nullptr; 10450 } 10451 10452 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 10453 assert(!Node->OperandList && "Node already has operands"); 10454 assert(SDNode::getMaxNumOperands() >= Vals.size() && 10455 "too many operands to fit into SDNode"); 10456 SDUse *Ops = OperandRecycler.allocate( 10457 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 10458 10459 bool IsDivergent = false; 10460 for (unsigned I = 0; I != Vals.size(); ++I) { 10461 Ops[I].setUser(Node); 10462 Ops[I].setInitial(Vals[I]); 10463 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 10464 IsDivergent |= Ops[I].getNode()->isDivergent(); 10465 } 10466 Node->NumOperands = Vals.size(); 10467 Node->OperandList = Ops; 10468 if (!TLI->isSDNodeAlwaysUniform(Node)) { 10469 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 10470 Node->SDNodeBits.IsDivergent = IsDivergent; 10471 } 10472 checkForCycles(Node); 10473 } 10474 10475 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 10476 SmallVectorImpl<SDValue> &Vals) { 10477 size_t Limit = SDNode::getMaxNumOperands(); 10478 while (Vals.size() > Limit) { 10479 unsigned SliceIdx = Vals.size() - Limit; 10480 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 10481 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 10482 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 10483 Vals.emplace_back(NewTF); 10484 } 10485 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 10486 } 10487 10488 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 10489 EVT VT, SDNodeFlags Flags) { 10490 switch (Opcode) { 10491 default: 10492 return SDValue(); 10493 case ISD::ADD: 10494 case ISD::OR: 10495 case ISD::XOR: 10496 case ISD::UMAX: 10497 return getConstant(0, DL, VT); 10498 case ISD::MUL: 10499 return getConstant(1, DL, VT); 10500 case ISD::AND: 10501 case ISD::UMIN: 10502 return getAllOnesConstant(DL, VT); 10503 case ISD::SMAX: 10504 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 10505 case ISD::SMIN: 10506 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 10507 case ISD::FADD: 10508 return getConstantFP(-0.0, DL, VT); 10509 case ISD::FMUL: 10510 return getConstantFP(1.0, DL, VT); 10511 case ISD::FMINNUM: 10512 case ISD::FMAXNUM: { 10513 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 10514 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 10515 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 10516 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 10517 APFloat::getLargest(Semantics); 10518 if (Opcode == ISD::FMAXNUM) 10519 NeutralAF.changeSign(); 10520 10521 return getConstantFP(NeutralAF, DL, VT); 10522 } 10523 } 10524 } 10525 10526 #ifndef NDEBUG 10527 static void checkForCyclesHelper(const SDNode *N, 10528 SmallPtrSetImpl<const SDNode*> &Visited, 10529 SmallPtrSetImpl<const SDNode*> &Checked, 10530 const llvm::SelectionDAG *DAG) { 10531 // If this node has already been checked, don't check it again. 10532 if (Checked.count(N)) 10533 return; 10534 10535 // If a node has already been visited on this depth-first walk, reject it as 10536 // a cycle. 10537 if (!Visited.insert(N).second) { 10538 errs() << "Detected cycle in SelectionDAG\n"; 10539 dbgs() << "Offending node:\n"; 10540 N->dumprFull(DAG); dbgs() << "\n"; 10541 abort(); 10542 } 10543 10544 for (const SDValue &Op : N->op_values()) 10545 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 10546 10547 Checked.insert(N); 10548 Visited.erase(N); 10549 } 10550 #endif 10551 10552 void llvm::checkForCycles(const llvm::SDNode *N, 10553 const llvm::SelectionDAG *DAG, 10554 bool force) { 10555 #ifndef NDEBUG 10556 bool check = force; 10557 #ifdef EXPENSIVE_CHECKS 10558 check = true; 10559 #endif // EXPENSIVE_CHECKS 10560 if (check) { 10561 assert(N && "Checking nonexistent SDNode"); 10562 SmallPtrSet<const SDNode*, 32> visited; 10563 SmallPtrSet<const SDNode*, 32> checked; 10564 checkForCyclesHelper(N, visited, checked, DAG); 10565 } 10566 #endif // !NDEBUG 10567 } 10568 10569 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 10570 checkForCycles(DAG->getRoot().getNode(), DAG, force); 10571 } 10572