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 } 150 151 auto *BV = dyn_cast<BuildVectorSDNode>(N); 152 if (!BV) 153 return false; 154 155 APInt SplatUndef; 156 unsigned SplatBitSize; 157 bool HasUndefs; 158 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 159 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 160 EltSize) && 161 EltSize == SplatBitSize; 162 } 163 164 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 165 // specializations of the more general isConstantSplatVector()? 166 167 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 168 // Look through a bit convert. 169 while (N->getOpcode() == ISD::BITCAST) 170 N = N->getOperand(0).getNode(); 171 172 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 173 APInt SplatVal; 174 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue(); 175 } 176 177 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 178 179 unsigned i = 0, e = N->getNumOperands(); 180 181 // Skip over all of the undef values. 182 while (i != e && N->getOperand(i).isUndef()) 183 ++i; 184 185 // Do not accept an all-undef vector. 186 if (i == e) return false; 187 188 // Do not accept build_vectors that aren't all constants or which have non-~0 189 // elements. We have to be a bit careful here, as the type of the constant 190 // may not be the same as the type of the vector elements due to type 191 // legalization (the elements are promoted to a legal type for the target and 192 // a vector of a type may be legal when the base element type is not). 193 // We only want to check enough bits to cover the vector elements, because 194 // we care if the resultant vector is all ones, not whether the individual 195 // constants are. 196 SDValue NotZero = N->getOperand(i); 197 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 198 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 199 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 200 return false; 201 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 202 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 203 return false; 204 } else 205 return false; 206 207 // Okay, we have at least one ~0 value, check to see if the rest match or are 208 // undefs. Even with the above element type twiddling, this should be OK, as 209 // the same type legalization should have applied to all the elements. 210 for (++i; i != e; ++i) 211 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 212 return false; 213 return true; 214 } 215 216 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 217 // Look through a bit convert. 218 while (N->getOpcode() == ISD::BITCAST) 219 N = N->getOperand(0).getNode(); 220 221 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 222 APInt SplatVal; 223 return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue(); 224 } 225 226 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 227 228 bool IsAllUndef = true; 229 for (const SDValue &Op : N->op_values()) { 230 if (Op.isUndef()) 231 continue; 232 IsAllUndef = false; 233 // Do not accept build_vectors that aren't all constants or which have non-0 234 // elements. We have to be a bit careful here, as the type of the constant 235 // may not be the same as the type of the vector elements due to type 236 // legalization (the elements are promoted to a legal type for the target 237 // and a vector of a type may be legal when the base element type is not). 238 // We only want to check enough bits to cover the vector elements, because 239 // we care if the resultant vector is all zeros, not whether the individual 240 // constants are. 241 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 242 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 243 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 244 return false; 245 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 246 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 247 return false; 248 } else 249 return false; 250 } 251 252 // Do not accept an all-undef vector. 253 if (IsAllUndef) 254 return false; 255 return true; 256 } 257 258 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 259 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 260 } 261 262 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 263 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 264 } 265 266 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 267 if (N->getOpcode() != ISD::BUILD_VECTOR) 268 return false; 269 270 for (const SDValue &Op : N->op_values()) { 271 if (Op.isUndef()) 272 continue; 273 if (!isa<ConstantSDNode>(Op)) 274 return false; 275 } 276 return true; 277 } 278 279 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 280 if (N->getOpcode() != ISD::BUILD_VECTOR) 281 return false; 282 283 for (const SDValue &Op : N->op_values()) { 284 if (Op.isUndef()) 285 continue; 286 if (!isa<ConstantFPSDNode>(Op)) 287 return false; 288 } 289 return true; 290 } 291 292 bool ISD::allOperandsUndef(const SDNode *N) { 293 // Return false if the node has no operands. 294 // This is "logically inconsistent" with the definition of "all" but 295 // is probably the desired behavior. 296 if (N->getNumOperands() == 0) 297 return false; 298 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 299 } 300 301 bool ISD::matchUnaryPredicate(SDValue Op, 302 std::function<bool(ConstantSDNode *)> Match, 303 bool AllowUndefs) { 304 // FIXME: Add support for scalar UNDEF cases? 305 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 306 return Match(Cst); 307 308 // FIXME: Add support for vector UNDEF cases? 309 if (ISD::BUILD_VECTOR != Op.getOpcode() && 310 ISD::SPLAT_VECTOR != Op.getOpcode()) 311 return false; 312 313 EVT SVT = Op.getValueType().getScalarType(); 314 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 315 if (AllowUndefs && Op.getOperand(i).isUndef()) { 316 if (!Match(nullptr)) 317 return false; 318 continue; 319 } 320 321 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 322 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 323 return false; 324 } 325 return true; 326 } 327 328 bool ISD::matchBinaryPredicate( 329 SDValue LHS, SDValue RHS, 330 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 331 bool AllowUndefs, bool AllowTypeMismatch) { 332 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 333 return false; 334 335 // TODO: Add support for scalar UNDEF cases? 336 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 337 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 338 return Match(LHSCst, RHSCst); 339 340 // TODO: Add support for vector UNDEF cases? 341 if (ISD::BUILD_VECTOR != LHS.getOpcode() || 342 ISD::BUILD_VECTOR != RHS.getOpcode()) 343 return false; 344 345 EVT SVT = LHS.getValueType().getScalarType(); 346 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 347 SDValue LHSOp = LHS.getOperand(i); 348 SDValue RHSOp = RHS.getOperand(i); 349 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 350 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 351 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 352 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 353 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 354 return false; 355 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 356 LHSOp.getValueType() != RHSOp.getValueType())) 357 return false; 358 if (!Match(LHSCst, RHSCst)) 359 return false; 360 } 361 return true; 362 } 363 364 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 365 switch (VecReduceOpcode) { 366 default: 367 llvm_unreachable("Expected VECREDUCE opcode"); 368 case ISD::VECREDUCE_FADD: 369 case ISD::VECREDUCE_SEQ_FADD: 370 return ISD::FADD; 371 case ISD::VECREDUCE_FMUL: 372 case ISD::VECREDUCE_SEQ_FMUL: 373 return ISD::FMUL; 374 case ISD::VECREDUCE_ADD: 375 return ISD::ADD; 376 case ISD::VECREDUCE_MUL: 377 return ISD::MUL; 378 case ISD::VECREDUCE_AND: 379 return ISD::AND; 380 case ISD::VECREDUCE_OR: 381 return ISD::OR; 382 case ISD::VECREDUCE_XOR: 383 return ISD::XOR; 384 case ISD::VECREDUCE_SMAX: 385 return ISD::SMAX; 386 case ISD::VECREDUCE_SMIN: 387 return ISD::SMIN; 388 case ISD::VECREDUCE_UMAX: 389 return ISD::UMAX; 390 case ISD::VECREDUCE_UMIN: 391 return ISD::UMIN; 392 case ISD::VECREDUCE_FMAX: 393 return ISD::FMAXNUM; 394 case ISD::VECREDUCE_FMIN: 395 return ISD::FMINNUM; 396 } 397 } 398 399 bool ISD::isVPOpcode(unsigned Opcode) { 400 switch (Opcode) { 401 default: 402 return false; 403 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \ 404 case ISD::SDOPC: \ 405 return true; 406 #include "llvm/IR/VPIntrinsics.def" 407 } 408 } 409 410 /// The operand position of the vector mask. 411 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 412 switch (Opcode) { 413 default: 414 return None; 415 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...) \ 416 case ISD::SDOPC: \ 417 return MASKPOS; 418 #include "llvm/IR/VPIntrinsics.def" 419 } 420 } 421 422 /// The operand position of the explicit vector length parameter. 423 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 424 switch (Opcode) { 425 default: 426 return None; 427 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 428 case ISD::SDOPC: \ 429 return EVLPOS; 430 #include "llvm/IR/VPIntrinsics.def" 431 } 432 } 433 434 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 435 switch (ExtType) { 436 case ISD::EXTLOAD: 437 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 438 case ISD::SEXTLOAD: 439 return ISD::SIGN_EXTEND; 440 case ISD::ZEXTLOAD: 441 return ISD::ZERO_EXTEND; 442 default: 443 break; 444 } 445 446 llvm_unreachable("Invalid LoadExtType"); 447 } 448 449 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 450 // To perform this operation, we just need to swap the L and G bits of the 451 // operation. 452 unsigned OldL = (Operation >> 2) & 1; 453 unsigned OldG = (Operation >> 1) & 1; 454 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 455 (OldL << 1) | // New G bit 456 (OldG << 2)); // New L bit. 457 } 458 459 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 460 unsigned Operation = Op; 461 if (isIntegerLike) 462 Operation ^= 7; // Flip L, G, E bits, but not U. 463 else 464 Operation ^= 15; // Flip all of the condition bits. 465 466 if (Operation > ISD::SETTRUE2) 467 Operation &= ~8; // Don't let N and U bits get set. 468 469 return ISD::CondCode(Operation); 470 } 471 472 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 473 return getSetCCInverseImpl(Op, Type.isInteger()); 474 } 475 476 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 477 bool isIntegerLike) { 478 return getSetCCInverseImpl(Op, isIntegerLike); 479 } 480 481 /// For an integer comparison, return 1 if the comparison is a signed operation 482 /// and 2 if the result is an unsigned comparison. Return zero if the operation 483 /// does not depend on the sign of the input (setne and seteq). 484 static int isSignedOp(ISD::CondCode Opcode) { 485 switch (Opcode) { 486 default: llvm_unreachable("Illegal integer setcc operation!"); 487 case ISD::SETEQ: 488 case ISD::SETNE: return 0; 489 case ISD::SETLT: 490 case ISD::SETLE: 491 case ISD::SETGT: 492 case ISD::SETGE: return 1; 493 case ISD::SETULT: 494 case ISD::SETULE: 495 case ISD::SETUGT: 496 case ISD::SETUGE: return 2; 497 } 498 } 499 500 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 501 EVT Type) { 502 bool IsInteger = Type.isInteger(); 503 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 504 // Cannot fold a signed integer setcc with an unsigned integer setcc. 505 return ISD::SETCC_INVALID; 506 507 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 508 509 // If the N and U bits get set, then the resultant comparison DOES suddenly 510 // care about orderedness, and it is true when ordered. 511 if (Op > ISD::SETTRUE2) 512 Op &= ~16; // Clear the U bit if the N bit is set. 513 514 // Canonicalize illegal integer setcc's. 515 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 516 Op = ISD::SETNE; 517 518 return ISD::CondCode(Op); 519 } 520 521 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 522 EVT Type) { 523 bool IsInteger = Type.isInteger(); 524 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 525 // Cannot fold a signed setcc with an unsigned setcc. 526 return ISD::SETCC_INVALID; 527 528 // Combine all of the condition bits. 529 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 530 531 // Canonicalize illegal integer setcc's. 532 if (IsInteger) { 533 switch (Result) { 534 default: break; 535 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 536 case ISD::SETOEQ: // SETEQ & SETU[LG]E 537 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 538 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 539 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 540 } 541 } 542 543 return Result; 544 } 545 546 //===----------------------------------------------------------------------===// 547 // SDNode Profile Support 548 //===----------------------------------------------------------------------===// 549 550 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 551 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 552 ID.AddInteger(OpC); 553 } 554 555 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 556 /// solely with their pointer. 557 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 558 ID.AddPointer(VTList.VTs); 559 } 560 561 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 562 static void AddNodeIDOperands(FoldingSetNodeID &ID, 563 ArrayRef<SDValue> Ops) { 564 for (auto& Op : Ops) { 565 ID.AddPointer(Op.getNode()); 566 ID.AddInteger(Op.getResNo()); 567 } 568 } 569 570 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 571 static void AddNodeIDOperands(FoldingSetNodeID &ID, 572 ArrayRef<SDUse> Ops) { 573 for (auto& Op : Ops) { 574 ID.AddPointer(Op.getNode()); 575 ID.AddInteger(Op.getResNo()); 576 } 577 } 578 579 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 580 SDVTList VTList, ArrayRef<SDValue> OpList) { 581 AddNodeIDOpcode(ID, OpC); 582 AddNodeIDValueTypes(ID, VTList); 583 AddNodeIDOperands(ID, OpList); 584 } 585 586 /// If this is an SDNode with special info, add this info to the NodeID data. 587 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 588 switch (N->getOpcode()) { 589 case ISD::TargetExternalSymbol: 590 case ISD::ExternalSymbol: 591 case ISD::MCSymbol: 592 llvm_unreachable("Should only be used on nodes with operands"); 593 default: break; // Normal nodes don't need extra info. 594 case ISD::TargetConstant: 595 case ISD::Constant: { 596 const ConstantSDNode *C = cast<ConstantSDNode>(N); 597 ID.AddPointer(C->getConstantIntValue()); 598 ID.AddBoolean(C->isOpaque()); 599 break; 600 } 601 case ISD::TargetConstantFP: 602 case ISD::ConstantFP: 603 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 604 break; 605 case ISD::TargetGlobalAddress: 606 case ISD::GlobalAddress: 607 case ISD::TargetGlobalTLSAddress: 608 case ISD::GlobalTLSAddress: { 609 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 610 ID.AddPointer(GA->getGlobal()); 611 ID.AddInteger(GA->getOffset()); 612 ID.AddInteger(GA->getTargetFlags()); 613 break; 614 } 615 case ISD::BasicBlock: 616 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 617 break; 618 case ISD::Register: 619 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 620 break; 621 case ISD::RegisterMask: 622 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 623 break; 624 case ISD::SRCVALUE: 625 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 626 break; 627 case ISD::FrameIndex: 628 case ISD::TargetFrameIndex: 629 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 630 break; 631 case ISD::LIFETIME_START: 632 case ISD::LIFETIME_END: 633 if (cast<LifetimeSDNode>(N)->hasOffset()) { 634 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 635 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 636 } 637 break; 638 case ISD::PSEUDO_PROBE: 639 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 640 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 641 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 642 break; 643 case ISD::JumpTable: 644 case ISD::TargetJumpTable: 645 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 646 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 647 break; 648 case ISD::ConstantPool: 649 case ISD::TargetConstantPool: { 650 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 651 ID.AddInteger(CP->getAlign().value()); 652 ID.AddInteger(CP->getOffset()); 653 if (CP->isMachineConstantPoolEntry()) 654 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 655 else 656 ID.AddPointer(CP->getConstVal()); 657 ID.AddInteger(CP->getTargetFlags()); 658 break; 659 } 660 case ISD::TargetIndex: { 661 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 662 ID.AddInteger(TI->getIndex()); 663 ID.AddInteger(TI->getOffset()); 664 ID.AddInteger(TI->getTargetFlags()); 665 break; 666 } 667 case ISD::LOAD: { 668 const LoadSDNode *LD = cast<LoadSDNode>(N); 669 ID.AddInteger(LD->getMemoryVT().getRawBits()); 670 ID.AddInteger(LD->getRawSubclassData()); 671 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 672 break; 673 } 674 case ISD::STORE: { 675 const StoreSDNode *ST = cast<StoreSDNode>(N); 676 ID.AddInteger(ST->getMemoryVT().getRawBits()); 677 ID.AddInteger(ST->getRawSubclassData()); 678 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 679 break; 680 } 681 case ISD::MLOAD: { 682 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 683 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 684 ID.AddInteger(MLD->getRawSubclassData()); 685 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 686 break; 687 } 688 case ISD::MSTORE: { 689 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 690 ID.AddInteger(MST->getMemoryVT().getRawBits()); 691 ID.AddInteger(MST->getRawSubclassData()); 692 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 693 break; 694 } 695 case ISD::MGATHER: { 696 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 697 ID.AddInteger(MG->getMemoryVT().getRawBits()); 698 ID.AddInteger(MG->getRawSubclassData()); 699 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 700 break; 701 } 702 case ISD::MSCATTER: { 703 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 704 ID.AddInteger(MS->getMemoryVT().getRawBits()); 705 ID.AddInteger(MS->getRawSubclassData()); 706 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 707 break; 708 } 709 case ISD::ATOMIC_CMP_SWAP: 710 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 711 case ISD::ATOMIC_SWAP: 712 case ISD::ATOMIC_LOAD_ADD: 713 case ISD::ATOMIC_LOAD_SUB: 714 case ISD::ATOMIC_LOAD_AND: 715 case ISD::ATOMIC_LOAD_CLR: 716 case ISD::ATOMIC_LOAD_OR: 717 case ISD::ATOMIC_LOAD_XOR: 718 case ISD::ATOMIC_LOAD_NAND: 719 case ISD::ATOMIC_LOAD_MIN: 720 case ISD::ATOMIC_LOAD_MAX: 721 case ISD::ATOMIC_LOAD_UMIN: 722 case ISD::ATOMIC_LOAD_UMAX: 723 case ISD::ATOMIC_LOAD: 724 case ISD::ATOMIC_STORE: { 725 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 726 ID.AddInteger(AT->getMemoryVT().getRawBits()); 727 ID.AddInteger(AT->getRawSubclassData()); 728 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 729 break; 730 } 731 case ISD::PREFETCH: { 732 const MemSDNode *PF = cast<MemSDNode>(N); 733 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 734 break; 735 } 736 case ISD::VECTOR_SHUFFLE: { 737 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 738 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 739 i != e; ++i) 740 ID.AddInteger(SVN->getMaskElt(i)); 741 break; 742 } 743 case ISD::TargetBlockAddress: 744 case ISD::BlockAddress: { 745 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 746 ID.AddPointer(BA->getBlockAddress()); 747 ID.AddInteger(BA->getOffset()); 748 ID.AddInteger(BA->getTargetFlags()); 749 break; 750 } 751 } // end switch (N->getOpcode()) 752 753 // Target specific memory nodes could also have address spaces to check. 754 if (N->isTargetMemoryOpcode()) 755 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 756 } 757 758 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 759 /// data. 760 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 761 AddNodeIDOpcode(ID, N->getOpcode()); 762 // Add the return value info. 763 AddNodeIDValueTypes(ID, N->getVTList()); 764 // Add the operand info. 765 AddNodeIDOperands(ID, N->ops()); 766 767 // Handle SDNode leafs with special info. 768 AddNodeIDCustom(ID, N); 769 } 770 771 //===----------------------------------------------------------------------===// 772 // SelectionDAG Class 773 //===----------------------------------------------------------------------===// 774 775 /// doNotCSE - Return true if CSE should not be performed for this node. 776 static bool doNotCSE(SDNode *N) { 777 if (N->getValueType(0) == MVT::Glue) 778 return true; // Never CSE anything that produces a flag. 779 780 switch (N->getOpcode()) { 781 default: break; 782 case ISD::HANDLENODE: 783 case ISD::EH_LABEL: 784 return true; // Never CSE these nodes. 785 } 786 787 // Check that remaining values produced are not flags. 788 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 789 if (N->getValueType(i) == MVT::Glue) 790 return true; // Never CSE anything that produces a flag. 791 792 return false; 793 } 794 795 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 796 /// SelectionDAG. 797 void SelectionDAG::RemoveDeadNodes() { 798 // Create a dummy node (which is not added to allnodes), that adds a reference 799 // to the root node, preventing it from being deleted. 800 HandleSDNode Dummy(getRoot()); 801 802 SmallVector<SDNode*, 128> DeadNodes; 803 804 // Add all obviously-dead nodes to the DeadNodes worklist. 805 for (SDNode &Node : allnodes()) 806 if (Node.use_empty()) 807 DeadNodes.push_back(&Node); 808 809 RemoveDeadNodes(DeadNodes); 810 811 // If the root changed (e.g. it was a dead load, update the root). 812 setRoot(Dummy.getValue()); 813 } 814 815 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 816 /// given list, and any nodes that become unreachable as a result. 817 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 818 819 // Process the worklist, deleting the nodes and adding their uses to the 820 // worklist. 821 while (!DeadNodes.empty()) { 822 SDNode *N = DeadNodes.pop_back_val(); 823 // Skip to next node if we've already managed to delete the node. This could 824 // happen if replacing a node causes a node previously added to the node to 825 // be deleted. 826 if (N->getOpcode() == ISD::DELETED_NODE) 827 continue; 828 829 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 830 DUL->NodeDeleted(N, nullptr); 831 832 // Take the node out of the appropriate CSE map. 833 RemoveNodeFromCSEMaps(N); 834 835 // Next, brutally remove the operand list. This is safe to do, as there are 836 // no cycles in the graph. 837 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 838 SDUse &Use = *I++; 839 SDNode *Operand = Use.getNode(); 840 Use.set(SDValue()); 841 842 // Now that we removed this operand, see if there are no uses of it left. 843 if (Operand->use_empty()) 844 DeadNodes.push_back(Operand); 845 } 846 847 DeallocateNode(N); 848 } 849 } 850 851 void SelectionDAG::RemoveDeadNode(SDNode *N){ 852 SmallVector<SDNode*, 16> DeadNodes(1, N); 853 854 // Create a dummy node that adds a reference to the root node, preventing 855 // it from being deleted. (This matters if the root is an operand of the 856 // dead node.) 857 HandleSDNode Dummy(getRoot()); 858 859 RemoveDeadNodes(DeadNodes); 860 } 861 862 void SelectionDAG::DeleteNode(SDNode *N) { 863 // First take this out of the appropriate CSE map. 864 RemoveNodeFromCSEMaps(N); 865 866 // Finally, remove uses due to operands of this node, remove from the 867 // AllNodes list, and delete the node. 868 DeleteNodeNotInCSEMaps(N); 869 } 870 871 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 872 assert(N->getIterator() != AllNodes.begin() && 873 "Cannot delete the entry node!"); 874 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 875 876 // Drop all of the operands and decrement used node's use counts. 877 N->DropOperands(); 878 879 DeallocateNode(N); 880 } 881 882 void SDDbgInfo::erase(const SDNode *Node) { 883 DbgValMapType::iterator I = DbgValMap.find(Node); 884 if (I == DbgValMap.end()) 885 return; 886 for (auto &Val: I->second) 887 Val->setIsInvalidated(); 888 DbgValMap.erase(I); 889 } 890 891 void SelectionDAG::DeallocateNode(SDNode *N) { 892 // If we have operands, deallocate them. 893 removeOperands(N); 894 895 NodeAllocator.Deallocate(AllNodes.remove(N)); 896 897 // Set the opcode to DELETED_NODE to help catch bugs when node 898 // memory is reallocated. 899 // FIXME: There are places in SDag that have grown a dependency on the opcode 900 // value in the released node. 901 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 902 N->NodeType = ISD::DELETED_NODE; 903 904 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 905 // them and forget about that node. 906 DbgInfo->erase(N); 907 } 908 909 #ifndef NDEBUG 910 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 911 static void VerifySDNode(SDNode *N) { 912 switch (N->getOpcode()) { 913 default: 914 break; 915 case ISD::BUILD_PAIR: { 916 EVT VT = N->getValueType(0); 917 assert(N->getNumValues() == 1 && "Too many results!"); 918 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 919 "Wrong return type!"); 920 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 921 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 922 "Mismatched operand types!"); 923 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 924 "Wrong operand type!"); 925 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 926 "Wrong return type size"); 927 break; 928 } 929 case ISD::BUILD_VECTOR: { 930 assert(N->getNumValues() == 1 && "Too many results!"); 931 assert(N->getValueType(0).isVector() && "Wrong return type!"); 932 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 933 "Wrong number of operands!"); 934 EVT EltVT = N->getValueType(0).getVectorElementType(); 935 for (const SDUse &Op : N->ops()) { 936 assert((Op.getValueType() == EltVT || 937 (EltVT.isInteger() && Op.getValueType().isInteger() && 938 EltVT.bitsLE(Op.getValueType()))) && 939 "Wrong operand type!"); 940 assert(Op.getValueType() == N->getOperand(0).getValueType() && 941 "Operands must all have the same type"); 942 } 943 break; 944 } 945 } 946 } 947 #endif // NDEBUG 948 949 /// Insert a newly allocated node into the DAG. 950 /// 951 /// Handles insertion into the all nodes list and CSE map, as well as 952 /// verification and other common operations when a new node is allocated. 953 void SelectionDAG::InsertNode(SDNode *N) { 954 AllNodes.push_back(N); 955 #ifndef NDEBUG 956 N->PersistentId = NextPersistentId++; 957 VerifySDNode(N); 958 #endif 959 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 960 DUL->NodeInserted(N); 961 } 962 963 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 964 /// correspond to it. This is useful when we're about to delete or repurpose 965 /// the node. We don't want future request for structurally identical nodes 966 /// to return N anymore. 967 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 968 bool Erased = false; 969 switch (N->getOpcode()) { 970 case ISD::HANDLENODE: return false; // noop. 971 case ISD::CONDCODE: 972 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 973 "Cond code doesn't exist!"); 974 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 975 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 976 break; 977 case ISD::ExternalSymbol: 978 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 979 break; 980 case ISD::TargetExternalSymbol: { 981 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 982 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 983 ESN->getSymbol(), ESN->getTargetFlags())); 984 break; 985 } 986 case ISD::MCSymbol: { 987 auto *MCSN = cast<MCSymbolSDNode>(N); 988 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 989 break; 990 } 991 case ISD::VALUETYPE: { 992 EVT VT = cast<VTSDNode>(N)->getVT(); 993 if (VT.isExtended()) { 994 Erased = ExtendedValueTypeNodes.erase(VT); 995 } else { 996 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 997 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 998 } 999 break; 1000 } 1001 default: 1002 // Remove it from the CSE Map. 1003 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1004 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1005 Erased = CSEMap.RemoveNode(N); 1006 break; 1007 } 1008 #ifndef NDEBUG 1009 // Verify that the node was actually in one of the CSE maps, unless it has a 1010 // flag result (which cannot be CSE'd) or is one of the special cases that are 1011 // not subject to CSE. 1012 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1013 !N->isMachineOpcode() && !doNotCSE(N)) { 1014 N->dump(this); 1015 dbgs() << "\n"; 1016 llvm_unreachable("Node is not in map!"); 1017 } 1018 #endif 1019 return Erased; 1020 } 1021 1022 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1023 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1024 /// node already exists, in which case transfer all its users to the existing 1025 /// node. This transfer can potentially trigger recursive merging. 1026 void 1027 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1028 // For node types that aren't CSE'd, just act as if no identical node 1029 // already exists. 1030 if (!doNotCSE(N)) { 1031 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1032 if (Existing != N) { 1033 // If there was already an existing matching node, use ReplaceAllUsesWith 1034 // to replace the dead one with the existing one. This can cause 1035 // recursive merging of other unrelated nodes down the line. 1036 ReplaceAllUsesWith(N, Existing); 1037 1038 // N is now dead. Inform the listeners and delete it. 1039 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1040 DUL->NodeDeleted(N, Existing); 1041 DeleteNodeNotInCSEMaps(N); 1042 return; 1043 } 1044 } 1045 1046 // If the node doesn't already exist, we updated it. Inform listeners. 1047 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1048 DUL->NodeUpdated(N); 1049 } 1050 1051 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1052 /// were replaced with those specified. If this node is never memoized, 1053 /// return null, otherwise return a pointer to the slot it would take. If a 1054 /// node already exists with these operands, the slot will be non-null. 1055 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1056 void *&InsertPos) { 1057 if (doNotCSE(N)) 1058 return nullptr; 1059 1060 SDValue Ops[] = { Op }; 1061 FoldingSetNodeID ID; 1062 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1063 AddNodeIDCustom(ID, N); 1064 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1065 if (Node) 1066 Node->intersectFlagsWith(N->getFlags()); 1067 return Node; 1068 } 1069 1070 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1071 /// were replaced with those specified. If this node is never memoized, 1072 /// return null, otherwise return a pointer to the slot it would take. If a 1073 /// node already exists with these operands, the slot will be non-null. 1074 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1075 SDValue Op1, SDValue Op2, 1076 void *&InsertPos) { 1077 if (doNotCSE(N)) 1078 return nullptr; 1079 1080 SDValue Ops[] = { Op1, Op2 }; 1081 FoldingSetNodeID ID; 1082 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1083 AddNodeIDCustom(ID, N); 1084 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1085 if (Node) 1086 Node->intersectFlagsWith(N->getFlags()); 1087 return Node; 1088 } 1089 1090 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1091 /// were replaced with those specified. If this node is never memoized, 1092 /// return null, otherwise return a pointer to the slot it would take. If a 1093 /// node already exists with these operands, the slot will be non-null. 1094 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1095 void *&InsertPos) { 1096 if (doNotCSE(N)) 1097 return nullptr; 1098 1099 FoldingSetNodeID ID; 1100 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1101 AddNodeIDCustom(ID, N); 1102 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1103 if (Node) 1104 Node->intersectFlagsWith(N->getFlags()); 1105 return Node; 1106 } 1107 1108 Align SelectionDAG::getEVTAlign(EVT VT) const { 1109 Type *Ty = VT == MVT::iPTR ? 1110 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1111 VT.getTypeForEVT(*getContext()); 1112 1113 return getDataLayout().getABITypeAlign(Ty); 1114 } 1115 1116 // EntryNode could meaningfully have debug info if we can find it... 1117 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1118 : TM(tm), OptLevel(OL), 1119 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1120 Root(getEntryNode()) { 1121 InsertNode(&EntryNode); 1122 DbgInfo = new SDDbgInfo(); 1123 } 1124 1125 void SelectionDAG::init(MachineFunction &NewMF, 1126 OptimizationRemarkEmitter &NewORE, 1127 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1128 LegacyDivergenceAnalysis * Divergence, 1129 ProfileSummaryInfo *PSIin, 1130 BlockFrequencyInfo *BFIin) { 1131 MF = &NewMF; 1132 SDAGISelPass = PassPtr; 1133 ORE = &NewORE; 1134 TLI = getSubtarget().getTargetLowering(); 1135 TSI = getSubtarget().getSelectionDAGInfo(); 1136 LibInfo = LibraryInfo; 1137 Context = &MF->getFunction().getContext(); 1138 DA = Divergence; 1139 PSI = PSIin; 1140 BFI = BFIin; 1141 } 1142 1143 SelectionDAG::~SelectionDAG() { 1144 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1145 allnodes_clear(); 1146 OperandRecycler.clear(OperandAllocator); 1147 delete DbgInfo; 1148 } 1149 1150 bool SelectionDAG::shouldOptForSize() const { 1151 return MF->getFunction().hasOptSize() || 1152 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1153 } 1154 1155 void SelectionDAG::allnodes_clear() { 1156 assert(&*AllNodes.begin() == &EntryNode); 1157 AllNodes.remove(AllNodes.begin()); 1158 while (!AllNodes.empty()) 1159 DeallocateNode(&AllNodes.front()); 1160 #ifndef NDEBUG 1161 NextPersistentId = 0; 1162 #endif 1163 } 1164 1165 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1166 void *&InsertPos) { 1167 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1168 if (N) { 1169 switch (N->getOpcode()) { 1170 default: break; 1171 case ISD::Constant: 1172 case ISD::ConstantFP: 1173 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1174 "debug location. Use another overload."); 1175 } 1176 } 1177 return N; 1178 } 1179 1180 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1181 const SDLoc &DL, void *&InsertPos) { 1182 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1183 if (N) { 1184 switch (N->getOpcode()) { 1185 case ISD::Constant: 1186 case ISD::ConstantFP: 1187 // Erase debug location from the node if the node is used at several 1188 // different places. Do not propagate one location to all uses as it 1189 // will cause a worse single stepping debugging experience. 1190 if (N->getDebugLoc() != DL.getDebugLoc()) 1191 N->setDebugLoc(DebugLoc()); 1192 break; 1193 default: 1194 // When the node's point of use is located earlier in the instruction 1195 // sequence than its prior point of use, update its debug info to the 1196 // earlier location. 1197 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1198 N->setDebugLoc(DL.getDebugLoc()); 1199 break; 1200 } 1201 } 1202 return N; 1203 } 1204 1205 void SelectionDAG::clear() { 1206 allnodes_clear(); 1207 OperandRecycler.clear(OperandAllocator); 1208 OperandAllocator.Reset(); 1209 CSEMap.clear(); 1210 1211 ExtendedValueTypeNodes.clear(); 1212 ExternalSymbols.clear(); 1213 TargetExternalSymbols.clear(); 1214 MCSymbols.clear(); 1215 SDCallSiteDbgInfo.clear(); 1216 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1217 static_cast<CondCodeSDNode*>(nullptr)); 1218 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1219 static_cast<SDNode*>(nullptr)); 1220 1221 EntryNode.UseList = nullptr; 1222 InsertNode(&EntryNode); 1223 Root = getEntryNode(); 1224 DbgInfo->clear(); 1225 } 1226 1227 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1228 return VT.bitsGT(Op.getValueType()) 1229 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1230 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1231 } 1232 1233 std::pair<SDValue, SDValue> 1234 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1235 const SDLoc &DL, EVT VT) { 1236 assert(!VT.bitsEq(Op.getValueType()) && 1237 "Strict no-op FP extend/round not allowed."); 1238 SDValue Res = 1239 VT.bitsGT(Op.getValueType()) 1240 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1241 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1242 {Chain, Op, getIntPtrConstant(0, DL)}); 1243 1244 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1245 } 1246 1247 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1248 return VT.bitsGT(Op.getValueType()) ? 1249 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1250 getNode(ISD::TRUNCATE, DL, VT, Op); 1251 } 1252 1253 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1254 return VT.bitsGT(Op.getValueType()) ? 1255 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1256 getNode(ISD::TRUNCATE, DL, VT, Op); 1257 } 1258 1259 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1260 return VT.bitsGT(Op.getValueType()) ? 1261 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1262 getNode(ISD::TRUNCATE, DL, VT, Op); 1263 } 1264 1265 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1266 EVT OpVT) { 1267 if (VT.bitsLE(Op.getValueType())) 1268 return getNode(ISD::TRUNCATE, SL, VT, Op); 1269 1270 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1271 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1272 } 1273 1274 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1275 EVT OpVT = Op.getValueType(); 1276 assert(VT.isInteger() && OpVT.isInteger() && 1277 "Cannot getZeroExtendInReg FP types"); 1278 assert(VT.isVector() == OpVT.isVector() && 1279 "getZeroExtendInReg type should be vector iff the operand " 1280 "type is vector!"); 1281 assert((!VT.isVector() || 1282 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1283 "Vector element counts must match in getZeroExtendInReg"); 1284 assert(VT.bitsLE(OpVT) && "Not extending!"); 1285 if (OpVT == VT) 1286 return Op; 1287 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1288 VT.getScalarSizeInBits()); 1289 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1290 } 1291 1292 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1293 // Only unsigned pointer semantics are supported right now. In the future this 1294 // might delegate to TLI to check pointer signedness. 1295 return getZExtOrTrunc(Op, DL, VT); 1296 } 1297 1298 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1299 // Only unsigned pointer semantics are supported right now. In the future this 1300 // might delegate to TLI to check pointer signedness. 1301 return getZeroExtendInReg(Op, DL, VT); 1302 } 1303 1304 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1305 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1306 EVT EltVT = VT.getScalarType(); 1307 SDValue NegOne = 1308 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT); 1309 return getNode(ISD::XOR, DL, VT, Val, NegOne); 1310 } 1311 1312 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1313 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1314 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1315 } 1316 1317 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1318 EVT OpVT) { 1319 if (!V) 1320 return getConstant(0, DL, VT); 1321 1322 switch (TLI->getBooleanContents(OpVT)) { 1323 case TargetLowering::ZeroOrOneBooleanContent: 1324 case TargetLowering::UndefinedBooleanContent: 1325 return getConstant(1, DL, VT); 1326 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1327 return getAllOnesConstant(DL, VT); 1328 } 1329 llvm_unreachable("Unexpected boolean content enum!"); 1330 } 1331 1332 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1333 bool isT, bool isO) { 1334 EVT EltVT = VT.getScalarType(); 1335 assert((EltVT.getSizeInBits() >= 64 || 1336 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1337 "getConstant with a uint64_t value that doesn't fit in the type!"); 1338 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1339 } 1340 1341 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1342 bool isT, bool isO) { 1343 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1344 } 1345 1346 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1347 EVT VT, bool isT, bool isO) { 1348 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1349 1350 EVT EltVT = VT.getScalarType(); 1351 const ConstantInt *Elt = &Val; 1352 1353 // In some cases the vector type is legal but the element type is illegal and 1354 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1355 // inserted value (the type does not need to match the vector element type). 1356 // Any extra bits introduced will be truncated away. 1357 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1358 TargetLowering::TypePromoteInteger) { 1359 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1360 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1361 Elt = ConstantInt::get(*getContext(), NewVal); 1362 } 1363 // In other cases the element type is illegal and needs to be expanded, for 1364 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1365 // the value into n parts and use a vector type with n-times the elements. 1366 // Then bitcast to the type requested. 1367 // Legalizing constants too early makes the DAGCombiner's job harder so we 1368 // only legalize if the DAG tells us we must produce legal types. 1369 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1370 TLI->getTypeAction(*getContext(), EltVT) == 1371 TargetLowering::TypeExpandInteger) { 1372 const APInt &NewVal = Elt->getValue(); 1373 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1374 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1375 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1376 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1377 1378 // Check the temporary vector is the correct size. If this fails then 1379 // getTypeToTransformTo() probably returned a type whose size (in bits) 1380 // isn't a power-of-2 factor of the requested type size. 1381 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1382 1383 SmallVector<SDValue, 2> EltParts; 1384 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) { 1385 EltParts.push_back(getConstant( 1386 NewVal.lshr(i * ViaEltSizeInBits).zextOrTrunc(ViaEltSizeInBits), DL, 1387 ViaEltVT, isT, isO)); 1388 } 1389 1390 // EltParts is currently in little endian order. If we actually want 1391 // big-endian order then reverse it now. 1392 if (getDataLayout().isBigEndian()) 1393 std::reverse(EltParts.begin(), EltParts.end()); 1394 1395 // The elements must be reversed when the element order is different 1396 // to the endianness of the elements (because the BITCAST is itself a 1397 // vector shuffle in this situation). However, we do not need any code to 1398 // perform this reversal because getConstant() is producing a vector 1399 // splat. 1400 // This situation occurs in MIPS MSA. 1401 1402 SmallVector<SDValue, 8> Ops; 1403 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1404 llvm::append_range(Ops, EltParts); 1405 1406 SDValue V = 1407 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1408 return V; 1409 } 1410 1411 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1412 "APInt size does not match type size!"); 1413 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1414 FoldingSetNodeID ID; 1415 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1416 ID.AddPointer(Elt); 1417 ID.AddBoolean(isO); 1418 void *IP = nullptr; 1419 SDNode *N = nullptr; 1420 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1421 if (!VT.isVector()) 1422 return SDValue(N, 0); 1423 1424 if (!N) { 1425 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1426 CSEMap.InsertNode(N, IP); 1427 InsertNode(N); 1428 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1429 } 1430 1431 SDValue Result(N, 0); 1432 if (VT.isScalableVector()) 1433 Result = getSplatVector(VT, DL, Result); 1434 else if (VT.isVector()) 1435 Result = getSplatBuildVector(VT, DL, Result); 1436 1437 return Result; 1438 } 1439 1440 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1441 bool isTarget) { 1442 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1443 } 1444 1445 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1446 const SDLoc &DL, bool LegalTypes) { 1447 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1448 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1449 return getConstant(Val, DL, ShiftVT); 1450 } 1451 1452 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1453 bool isTarget) { 1454 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1455 } 1456 1457 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1458 bool isTarget) { 1459 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1460 } 1461 1462 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1463 EVT VT, bool isTarget) { 1464 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1465 1466 EVT EltVT = VT.getScalarType(); 1467 1468 // Do the map lookup using the actual bit pattern for the floating point 1469 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1470 // we don't have issues with SNANs. 1471 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1472 FoldingSetNodeID ID; 1473 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1474 ID.AddPointer(&V); 1475 void *IP = nullptr; 1476 SDNode *N = nullptr; 1477 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1478 if (!VT.isVector()) 1479 return SDValue(N, 0); 1480 1481 if (!N) { 1482 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1483 CSEMap.InsertNode(N, IP); 1484 InsertNode(N); 1485 } 1486 1487 SDValue Result(N, 0); 1488 if (VT.isScalableVector()) 1489 Result = getSplatVector(VT, DL, Result); 1490 else if (VT.isVector()) 1491 Result = getSplatBuildVector(VT, DL, Result); 1492 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1493 return Result; 1494 } 1495 1496 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1497 bool isTarget) { 1498 EVT EltVT = VT.getScalarType(); 1499 if (EltVT == MVT::f32) 1500 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1501 else if (EltVT == MVT::f64) 1502 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1503 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1504 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1505 bool Ignored; 1506 APFloat APF = APFloat(Val); 1507 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1508 &Ignored); 1509 return getConstantFP(APF, DL, VT, isTarget); 1510 } else 1511 llvm_unreachable("Unsupported type in getConstantFP"); 1512 } 1513 1514 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1515 EVT VT, int64_t Offset, bool isTargetGA, 1516 unsigned TargetFlags) { 1517 assert((TargetFlags == 0 || isTargetGA) && 1518 "Cannot set target flags on target-independent globals"); 1519 1520 // Truncate (with sign-extension) the offset value to the pointer size. 1521 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1522 if (BitWidth < 64) 1523 Offset = SignExtend64(Offset, BitWidth); 1524 1525 unsigned Opc; 1526 if (GV->isThreadLocal()) 1527 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1528 else 1529 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1530 1531 FoldingSetNodeID ID; 1532 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1533 ID.AddPointer(GV); 1534 ID.AddInteger(Offset); 1535 ID.AddInteger(TargetFlags); 1536 void *IP = nullptr; 1537 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1538 return SDValue(E, 0); 1539 1540 auto *N = newSDNode<GlobalAddressSDNode>( 1541 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1542 CSEMap.InsertNode(N, IP); 1543 InsertNode(N); 1544 return SDValue(N, 0); 1545 } 1546 1547 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1548 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1549 FoldingSetNodeID ID; 1550 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1551 ID.AddInteger(FI); 1552 void *IP = nullptr; 1553 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1554 return SDValue(E, 0); 1555 1556 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1557 CSEMap.InsertNode(N, IP); 1558 InsertNode(N); 1559 return SDValue(N, 0); 1560 } 1561 1562 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1563 unsigned TargetFlags) { 1564 assert((TargetFlags == 0 || isTarget) && 1565 "Cannot set target flags on target-independent jump tables"); 1566 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1567 FoldingSetNodeID ID; 1568 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1569 ID.AddInteger(JTI); 1570 ID.AddInteger(TargetFlags); 1571 void *IP = nullptr; 1572 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1573 return SDValue(E, 0); 1574 1575 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1576 CSEMap.InsertNode(N, IP); 1577 InsertNode(N); 1578 return SDValue(N, 0); 1579 } 1580 1581 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1582 MaybeAlign Alignment, int Offset, 1583 bool isTarget, unsigned TargetFlags) { 1584 assert((TargetFlags == 0 || isTarget) && 1585 "Cannot set target flags on target-independent globals"); 1586 if (!Alignment) 1587 Alignment = shouldOptForSize() 1588 ? getDataLayout().getABITypeAlign(C->getType()) 1589 : getDataLayout().getPrefTypeAlign(C->getType()); 1590 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1591 FoldingSetNodeID ID; 1592 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1593 ID.AddInteger(Alignment->value()); 1594 ID.AddInteger(Offset); 1595 ID.AddPointer(C); 1596 ID.AddInteger(TargetFlags); 1597 void *IP = nullptr; 1598 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1599 return SDValue(E, 0); 1600 1601 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1602 TargetFlags); 1603 CSEMap.InsertNode(N, IP); 1604 InsertNode(N); 1605 SDValue V = SDValue(N, 0); 1606 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1607 return V; 1608 } 1609 1610 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1611 MaybeAlign Alignment, int Offset, 1612 bool isTarget, unsigned TargetFlags) { 1613 assert((TargetFlags == 0 || isTarget) && 1614 "Cannot set target flags on target-independent globals"); 1615 if (!Alignment) 1616 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1617 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1618 FoldingSetNodeID ID; 1619 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1620 ID.AddInteger(Alignment->value()); 1621 ID.AddInteger(Offset); 1622 C->addSelectionDAGCSEId(ID); 1623 ID.AddInteger(TargetFlags); 1624 void *IP = nullptr; 1625 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1626 return SDValue(E, 0); 1627 1628 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1629 TargetFlags); 1630 CSEMap.InsertNode(N, IP); 1631 InsertNode(N); 1632 return SDValue(N, 0); 1633 } 1634 1635 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1636 unsigned TargetFlags) { 1637 FoldingSetNodeID ID; 1638 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1639 ID.AddInteger(Index); 1640 ID.AddInteger(Offset); 1641 ID.AddInteger(TargetFlags); 1642 void *IP = nullptr; 1643 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1644 return SDValue(E, 0); 1645 1646 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1647 CSEMap.InsertNode(N, IP); 1648 InsertNode(N); 1649 return SDValue(N, 0); 1650 } 1651 1652 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1653 FoldingSetNodeID ID; 1654 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1655 ID.AddPointer(MBB); 1656 void *IP = nullptr; 1657 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1658 return SDValue(E, 0); 1659 1660 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1661 CSEMap.InsertNode(N, IP); 1662 InsertNode(N); 1663 return SDValue(N, 0); 1664 } 1665 1666 SDValue SelectionDAG::getValueType(EVT VT) { 1667 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1668 ValueTypeNodes.size()) 1669 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1670 1671 SDNode *&N = VT.isExtended() ? 1672 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1673 1674 if (N) return SDValue(N, 0); 1675 N = newSDNode<VTSDNode>(VT); 1676 InsertNode(N); 1677 return SDValue(N, 0); 1678 } 1679 1680 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1681 SDNode *&N = ExternalSymbols[Sym]; 1682 if (N) return SDValue(N, 0); 1683 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1684 InsertNode(N); 1685 return SDValue(N, 0); 1686 } 1687 1688 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1689 SDNode *&N = MCSymbols[Sym]; 1690 if (N) 1691 return SDValue(N, 0); 1692 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1693 InsertNode(N); 1694 return SDValue(N, 0); 1695 } 1696 1697 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1698 unsigned TargetFlags) { 1699 SDNode *&N = 1700 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1701 if (N) return SDValue(N, 0); 1702 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1703 InsertNode(N); 1704 return SDValue(N, 0); 1705 } 1706 1707 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1708 if ((unsigned)Cond >= CondCodeNodes.size()) 1709 CondCodeNodes.resize(Cond+1); 1710 1711 if (!CondCodeNodes[Cond]) { 1712 auto *N = newSDNode<CondCodeSDNode>(Cond); 1713 CondCodeNodes[Cond] = N; 1714 InsertNode(N); 1715 } 1716 1717 return SDValue(CondCodeNodes[Cond], 0); 1718 } 1719 1720 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1721 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1722 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1723 std::swap(N1, N2); 1724 ShuffleVectorSDNode::commuteMask(M); 1725 } 1726 1727 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1728 SDValue N2, ArrayRef<int> Mask) { 1729 assert(VT.getVectorNumElements() == Mask.size() && 1730 "Must have the same number of vector elements as mask elements!"); 1731 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1732 "Invalid VECTOR_SHUFFLE"); 1733 1734 // Canonicalize shuffle undef, undef -> undef 1735 if (N1.isUndef() && N2.isUndef()) 1736 return getUNDEF(VT); 1737 1738 // Validate that all indices in Mask are within the range of the elements 1739 // input to the shuffle. 1740 int NElts = Mask.size(); 1741 assert(llvm::all_of(Mask, 1742 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1743 "Index out of range"); 1744 1745 // Copy the mask so we can do any needed cleanup. 1746 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1747 1748 // Canonicalize shuffle v, v -> v, undef 1749 if (N1 == N2) { 1750 N2 = getUNDEF(VT); 1751 for (int i = 0; i != NElts; ++i) 1752 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1753 } 1754 1755 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1756 if (N1.isUndef()) 1757 commuteShuffle(N1, N2, MaskVec); 1758 1759 if (TLI->hasVectorBlend()) { 1760 // If shuffling a splat, try to blend the splat instead. We do this here so 1761 // that even when this arises during lowering we don't have to re-handle it. 1762 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1763 BitVector UndefElements; 1764 SDValue Splat = BV->getSplatValue(&UndefElements); 1765 if (!Splat) 1766 return; 1767 1768 for (int i = 0; i < NElts; ++i) { 1769 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1770 continue; 1771 1772 // If this input comes from undef, mark it as such. 1773 if (UndefElements[MaskVec[i] - Offset]) { 1774 MaskVec[i] = -1; 1775 continue; 1776 } 1777 1778 // If we can blend a non-undef lane, use that instead. 1779 if (!UndefElements[i]) 1780 MaskVec[i] = i + Offset; 1781 } 1782 }; 1783 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1784 BlendSplat(N1BV, 0); 1785 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1786 BlendSplat(N2BV, NElts); 1787 } 1788 1789 // Canonicalize all index into lhs, -> shuffle lhs, undef 1790 // Canonicalize all index into rhs, -> shuffle rhs, undef 1791 bool AllLHS = true, AllRHS = true; 1792 bool N2Undef = N2.isUndef(); 1793 for (int i = 0; i != NElts; ++i) { 1794 if (MaskVec[i] >= NElts) { 1795 if (N2Undef) 1796 MaskVec[i] = -1; 1797 else 1798 AllLHS = false; 1799 } else if (MaskVec[i] >= 0) { 1800 AllRHS = false; 1801 } 1802 } 1803 if (AllLHS && AllRHS) 1804 return getUNDEF(VT); 1805 if (AllLHS && !N2Undef) 1806 N2 = getUNDEF(VT); 1807 if (AllRHS) { 1808 N1 = getUNDEF(VT); 1809 commuteShuffle(N1, N2, MaskVec); 1810 } 1811 // Reset our undef status after accounting for the mask. 1812 N2Undef = N2.isUndef(); 1813 // Re-check whether both sides ended up undef. 1814 if (N1.isUndef() && N2Undef) 1815 return getUNDEF(VT); 1816 1817 // If Identity shuffle return that node. 1818 bool Identity = true, AllSame = true; 1819 for (int i = 0; i != NElts; ++i) { 1820 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1821 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1822 } 1823 if (Identity && NElts) 1824 return N1; 1825 1826 // Shuffling a constant splat doesn't change the result. 1827 if (N2Undef) { 1828 SDValue V = N1; 1829 1830 // Look through any bitcasts. We check that these don't change the number 1831 // (and size) of elements and just changes their types. 1832 while (V.getOpcode() == ISD::BITCAST) 1833 V = V->getOperand(0); 1834 1835 // A splat should always show up as a build vector node. 1836 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1837 BitVector UndefElements; 1838 SDValue Splat = BV->getSplatValue(&UndefElements); 1839 // If this is a splat of an undef, shuffling it is also undef. 1840 if (Splat && Splat.isUndef()) 1841 return getUNDEF(VT); 1842 1843 bool SameNumElts = 1844 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1845 1846 // We only have a splat which can skip shuffles if there is a splatted 1847 // value and no undef lanes rearranged by the shuffle. 1848 if (Splat && UndefElements.none()) { 1849 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1850 // number of elements match or the value splatted is a zero constant. 1851 if (SameNumElts) 1852 return N1; 1853 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1854 if (C->isNullValue()) 1855 return N1; 1856 } 1857 1858 // If the shuffle itself creates a splat, build the vector directly. 1859 if (AllSame && SameNumElts) { 1860 EVT BuildVT = BV->getValueType(0); 1861 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1862 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1863 1864 // We may have jumped through bitcasts, so the type of the 1865 // BUILD_VECTOR may not match the type of the shuffle. 1866 if (BuildVT != VT) 1867 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1868 return NewBV; 1869 } 1870 } 1871 } 1872 1873 FoldingSetNodeID ID; 1874 SDValue Ops[2] = { N1, N2 }; 1875 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1876 for (int i = 0; i != NElts; ++i) 1877 ID.AddInteger(MaskVec[i]); 1878 1879 void* IP = nullptr; 1880 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1881 return SDValue(E, 0); 1882 1883 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1884 // SDNode doesn't have access to it. This memory will be "leaked" when 1885 // the node is deallocated, but recovered when the NodeAllocator is released. 1886 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1887 llvm::copy(MaskVec, MaskAlloc); 1888 1889 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 1890 dl.getDebugLoc(), MaskAlloc); 1891 createOperands(N, Ops); 1892 1893 CSEMap.InsertNode(N, IP); 1894 InsertNode(N); 1895 SDValue V = SDValue(N, 0); 1896 NewSDValueDbgMsg(V, "Creating new node: ", this); 1897 return V; 1898 } 1899 1900 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 1901 EVT VT = SV.getValueType(0); 1902 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 1903 ShuffleVectorSDNode::commuteMask(MaskVec); 1904 1905 SDValue Op0 = SV.getOperand(0); 1906 SDValue Op1 = SV.getOperand(1); 1907 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 1908 } 1909 1910 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1911 FoldingSetNodeID ID; 1912 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 1913 ID.AddInteger(RegNo); 1914 void *IP = nullptr; 1915 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1916 return SDValue(E, 0); 1917 1918 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 1919 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 1920 CSEMap.InsertNode(N, IP); 1921 InsertNode(N); 1922 return SDValue(N, 0); 1923 } 1924 1925 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 1926 FoldingSetNodeID ID; 1927 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 1928 ID.AddPointer(RegMask); 1929 void *IP = nullptr; 1930 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1931 return SDValue(E, 0); 1932 1933 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 1934 CSEMap.InsertNode(N, IP); 1935 InsertNode(N); 1936 return SDValue(N, 0); 1937 } 1938 1939 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 1940 MCSymbol *Label) { 1941 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 1942 } 1943 1944 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 1945 SDValue Root, MCSymbol *Label) { 1946 FoldingSetNodeID ID; 1947 SDValue Ops[] = { Root }; 1948 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 1949 ID.AddPointer(Label); 1950 void *IP = nullptr; 1951 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1952 return SDValue(E, 0); 1953 1954 auto *N = 1955 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 1956 createOperands(N, Ops); 1957 1958 CSEMap.InsertNode(N, IP); 1959 InsertNode(N); 1960 return SDValue(N, 0); 1961 } 1962 1963 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 1964 int64_t Offset, bool isTarget, 1965 unsigned TargetFlags) { 1966 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 1967 1968 FoldingSetNodeID ID; 1969 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1970 ID.AddPointer(BA); 1971 ID.AddInteger(Offset); 1972 ID.AddInteger(TargetFlags); 1973 void *IP = nullptr; 1974 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1975 return SDValue(E, 0); 1976 1977 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 1978 CSEMap.InsertNode(N, IP); 1979 InsertNode(N); 1980 return SDValue(N, 0); 1981 } 1982 1983 SDValue SelectionDAG::getSrcValue(const Value *V) { 1984 FoldingSetNodeID ID; 1985 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 1986 ID.AddPointer(V); 1987 1988 void *IP = nullptr; 1989 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1990 return SDValue(E, 0); 1991 1992 auto *N = newSDNode<SrcValueSDNode>(V); 1993 CSEMap.InsertNode(N, IP); 1994 InsertNode(N); 1995 return SDValue(N, 0); 1996 } 1997 1998 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 1999 FoldingSetNodeID ID; 2000 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2001 ID.AddPointer(MD); 2002 2003 void *IP = nullptr; 2004 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2005 return SDValue(E, 0); 2006 2007 auto *N = newSDNode<MDNodeSDNode>(MD); 2008 CSEMap.InsertNode(N, IP); 2009 InsertNode(N); 2010 return SDValue(N, 0); 2011 } 2012 2013 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2014 if (VT == V.getValueType()) 2015 return V; 2016 2017 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2018 } 2019 2020 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2021 unsigned SrcAS, unsigned DestAS) { 2022 SDValue Ops[] = {Ptr}; 2023 FoldingSetNodeID ID; 2024 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2025 ID.AddInteger(SrcAS); 2026 ID.AddInteger(DestAS); 2027 2028 void *IP = nullptr; 2029 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2030 return SDValue(E, 0); 2031 2032 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2033 VT, SrcAS, DestAS); 2034 createOperands(N, Ops); 2035 2036 CSEMap.InsertNode(N, IP); 2037 InsertNode(N); 2038 return SDValue(N, 0); 2039 } 2040 2041 SDValue SelectionDAG::getFreeze(SDValue V) { 2042 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2043 } 2044 2045 /// getShiftAmountOperand - Return the specified value casted to 2046 /// the target's desired shift amount type. 2047 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2048 EVT OpTy = Op.getValueType(); 2049 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2050 if (OpTy == ShTy || OpTy.isVector()) return Op; 2051 2052 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2053 } 2054 2055 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2056 SDLoc dl(Node); 2057 const TargetLowering &TLI = getTargetLoweringInfo(); 2058 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2059 EVT VT = Node->getValueType(0); 2060 SDValue Tmp1 = Node->getOperand(0); 2061 SDValue Tmp2 = Node->getOperand(1); 2062 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2063 2064 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2065 Tmp2, MachinePointerInfo(V)); 2066 SDValue VAList = VAListLoad; 2067 2068 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2069 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2070 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2071 2072 VAList = 2073 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2074 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2075 } 2076 2077 // Increment the pointer, VAList, to the next vaarg 2078 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2079 getConstant(getDataLayout().getTypeAllocSize( 2080 VT.getTypeForEVT(*getContext())), 2081 dl, VAList.getValueType())); 2082 // Store the incremented VAList to the legalized pointer 2083 Tmp1 = 2084 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2085 // Load the actual argument out of the pointer VAList 2086 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2087 } 2088 2089 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2090 SDLoc dl(Node); 2091 const TargetLowering &TLI = getTargetLoweringInfo(); 2092 // This defaults to loading a pointer from the input and storing it to the 2093 // output, returning the chain. 2094 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2095 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2096 SDValue Tmp1 = 2097 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2098 Node->getOperand(2), MachinePointerInfo(VS)); 2099 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2100 MachinePointerInfo(VD)); 2101 } 2102 2103 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2104 const DataLayout &DL = getDataLayout(); 2105 Type *Ty = VT.getTypeForEVT(*getContext()); 2106 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2107 2108 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2109 return RedAlign; 2110 2111 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2112 const Align StackAlign = TFI->getStackAlign(); 2113 2114 // See if we can choose a smaller ABI alignment in cases where it's an 2115 // illegal vector type that will get broken down. 2116 if (RedAlign > StackAlign) { 2117 EVT IntermediateVT; 2118 MVT RegisterVT; 2119 unsigned NumIntermediates; 2120 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2121 NumIntermediates, RegisterVT); 2122 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2123 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2124 if (RedAlign2 < RedAlign) 2125 RedAlign = RedAlign2; 2126 } 2127 2128 return RedAlign; 2129 } 2130 2131 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2132 MachineFrameInfo &MFI = MF->getFrameInfo(); 2133 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2134 int StackID = 0; 2135 if (Bytes.isScalable()) 2136 StackID = TFI->getStackIDForScalableVectors(); 2137 // The stack id gives an indication of whether the object is scalable or 2138 // not, so it's safe to pass in the minimum size here. 2139 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2140 false, nullptr, StackID); 2141 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2142 } 2143 2144 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2145 Type *Ty = VT.getTypeForEVT(*getContext()); 2146 Align StackAlign = 2147 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2148 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2149 } 2150 2151 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2152 TypeSize VT1Size = VT1.getStoreSize(); 2153 TypeSize VT2Size = VT2.getStoreSize(); 2154 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2155 "Don't know how to choose the maximum size when creating a stack " 2156 "temporary"); 2157 TypeSize Bytes = 2158 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2159 2160 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2161 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2162 const DataLayout &DL = getDataLayout(); 2163 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2164 return CreateStackTemporary(Bytes, Align); 2165 } 2166 2167 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2168 ISD::CondCode Cond, const SDLoc &dl) { 2169 EVT OpVT = N1.getValueType(); 2170 2171 // These setcc operations always fold. 2172 switch (Cond) { 2173 default: break; 2174 case ISD::SETFALSE: 2175 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2176 case ISD::SETTRUE: 2177 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2178 2179 case ISD::SETOEQ: 2180 case ISD::SETOGT: 2181 case ISD::SETOGE: 2182 case ISD::SETOLT: 2183 case ISD::SETOLE: 2184 case ISD::SETONE: 2185 case ISD::SETO: 2186 case ISD::SETUO: 2187 case ISD::SETUEQ: 2188 case ISD::SETUNE: 2189 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2190 break; 2191 } 2192 2193 if (OpVT.isInteger()) { 2194 // For EQ and NE, we can always pick a value for the undef to make the 2195 // predicate pass or fail, so we can return undef. 2196 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2197 // icmp eq/ne X, undef -> undef. 2198 if ((N1.isUndef() || N2.isUndef()) && 2199 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2200 return getUNDEF(VT); 2201 2202 // If both operands are undef, we can return undef for int comparison. 2203 // icmp undef, undef -> undef. 2204 if (N1.isUndef() && N2.isUndef()) 2205 return getUNDEF(VT); 2206 2207 // icmp X, X -> true/false 2208 // icmp X, undef -> true/false because undef could be X. 2209 if (N1 == N2) 2210 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2211 } 2212 2213 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2214 const APInt &C2 = N2C->getAPIntValue(); 2215 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2216 const APInt &C1 = N1C->getAPIntValue(); 2217 2218 switch (Cond) { 2219 default: llvm_unreachable("Unknown integer setcc!"); 2220 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT); 2221 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT); 2222 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT); 2223 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT); 2224 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT); 2225 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT); 2226 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT); 2227 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT); 2228 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT); 2229 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT); 2230 } 2231 } 2232 } 2233 2234 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2235 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2236 2237 if (N1CFP && N2CFP) { 2238 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2239 switch (Cond) { 2240 default: break; 2241 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2242 return getUNDEF(VT); 2243 LLVM_FALLTHROUGH; 2244 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2245 OpVT); 2246 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2247 return getUNDEF(VT); 2248 LLVM_FALLTHROUGH; 2249 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2250 R==APFloat::cmpLessThan, dl, VT, 2251 OpVT); 2252 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2253 return getUNDEF(VT); 2254 LLVM_FALLTHROUGH; 2255 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2256 OpVT); 2257 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2258 return getUNDEF(VT); 2259 LLVM_FALLTHROUGH; 2260 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2261 VT, OpVT); 2262 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2263 return getUNDEF(VT); 2264 LLVM_FALLTHROUGH; 2265 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2266 R==APFloat::cmpEqual, dl, VT, 2267 OpVT); 2268 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2269 return getUNDEF(VT); 2270 LLVM_FALLTHROUGH; 2271 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2272 R==APFloat::cmpEqual, dl, VT, OpVT); 2273 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2274 OpVT); 2275 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2276 OpVT); 2277 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2278 R==APFloat::cmpEqual, dl, VT, 2279 OpVT); 2280 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2281 OpVT); 2282 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2283 R==APFloat::cmpLessThan, dl, VT, 2284 OpVT); 2285 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2286 R==APFloat::cmpUnordered, dl, VT, 2287 OpVT); 2288 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2289 VT, OpVT); 2290 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2291 OpVT); 2292 } 2293 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2294 // Ensure that the constant occurs on the RHS. 2295 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2296 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2297 return SDValue(); 2298 return getSetCC(dl, VT, N2, N1, SwappedCond); 2299 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2300 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2301 // If an operand is known to be a nan (or undef that could be a nan), we can 2302 // fold it. 2303 // Choosing NaN for the undef will always make unordered comparison succeed 2304 // and ordered comparison fails. 2305 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2306 switch (ISD::getUnorderedFlavor(Cond)) { 2307 default: 2308 llvm_unreachable("Unknown flavor!"); 2309 case 0: // Known false. 2310 return getBoolConstant(false, dl, VT, OpVT); 2311 case 1: // Known true. 2312 return getBoolConstant(true, dl, VT, OpVT); 2313 case 2: // Undefined. 2314 return getUNDEF(VT); 2315 } 2316 } 2317 2318 // Could not fold it. 2319 return SDValue(); 2320 } 2321 2322 /// See if the specified operand can be simplified with the knowledge that only 2323 /// the bits specified by DemandedBits are used. 2324 /// TODO: really we should be making this into the DAG equivalent of 2325 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2326 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2327 EVT VT = V.getValueType(); 2328 2329 if (VT.isScalableVector()) 2330 return SDValue(); 2331 2332 APInt DemandedElts = VT.isVector() 2333 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2334 : APInt(1, 1); 2335 return GetDemandedBits(V, DemandedBits, DemandedElts); 2336 } 2337 2338 /// See if the specified operand can be simplified with the knowledge that only 2339 /// the bits specified by DemandedBits are used in the elements specified by 2340 /// DemandedElts. 2341 /// TODO: really we should be making this into the DAG equivalent of 2342 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2343 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2344 const APInt &DemandedElts) { 2345 switch (V.getOpcode()) { 2346 default: 2347 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2348 *this, 0); 2349 case ISD::Constant: { 2350 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2351 APInt NewVal = CVal & DemandedBits; 2352 if (NewVal != CVal) 2353 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2354 break; 2355 } 2356 case ISD::SRL: 2357 // Only look at single-use SRLs. 2358 if (!V.getNode()->hasOneUse()) 2359 break; 2360 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2361 // See if we can recursively simplify the LHS. 2362 unsigned Amt = RHSC->getZExtValue(); 2363 2364 // Watch out for shift count overflow though. 2365 if (Amt >= DemandedBits.getBitWidth()) 2366 break; 2367 APInt SrcDemandedBits = DemandedBits << Amt; 2368 if (SDValue SimplifyLHS = 2369 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2370 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2371 V.getOperand(1)); 2372 } 2373 break; 2374 } 2375 return SDValue(); 2376 } 2377 2378 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2379 /// use this predicate to simplify operations downstream. 2380 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2381 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2382 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2383 } 2384 2385 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2386 /// this predicate to simplify operations downstream. Mask is known to be zero 2387 /// for bits that V cannot have. 2388 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2389 unsigned Depth) const { 2390 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2391 } 2392 2393 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2394 /// DemandedElts. We use this predicate to simplify operations downstream. 2395 /// Mask is known to be zero for bits that V cannot have. 2396 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2397 const APInt &DemandedElts, 2398 unsigned Depth) const { 2399 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2400 } 2401 2402 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2403 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2404 unsigned Depth) const { 2405 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2406 } 2407 2408 /// isSplatValue - Return true if the vector V has the same value 2409 /// across all DemandedElts. For scalable vectors it does not make 2410 /// sense to specify which elements are demanded or undefined, therefore 2411 /// they are simply ignored. 2412 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2413 APInt &UndefElts, unsigned Depth) { 2414 EVT VT = V.getValueType(); 2415 assert(VT.isVector() && "Vector type expected"); 2416 2417 if (!VT.isScalableVector() && !DemandedElts) 2418 return false; // No demanded elts, better to assume we don't know anything. 2419 2420 if (Depth >= MaxRecursionDepth) 2421 return false; // Limit search depth. 2422 2423 // Deal with some common cases here that work for both fixed and scalable 2424 // vector types. 2425 switch (V.getOpcode()) { 2426 case ISD::SPLAT_VECTOR: 2427 UndefElts = V.getOperand(0).isUndef() 2428 ? APInt::getAllOnesValue(DemandedElts.getBitWidth()) 2429 : APInt(DemandedElts.getBitWidth(), 0); 2430 return true; 2431 case ISD::ADD: 2432 case ISD::SUB: 2433 case ISD::AND: 2434 case ISD::XOR: 2435 case ISD::OR: { 2436 APInt UndefLHS, UndefRHS; 2437 SDValue LHS = V.getOperand(0); 2438 SDValue RHS = V.getOperand(1); 2439 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2440 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2441 UndefElts = UndefLHS | UndefRHS; 2442 return true; 2443 } 2444 break; 2445 } 2446 case ISD::TRUNCATE: 2447 case ISD::SIGN_EXTEND: 2448 case ISD::ZERO_EXTEND: 2449 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2450 } 2451 2452 // We don't support other cases than those above for scalable vectors at 2453 // the moment. 2454 if (VT.isScalableVector()) 2455 return false; 2456 2457 unsigned NumElts = VT.getVectorNumElements(); 2458 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2459 UndefElts = APInt::getNullValue(NumElts); 2460 2461 switch (V.getOpcode()) { 2462 case ISD::BUILD_VECTOR: { 2463 SDValue Scl; 2464 for (unsigned i = 0; i != NumElts; ++i) { 2465 SDValue Op = V.getOperand(i); 2466 if (Op.isUndef()) { 2467 UndefElts.setBit(i); 2468 continue; 2469 } 2470 if (!DemandedElts[i]) 2471 continue; 2472 if (Scl && Scl != Op) 2473 return false; 2474 Scl = Op; 2475 } 2476 return true; 2477 } 2478 case ISD::VECTOR_SHUFFLE: { 2479 // Check if this is a shuffle node doing a splat. 2480 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2481 int SplatIndex = -1; 2482 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2483 for (int i = 0; i != (int)NumElts; ++i) { 2484 int M = Mask[i]; 2485 if (M < 0) { 2486 UndefElts.setBit(i); 2487 continue; 2488 } 2489 if (!DemandedElts[i]) 2490 continue; 2491 if (0 <= SplatIndex && SplatIndex != M) 2492 return false; 2493 SplatIndex = M; 2494 } 2495 return true; 2496 } 2497 case ISD::EXTRACT_SUBVECTOR: { 2498 // Offset the demanded elts by the subvector index. 2499 SDValue Src = V.getOperand(0); 2500 uint64_t Idx = V.getConstantOperandVal(1); 2501 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2502 APInt UndefSrcElts; 2503 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2504 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2505 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2506 return true; 2507 } 2508 break; 2509 } 2510 } 2511 2512 return false; 2513 } 2514 2515 /// Helper wrapper to main isSplatValue function. 2516 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) { 2517 EVT VT = V.getValueType(); 2518 assert(VT.isVector() && "Vector type expected"); 2519 2520 APInt UndefElts; 2521 APInt DemandedElts; 2522 2523 // For now we don't support this with scalable vectors. 2524 if (!VT.isScalableVector()) 2525 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2526 return isSplatValue(V, DemandedElts, UndefElts) && 2527 (AllowUndefs || !UndefElts); 2528 } 2529 2530 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2531 V = peekThroughExtractSubvectors(V); 2532 2533 EVT VT = V.getValueType(); 2534 unsigned Opcode = V.getOpcode(); 2535 switch (Opcode) { 2536 default: { 2537 APInt UndefElts; 2538 APInt DemandedElts; 2539 2540 if (!VT.isScalableVector()) 2541 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2542 2543 if (isSplatValue(V, DemandedElts, UndefElts)) { 2544 if (VT.isScalableVector()) { 2545 // DemandedElts and UndefElts are ignored for scalable vectors, since 2546 // the only supported cases are SPLAT_VECTOR nodes. 2547 SplatIdx = 0; 2548 } else { 2549 // Handle case where all demanded elements are UNDEF. 2550 if (DemandedElts.isSubsetOf(UndefElts)) { 2551 SplatIdx = 0; 2552 return getUNDEF(VT); 2553 } 2554 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2555 } 2556 return V; 2557 } 2558 break; 2559 } 2560 case ISD::SPLAT_VECTOR: 2561 SplatIdx = 0; 2562 return V; 2563 case ISD::VECTOR_SHUFFLE: { 2564 if (VT.isScalableVector()) 2565 return SDValue(); 2566 2567 // Check if this is a shuffle node doing a splat. 2568 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2569 // getTargetVShiftNode currently struggles without the splat source. 2570 auto *SVN = cast<ShuffleVectorSDNode>(V); 2571 if (!SVN->isSplat()) 2572 break; 2573 int Idx = SVN->getSplatIndex(); 2574 int NumElts = V.getValueType().getVectorNumElements(); 2575 SplatIdx = Idx % NumElts; 2576 return V.getOperand(Idx / NumElts); 2577 } 2578 } 2579 2580 return SDValue(); 2581 } 2582 2583 SDValue SelectionDAG::getSplatValue(SDValue V) { 2584 int SplatIdx; 2585 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) 2586 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), 2587 SrcVector.getValueType().getScalarType(), SrcVector, 2588 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2589 return SDValue(); 2590 } 2591 2592 const APInt * 2593 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2594 const APInt &DemandedElts) const { 2595 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2596 V.getOpcode() == ISD::SRA) && 2597 "Unknown shift node"); 2598 unsigned BitWidth = V.getScalarValueSizeInBits(); 2599 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2600 // Shifting more than the bitwidth is not valid. 2601 const APInt &ShAmt = SA->getAPIntValue(); 2602 if (ShAmt.ult(BitWidth)) 2603 return &ShAmt; 2604 } 2605 return nullptr; 2606 } 2607 2608 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2609 SDValue V, const APInt &DemandedElts) const { 2610 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2611 V.getOpcode() == ISD::SRA) && 2612 "Unknown shift node"); 2613 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2614 return ValidAmt; 2615 unsigned BitWidth = V.getScalarValueSizeInBits(); 2616 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2617 if (!BV) 2618 return nullptr; 2619 const APInt *MinShAmt = nullptr; 2620 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2621 if (!DemandedElts[i]) 2622 continue; 2623 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2624 if (!SA) 2625 return nullptr; 2626 // Shifting more than the bitwidth is not valid. 2627 const APInt &ShAmt = SA->getAPIntValue(); 2628 if (ShAmt.uge(BitWidth)) 2629 return nullptr; 2630 if (MinShAmt && MinShAmt->ule(ShAmt)) 2631 continue; 2632 MinShAmt = &ShAmt; 2633 } 2634 return MinShAmt; 2635 } 2636 2637 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2638 SDValue V, const APInt &DemandedElts) const { 2639 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2640 V.getOpcode() == ISD::SRA) && 2641 "Unknown shift node"); 2642 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2643 return ValidAmt; 2644 unsigned BitWidth = V.getScalarValueSizeInBits(); 2645 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2646 if (!BV) 2647 return nullptr; 2648 const APInt *MaxShAmt = nullptr; 2649 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2650 if (!DemandedElts[i]) 2651 continue; 2652 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2653 if (!SA) 2654 return nullptr; 2655 // Shifting more than the bitwidth is not valid. 2656 const APInt &ShAmt = SA->getAPIntValue(); 2657 if (ShAmt.uge(BitWidth)) 2658 return nullptr; 2659 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2660 continue; 2661 MaxShAmt = &ShAmt; 2662 } 2663 return MaxShAmt; 2664 } 2665 2666 /// Determine which bits of Op are known to be either zero or one and return 2667 /// them in Known. For vectors, the known bits are those that are shared by 2668 /// every vector element. 2669 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2670 EVT VT = Op.getValueType(); 2671 2672 // TOOD: Until we have a plan for how to represent demanded elements for 2673 // scalable vectors, we can just bail out for now. 2674 if (Op.getValueType().isScalableVector()) { 2675 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2676 return KnownBits(BitWidth); 2677 } 2678 2679 APInt DemandedElts = VT.isVector() 2680 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2681 : APInt(1, 1); 2682 return computeKnownBits(Op, DemandedElts, Depth); 2683 } 2684 2685 /// Determine which bits of Op are known to be either zero or one and return 2686 /// them in Known. The DemandedElts argument allows us to only collect the known 2687 /// bits that are shared by the requested vector elements. 2688 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2689 unsigned Depth) const { 2690 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2691 2692 KnownBits Known(BitWidth); // Don't know anything. 2693 2694 // TOOD: Until we have a plan for how to represent demanded elements for 2695 // scalable vectors, we can just bail out for now. 2696 if (Op.getValueType().isScalableVector()) 2697 return Known; 2698 2699 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2700 // We know all of the bits for a constant! 2701 return KnownBits::makeConstant(C->getAPIntValue()); 2702 } 2703 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2704 // We know all of the bits for a constant fp! 2705 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2706 } 2707 2708 if (Depth >= MaxRecursionDepth) 2709 return Known; // Limit search depth. 2710 2711 KnownBits Known2; 2712 unsigned NumElts = DemandedElts.getBitWidth(); 2713 assert((!Op.getValueType().isVector() || 2714 NumElts == Op.getValueType().getVectorNumElements()) && 2715 "Unexpected vector size"); 2716 2717 if (!DemandedElts) 2718 return Known; // No demanded elts, better to assume we don't know anything. 2719 2720 unsigned Opcode = Op.getOpcode(); 2721 switch (Opcode) { 2722 case ISD::BUILD_VECTOR: 2723 // Collect the known bits that are shared by every demanded vector element. 2724 Known.Zero.setAllBits(); Known.One.setAllBits(); 2725 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2726 if (!DemandedElts[i]) 2727 continue; 2728 2729 SDValue SrcOp = Op.getOperand(i); 2730 Known2 = computeKnownBits(SrcOp, Depth + 1); 2731 2732 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2733 if (SrcOp.getValueSizeInBits() != BitWidth) { 2734 assert(SrcOp.getValueSizeInBits() > BitWidth && 2735 "Expected BUILD_VECTOR implicit truncation"); 2736 Known2 = Known2.trunc(BitWidth); 2737 } 2738 2739 // Known bits are the values that are shared by every demanded element. 2740 Known = KnownBits::commonBits(Known, Known2); 2741 2742 // If we don't know any bits, early out. 2743 if (Known.isUnknown()) 2744 break; 2745 } 2746 break; 2747 case ISD::VECTOR_SHUFFLE: { 2748 // Collect the known bits that are shared by every vector element referenced 2749 // by the shuffle. 2750 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2751 Known.Zero.setAllBits(); Known.One.setAllBits(); 2752 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2753 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2754 for (unsigned i = 0; i != NumElts; ++i) { 2755 if (!DemandedElts[i]) 2756 continue; 2757 2758 int M = SVN->getMaskElt(i); 2759 if (M < 0) { 2760 // For UNDEF elements, we don't know anything about the common state of 2761 // the shuffle result. 2762 Known.resetAll(); 2763 DemandedLHS.clearAllBits(); 2764 DemandedRHS.clearAllBits(); 2765 break; 2766 } 2767 2768 if ((unsigned)M < NumElts) 2769 DemandedLHS.setBit((unsigned)M % NumElts); 2770 else 2771 DemandedRHS.setBit((unsigned)M % NumElts); 2772 } 2773 // Known bits are the values that are shared by every demanded element. 2774 if (!!DemandedLHS) { 2775 SDValue LHS = Op.getOperand(0); 2776 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2777 Known = KnownBits::commonBits(Known, Known2); 2778 } 2779 // If we don't know any bits, early out. 2780 if (Known.isUnknown()) 2781 break; 2782 if (!!DemandedRHS) { 2783 SDValue RHS = Op.getOperand(1); 2784 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2785 Known = KnownBits::commonBits(Known, Known2); 2786 } 2787 break; 2788 } 2789 case ISD::CONCAT_VECTORS: { 2790 // Split DemandedElts and test each of the demanded subvectors. 2791 Known.Zero.setAllBits(); Known.One.setAllBits(); 2792 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2793 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2794 unsigned NumSubVectors = Op.getNumOperands(); 2795 for (unsigned i = 0; i != NumSubVectors; ++i) { 2796 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); 2797 DemandedSub = DemandedSub.trunc(NumSubVectorElts); 2798 if (!!DemandedSub) { 2799 SDValue Sub = Op.getOperand(i); 2800 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2801 Known = KnownBits::commonBits(Known, Known2); 2802 } 2803 // If we don't know any bits, early out. 2804 if (Known.isUnknown()) 2805 break; 2806 } 2807 break; 2808 } 2809 case ISD::INSERT_SUBVECTOR: { 2810 // Demand any elements from the subvector and the remainder from the src its 2811 // inserted into. 2812 SDValue Src = Op.getOperand(0); 2813 SDValue Sub = Op.getOperand(1); 2814 uint64_t Idx = Op.getConstantOperandVal(2); 2815 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2816 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2817 APInt DemandedSrcElts = DemandedElts; 2818 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 2819 2820 Known.One.setAllBits(); 2821 Known.Zero.setAllBits(); 2822 if (!!DemandedSubElts) { 2823 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2824 if (Known.isUnknown()) 2825 break; // early-out. 2826 } 2827 if (!!DemandedSrcElts) { 2828 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2829 Known = KnownBits::commonBits(Known, Known2); 2830 } 2831 break; 2832 } 2833 case ISD::EXTRACT_SUBVECTOR: { 2834 // Offset the demanded elts by the subvector index. 2835 SDValue Src = Op.getOperand(0); 2836 // Bail until we can represent demanded elements for scalable vectors. 2837 if (Src.getValueType().isScalableVector()) 2838 break; 2839 uint64_t Idx = Op.getConstantOperandVal(1); 2840 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2841 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2842 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2843 break; 2844 } 2845 case ISD::SCALAR_TO_VECTOR: { 2846 // We know about scalar_to_vector as much as we know about it source, 2847 // which becomes the first element of otherwise unknown vector. 2848 if (DemandedElts != 1) 2849 break; 2850 2851 SDValue N0 = Op.getOperand(0); 2852 Known = computeKnownBits(N0, Depth + 1); 2853 if (N0.getValueSizeInBits() != BitWidth) 2854 Known = Known.trunc(BitWidth); 2855 2856 break; 2857 } 2858 case ISD::BITCAST: { 2859 SDValue N0 = Op.getOperand(0); 2860 EVT SubVT = N0.getValueType(); 2861 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 2862 2863 // Ignore bitcasts from unsupported types. 2864 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 2865 break; 2866 2867 // Fast handling of 'identity' bitcasts. 2868 if (BitWidth == SubBitWidth) { 2869 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 2870 break; 2871 } 2872 2873 bool IsLE = getDataLayout().isLittleEndian(); 2874 2875 // Bitcast 'small element' vector to 'large element' scalar/vector. 2876 if ((BitWidth % SubBitWidth) == 0) { 2877 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 2878 2879 // Collect known bits for the (larger) output by collecting the known 2880 // bits from each set of sub elements and shift these into place. 2881 // We need to separately call computeKnownBits for each set of 2882 // sub elements as the knownbits for each is likely to be different. 2883 unsigned SubScale = BitWidth / SubBitWidth; 2884 APInt SubDemandedElts(NumElts * SubScale, 0); 2885 for (unsigned i = 0; i != NumElts; ++i) 2886 if (DemandedElts[i]) 2887 SubDemandedElts.setBit(i * SubScale); 2888 2889 for (unsigned i = 0; i != SubScale; ++i) { 2890 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 2891 Depth + 1); 2892 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 2893 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts); 2894 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts); 2895 } 2896 } 2897 2898 // Bitcast 'large element' scalar/vector to 'small element' vector. 2899 if ((SubBitWidth % BitWidth) == 0) { 2900 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 2901 2902 // Collect known bits for the (smaller) output by collecting the known 2903 // bits from the overlapping larger input elements and extracting the 2904 // sub sections we actually care about. 2905 unsigned SubScale = SubBitWidth / BitWidth; 2906 APInt SubDemandedElts(NumElts / SubScale, 0); 2907 for (unsigned i = 0; i != NumElts; ++i) 2908 if (DemandedElts[i]) 2909 SubDemandedElts.setBit(i / SubScale); 2910 2911 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 2912 2913 Known.Zero.setAllBits(); Known.One.setAllBits(); 2914 for (unsigned i = 0; i != NumElts; ++i) 2915 if (DemandedElts[i]) { 2916 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 2917 unsigned Offset = (Shifts % SubScale) * BitWidth; 2918 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth); 2919 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth); 2920 // If we don't know any bits, early out. 2921 if (Known.isUnknown()) 2922 break; 2923 } 2924 } 2925 break; 2926 } 2927 case ISD::AND: 2928 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2929 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2930 2931 Known &= Known2; 2932 break; 2933 case ISD::OR: 2934 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2935 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2936 2937 Known |= Known2; 2938 break; 2939 case ISD::XOR: 2940 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2941 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2942 2943 Known ^= Known2; 2944 break; 2945 case ISD::MUL: { 2946 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2947 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2948 Known = KnownBits::computeForMul(Known, Known2); 2949 break; 2950 } 2951 case ISD::UDIV: { 2952 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2953 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2954 Known = KnownBits::udiv(Known, Known2); 2955 break; 2956 } 2957 case ISD::SELECT: 2958 case ISD::VSELECT: 2959 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 2960 // If we don't know any bits, early out. 2961 if (Known.isUnknown()) 2962 break; 2963 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 2964 2965 // Only known if known in both the LHS and RHS. 2966 Known = KnownBits::commonBits(Known, Known2); 2967 break; 2968 case ISD::SELECT_CC: 2969 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 2970 // If we don't know any bits, early out. 2971 if (Known.isUnknown()) 2972 break; 2973 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 2974 2975 // Only known if known in both the LHS and RHS. 2976 Known = KnownBits::commonBits(Known, Known2); 2977 break; 2978 case ISD::SMULO: 2979 case ISD::UMULO: 2980 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 2981 if (Op.getResNo() != 1) 2982 break; 2983 // The boolean result conforms to getBooleanContents. 2984 // If we know the result of a setcc has the top bits zero, use this info. 2985 // We know that we have an integer-based boolean since these operations 2986 // are only available for integer. 2987 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 2988 TargetLowering::ZeroOrOneBooleanContent && 2989 BitWidth > 1) 2990 Known.Zero.setBitsFrom(1); 2991 break; 2992 case ISD::SETCC: 2993 case ISD::STRICT_FSETCC: 2994 case ISD::STRICT_FSETCCS: { 2995 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 2996 // If we know the result of a setcc has the top bits zero, use this info. 2997 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 2998 TargetLowering::ZeroOrOneBooleanContent && 2999 BitWidth > 1) 3000 Known.Zero.setBitsFrom(1); 3001 break; 3002 } 3003 case ISD::SHL: 3004 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3005 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3006 Known = KnownBits::shl(Known, Known2); 3007 3008 // Minimum shift low bits are known zero. 3009 if (const APInt *ShMinAmt = 3010 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3011 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3012 break; 3013 case ISD::SRL: 3014 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3015 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3016 Known = KnownBits::lshr(Known, Known2); 3017 3018 // Minimum shift high bits are known zero. 3019 if (const APInt *ShMinAmt = 3020 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3021 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3022 break; 3023 case ISD::SRA: 3024 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3025 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3026 Known = KnownBits::ashr(Known, Known2); 3027 // TODO: Add minimum shift high known sign bits. 3028 break; 3029 case ISD::FSHL: 3030 case ISD::FSHR: 3031 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3032 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3033 3034 // For fshl, 0-shift returns the 1st arg. 3035 // For fshr, 0-shift returns the 2nd arg. 3036 if (Amt == 0) { 3037 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3038 DemandedElts, Depth + 1); 3039 break; 3040 } 3041 3042 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3043 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3044 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3045 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3046 if (Opcode == ISD::FSHL) { 3047 Known.One <<= Amt; 3048 Known.Zero <<= Amt; 3049 Known2.One.lshrInPlace(BitWidth - Amt); 3050 Known2.Zero.lshrInPlace(BitWidth - Amt); 3051 } else { 3052 Known.One <<= BitWidth - Amt; 3053 Known.Zero <<= BitWidth - Amt; 3054 Known2.One.lshrInPlace(Amt); 3055 Known2.Zero.lshrInPlace(Amt); 3056 } 3057 Known.One |= Known2.One; 3058 Known.Zero |= Known2.Zero; 3059 } 3060 break; 3061 case ISD::SIGN_EXTEND_INREG: { 3062 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3063 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3064 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3065 break; 3066 } 3067 case ISD::CTTZ: 3068 case ISD::CTTZ_ZERO_UNDEF: { 3069 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3070 // If we have a known 1, its position is our upper bound. 3071 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3072 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3073 Known.Zero.setBitsFrom(LowBits); 3074 break; 3075 } 3076 case ISD::CTLZ: 3077 case ISD::CTLZ_ZERO_UNDEF: { 3078 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3079 // If we have a known 1, its position is our upper bound. 3080 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3081 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3082 Known.Zero.setBitsFrom(LowBits); 3083 break; 3084 } 3085 case ISD::CTPOP: { 3086 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3087 // If we know some of the bits are zero, they can't be one. 3088 unsigned PossibleOnes = Known2.countMaxPopulation(); 3089 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3090 break; 3091 } 3092 case ISD::PARITY: { 3093 // Parity returns 0 everywhere but the LSB. 3094 Known.Zero.setBitsFrom(1); 3095 break; 3096 } 3097 case ISD::LOAD: { 3098 LoadSDNode *LD = cast<LoadSDNode>(Op); 3099 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3100 if (ISD::isNON_EXTLoad(LD) && Cst) { 3101 // Determine any common known bits from the loaded constant pool value. 3102 Type *CstTy = Cst->getType(); 3103 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3104 // If its a vector splat, then we can (quickly) reuse the scalar path. 3105 // NOTE: We assume all elements match and none are UNDEF. 3106 if (CstTy->isVectorTy()) { 3107 if (const Constant *Splat = Cst->getSplatValue()) { 3108 Cst = Splat; 3109 CstTy = Cst->getType(); 3110 } 3111 } 3112 // TODO - do we need to handle different bitwidths? 3113 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3114 // Iterate across all vector elements finding common known bits. 3115 Known.One.setAllBits(); 3116 Known.Zero.setAllBits(); 3117 for (unsigned i = 0; i != NumElts; ++i) { 3118 if (!DemandedElts[i]) 3119 continue; 3120 if (Constant *Elt = Cst->getAggregateElement(i)) { 3121 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3122 const APInt &Value = CInt->getValue(); 3123 Known.One &= Value; 3124 Known.Zero &= ~Value; 3125 continue; 3126 } 3127 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3128 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3129 Known.One &= Value; 3130 Known.Zero &= ~Value; 3131 continue; 3132 } 3133 } 3134 Known.One.clearAllBits(); 3135 Known.Zero.clearAllBits(); 3136 break; 3137 } 3138 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3139 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3140 Known = KnownBits::makeConstant(CInt->getValue()); 3141 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3142 Known = 3143 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3144 } 3145 } 3146 } 3147 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3148 // If this is a ZEXTLoad and we are looking at the loaded value. 3149 EVT VT = LD->getMemoryVT(); 3150 unsigned MemBits = VT.getScalarSizeInBits(); 3151 Known.Zero.setBitsFrom(MemBits); 3152 } else if (const MDNode *Ranges = LD->getRanges()) { 3153 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3154 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3155 } 3156 break; 3157 } 3158 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3159 EVT InVT = Op.getOperand(0).getValueType(); 3160 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3161 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3162 Known = Known.zext(BitWidth); 3163 break; 3164 } 3165 case ISD::ZERO_EXTEND: { 3166 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3167 Known = Known.zext(BitWidth); 3168 break; 3169 } 3170 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3171 EVT InVT = Op.getOperand(0).getValueType(); 3172 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3173 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3174 // If the sign bit is known to be zero or one, then sext will extend 3175 // it to the top bits, else it will just zext. 3176 Known = Known.sext(BitWidth); 3177 break; 3178 } 3179 case ISD::SIGN_EXTEND: { 3180 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3181 // If the sign bit is known to be zero or one, then sext will extend 3182 // it to the top bits, else it will just zext. 3183 Known = Known.sext(BitWidth); 3184 break; 3185 } 3186 case ISD::ANY_EXTEND_VECTOR_INREG: { 3187 EVT InVT = Op.getOperand(0).getValueType(); 3188 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3189 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3190 Known = Known.anyext(BitWidth); 3191 break; 3192 } 3193 case ISD::ANY_EXTEND: { 3194 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3195 Known = Known.anyext(BitWidth); 3196 break; 3197 } 3198 case ISD::TRUNCATE: { 3199 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3200 Known = Known.trunc(BitWidth); 3201 break; 3202 } 3203 case ISD::AssertZext: { 3204 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3205 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3206 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3207 Known.Zero |= (~InMask); 3208 Known.One &= (~Known.Zero); 3209 break; 3210 } 3211 case ISD::AssertAlign: { 3212 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3213 assert(LogOfAlign != 0); 3214 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3215 // well as clearing one bits. 3216 Known.Zero.setLowBits(LogOfAlign); 3217 Known.One.clearLowBits(LogOfAlign); 3218 break; 3219 } 3220 case ISD::FGETSIGN: 3221 // All bits are zero except the low bit. 3222 Known.Zero.setBitsFrom(1); 3223 break; 3224 case ISD::USUBO: 3225 case ISD::SSUBO: 3226 if (Op.getResNo() == 1) { 3227 // If we know the result of a setcc has the top bits zero, use this info. 3228 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3229 TargetLowering::ZeroOrOneBooleanContent && 3230 BitWidth > 1) 3231 Known.Zero.setBitsFrom(1); 3232 break; 3233 } 3234 LLVM_FALLTHROUGH; 3235 case ISD::SUB: 3236 case ISD::SUBC: { 3237 assert(Op.getResNo() == 0 && 3238 "We only compute knownbits for the difference here."); 3239 3240 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3241 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3242 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3243 Known, Known2); 3244 break; 3245 } 3246 case ISD::UADDO: 3247 case ISD::SADDO: 3248 case ISD::ADDCARRY: 3249 if (Op.getResNo() == 1) { 3250 // If we know the result of a setcc has the top bits zero, use this info. 3251 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3252 TargetLowering::ZeroOrOneBooleanContent && 3253 BitWidth > 1) 3254 Known.Zero.setBitsFrom(1); 3255 break; 3256 } 3257 LLVM_FALLTHROUGH; 3258 case ISD::ADD: 3259 case ISD::ADDC: 3260 case ISD::ADDE: { 3261 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3262 3263 // With ADDE and ADDCARRY, a carry bit may be added in. 3264 KnownBits Carry(1); 3265 if (Opcode == ISD::ADDE) 3266 // Can't track carry from glue, set carry to unknown. 3267 Carry.resetAll(); 3268 else if (Opcode == ISD::ADDCARRY) 3269 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3270 // the trouble (how often will we find a known carry bit). And I haven't 3271 // tested this very much yet, but something like this might work: 3272 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3273 // Carry = Carry.zextOrTrunc(1, false); 3274 Carry.resetAll(); 3275 else 3276 Carry.setAllZero(); 3277 3278 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3279 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3280 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3281 break; 3282 } 3283 case ISD::SREM: { 3284 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3285 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3286 Known = KnownBits::srem(Known, Known2); 3287 break; 3288 } 3289 case ISD::UREM: { 3290 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3291 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3292 Known = KnownBits::urem(Known, Known2); 3293 break; 3294 } 3295 case ISD::EXTRACT_ELEMENT: { 3296 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3297 const unsigned Index = Op.getConstantOperandVal(1); 3298 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3299 3300 // Remove low part of known bits mask 3301 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3302 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3303 3304 // Remove high part of known bit mask 3305 Known = Known.trunc(EltBitWidth); 3306 break; 3307 } 3308 case ISD::EXTRACT_VECTOR_ELT: { 3309 SDValue InVec = Op.getOperand(0); 3310 SDValue EltNo = Op.getOperand(1); 3311 EVT VecVT = InVec.getValueType(); 3312 // computeKnownBits not yet implemented for scalable vectors. 3313 if (VecVT.isScalableVector()) 3314 break; 3315 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3316 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3317 3318 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3319 // anything about the extended bits. 3320 if (BitWidth > EltBitWidth) 3321 Known = Known.trunc(EltBitWidth); 3322 3323 // If we know the element index, just demand that vector element, else for 3324 // an unknown element index, ignore DemandedElts and demand them all. 3325 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 3326 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3327 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3328 DemandedSrcElts = 3329 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3330 3331 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3332 if (BitWidth > EltBitWidth) 3333 Known = Known.anyext(BitWidth); 3334 break; 3335 } 3336 case ISD::INSERT_VECTOR_ELT: { 3337 // If we know the element index, split the demand between the 3338 // source vector and the inserted element, otherwise assume we need 3339 // the original demanded vector elements and the value. 3340 SDValue InVec = Op.getOperand(0); 3341 SDValue InVal = Op.getOperand(1); 3342 SDValue EltNo = Op.getOperand(2); 3343 bool DemandedVal = true; 3344 APInt DemandedVecElts = DemandedElts; 3345 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3346 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3347 unsigned EltIdx = CEltNo->getZExtValue(); 3348 DemandedVal = !!DemandedElts[EltIdx]; 3349 DemandedVecElts.clearBit(EltIdx); 3350 } 3351 Known.One.setAllBits(); 3352 Known.Zero.setAllBits(); 3353 if (DemandedVal) { 3354 Known2 = computeKnownBits(InVal, Depth + 1); 3355 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3356 } 3357 if (!!DemandedVecElts) { 3358 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3359 Known = KnownBits::commonBits(Known, Known2); 3360 } 3361 break; 3362 } 3363 case ISD::BITREVERSE: { 3364 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3365 Known = Known2.reverseBits(); 3366 break; 3367 } 3368 case ISD::BSWAP: { 3369 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3370 Known = Known2.byteSwap(); 3371 break; 3372 } 3373 case ISD::ABS: { 3374 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3375 Known = Known2.abs(); 3376 break; 3377 } 3378 case ISD::UMIN: { 3379 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3380 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3381 Known = KnownBits::umin(Known, Known2); 3382 break; 3383 } 3384 case ISD::UMAX: { 3385 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3386 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3387 Known = KnownBits::umax(Known, Known2); 3388 break; 3389 } 3390 case ISD::SMIN: 3391 case ISD::SMAX: { 3392 // If we have a clamp pattern, we know that the number of sign bits will be 3393 // the minimum of the clamp min/max range. 3394 bool IsMax = (Opcode == ISD::SMAX); 3395 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3396 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3397 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3398 CstHigh = 3399 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3400 if (CstLow && CstHigh) { 3401 if (!IsMax) 3402 std::swap(CstLow, CstHigh); 3403 3404 const APInt &ValueLow = CstLow->getAPIntValue(); 3405 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3406 if (ValueLow.sle(ValueHigh)) { 3407 unsigned LowSignBits = ValueLow.getNumSignBits(); 3408 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3409 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3410 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3411 Known.One.setHighBits(MinSignBits); 3412 break; 3413 } 3414 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3415 Known.Zero.setHighBits(MinSignBits); 3416 break; 3417 } 3418 } 3419 } 3420 3421 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3422 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3423 if (IsMax) 3424 Known = KnownBits::smax(Known, Known2); 3425 else 3426 Known = KnownBits::smin(Known, Known2); 3427 break; 3428 } 3429 case ISD::FrameIndex: 3430 case ISD::TargetFrameIndex: 3431 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3432 Known, getMachineFunction()); 3433 break; 3434 3435 default: 3436 if (Opcode < ISD::BUILTIN_OP_END) 3437 break; 3438 LLVM_FALLTHROUGH; 3439 case ISD::INTRINSIC_WO_CHAIN: 3440 case ISD::INTRINSIC_W_CHAIN: 3441 case ISD::INTRINSIC_VOID: 3442 // Allow the target to implement this method for its nodes. 3443 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3444 break; 3445 } 3446 3447 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3448 return Known; 3449 } 3450 3451 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3452 SDValue N1) const { 3453 // X + 0 never overflow 3454 if (isNullConstant(N1)) 3455 return OFK_Never; 3456 3457 KnownBits N1Known = computeKnownBits(N1); 3458 if (N1Known.Zero.getBoolValue()) { 3459 KnownBits N0Known = computeKnownBits(N0); 3460 3461 bool overflow; 3462 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3463 if (!overflow) 3464 return OFK_Never; 3465 } 3466 3467 // mulhi + 1 never overflow 3468 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3469 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3470 return OFK_Never; 3471 3472 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3473 KnownBits N0Known = computeKnownBits(N0); 3474 3475 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3476 return OFK_Never; 3477 } 3478 3479 return OFK_Sometime; 3480 } 3481 3482 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3483 EVT OpVT = Val.getValueType(); 3484 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3485 3486 // Is the constant a known power of 2? 3487 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3488 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3489 3490 // A left-shift of a constant one will have exactly one bit set because 3491 // shifting the bit off the end is undefined. 3492 if (Val.getOpcode() == ISD::SHL) { 3493 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3494 if (C && C->getAPIntValue() == 1) 3495 return true; 3496 } 3497 3498 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3499 // one bit set. 3500 if (Val.getOpcode() == ISD::SRL) { 3501 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3502 if (C && C->getAPIntValue().isSignMask()) 3503 return true; 3504 } 3505 3506 // Are all operands of a build vector constant powers of two? 3507 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3508 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3510 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3511 return false; 3512 })) 3513 return true; 3514 3515 // More could be done here, though the above checks are enough 3516 // to handle some common cases. 3517 3518 // Fall back to computeKnownBits to catch other known cases. 3519 KnownBits Known = computeKnownBits(Val); 3520 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3521 } 3522 3523 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3524 EVT VT = Op.getValueType(); 3525 3526 // TODO: Assume we don't know anything for now. 3527 if (VT.isScalableVector()) 3528 return 1; 3529 3530 APInt DemandedElts = VT.isVector() 3531 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 3532 : APInt(1, 1); 3533 return ComputeNumSignBits(Op, DemandedElts, Depth); 3534 } 3535 3536 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3537 unsigned Depth) const { 3538 EVT VT = Op.getValueType(); 3539 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3540 unsigned VTBits = VT.getScalarSizeInBits(); 3541 unsigned NumElts = DemandedElts.getBitWidth(); 3542 unsigned Tmp, Tmp2; 3543 unsigned FirstAnswer = 1; 3544 3545 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3546 const APInt &Val = C->getAPIntValue(); 3547 return Val.getNumSignBits(); 3548 } 3549 3550 if (Depth >= MaxRecursionDepth) 3551 return 1; // Limit search depth. 3552 3553 if (!DemandedElts || VT.isScalableVector()) 3554 return 1; // No demanded elts, better to assume we don't know anything. 3555 3556 unsigned Opcode = Op.getOpcode(); 3557 switch (Opcode) { 3558 default: break; 3559 case ISD::AssertSext: 3560 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3561 return VTBits-Tmp+1; 3562 case ISD::AssertZext: 3563 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3564 return VTBits-Tmp; 3565 3566 case ISD::BUILD_VECTOR: 3567 Tmp = VTBits; 3568 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3569 if (!DemandedElts[i]) 3570 continue; 3571 3572 SDValue SrcOp = Op.getOperand(i); 3573 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3574 3575 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3576 if (SrcOp.getValueSizeInBits() != VTBits) { 3577 assert(SrcOp.getValueSizeInBits() > VTBits && 3578 "Expected BUILD_VECTOR implicit truncation"); 3579 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3580 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3581 } 3582 Tmp = std::min(Tmp, Tmp2); 3583 } 3584 return Tmp; 3585 3586 case ISD::VECTOR_SHUFFLE: { 3587 // Collect the minimum number of sign bits that are shared by every vector 3588 // element referenced by the shuffle. 3589 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3590 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3591 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3592 for (unsigned i = 0; i != NumElts; ++i) { 3593 int M = SVN->getMaskElt(i); 3594 if (!DemandedElts[i]) 3595 continue; 3596 // For UNDEF elements, we don't know anything about the common state of 3597 // the shuffle result. 3598 if (M < 0) 3599 return 1; 3600 if ((unsigned)M < NumElts) 3601 DemandedLHS.setBit((unsigned)M % NumElts); 3602 else 3603 DemandedRHS.setBit((unsigned)M % NumElts); 3604 } 3605 Tmp = std::numeric_limits<unsigned>::max(); 3606 if (!!DemandedLHS) 3607 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3608 if (!!DemandedRHS) { 3609 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3610 Tmp = std::min(Tmp, Tmp2); 3611 } 3612 // If we don't know anything, early out and try computeKnownBits fall-back. 3613 if (Tmp == 1) 3614 break; 3615 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3616 return Tmp; 3617 } 3618 3619 case ISD::BITCAST: { 3620 SDValue N0 = Op.getOperand(0); 3621 EVT SrcVT = N0.getValueType(); 3622 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3623 3624 // Ignore bitcasts from unsupported types.. 3625 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3626 break; 3627 3628 // Fast handling of 'identity' bitcasts. 3629 if (VTBits == SrcBits) 3630 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3631 3632 bool IsLE = getDataLayout().isLittleEndian(); 3633 3634 // Bitcast 'large element' scalar/vector to 'small element' vector. 3635 if ((SrcBits % VTBits) == 0) { 3636 assert(VT.isVector() && "Expected bitcast to vector"); 3637 3638 unsigned Scale = SrcBits / VTBits; 3639 APInt SrcDemandedElts(NumElts / Scale, 0); 3640 for (unsigned i = 0; i != NumElts; ++i) 3641 if (DemandedElts[i]) 3642 SrcDemandedElts.setBit(i / Scale); 3643 3644 // Fast case - sign splat can be simply split across the small elements. 3645 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3646 if (Tmp == SrcBits) 3647 return VTBits; 3648 3649 // Slow case - determine how far the sign extends into each sub-element. 3650 Tmp2 = VTBits; 3651 for (unsigned i = 0; i != NumElts; ++i) 3652 if (DemandedElts[i]) { 3653 unsigned SubOffset = i % Scale; 3654 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3655 SubOffset = SubOffset * VTBits; 3656 if (Tmp <= SubOffset) 3657 return 1; 3658 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3659 } 3660 return Tmp2; 3661 } 3662 break; 3663 } 3664 3665 case ISD::SIGN_EXTEND: 3666 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3667 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3668 case ISD::SIGN_EXTEND_INREG: 3669 // Max of the input and what this extends. 3670 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3671 Tmp = VTBits-Tmp+1; 3672 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3673 return std::max(Tmp, Tmp2); 3674 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3675 SDValue Src = Op.getOperand(0); 3676 EVT SrcVT = Src.getValueType(); 3677 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3678 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3679 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3680 } 3681 case ISD::SRA: 3682 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3683 // SRA X, C -> adds C sign bits. 3684 if (const APInt *ShAmt = 3685 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3686 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3687 return Tmp; 3688 case ISD::SHL: 3689 if (const APInt *ShAmt = 3690 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3691 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3692 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3693 if (ShAmt->ult(Tmp)) 3694 return Tmp - ShAmt->getZExtValue(); 3695 } 3696 break; 3697 case ISD::AND: 3698 case ISD::OR: 3699 case ISD::XOR: // NOT is handled here. 3700 // Logical binary ops preserve the number of sign bits at the worst. 3701 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3702 if (Tmp != 1) { 3703 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3704 FirstAnswer = std::min(Tmp, Tmp2); 3705 // We computed what we know about the sign bits as our first 3706 // answer. Now proceed to the generic code that uses 3707 // computeKnownBits, and pick whichever answer is better. 3708 } 3709 break; 3710 3711 case ISD::SELECT: 3712 case ISD::VSELECT: 3713 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3714 if (Tmp == 1) return 1; // Early out. 3715 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3716 return std::min(Tmp, Tmp2); 3717 case ISD::SELECT_CC: 3718 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3719 if (Tmp == 1) return 1; // Early out. 3720 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3721 return std::min(Tmp, Tmp2); 3722 3723 case ISD::SMIN: 3724 case ISD::SMAX: { 3725 // If we have a clamp pattern, we know that the number of sign bits will be 3726 // the minimum of the clamp min/max range. 3727 bool IsMax = (Opcode == ISD::SMAX); 3728 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3729 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3730 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3731 CstHigh = 3732 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3733 if (CstLow && CstHigh) { 3734 if (!IsMax) 3735 std::swap(CstLow, CstHigh); 3736 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3737 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3738 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3739 return std::min(Tmp, Tmp2); 3740 } 3741 } 3742 3743 // Fallback - just get the minimum number of sign bits of the operands. 3744 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3745 if (Tmp == 1) 3746 return 1; // Early out. 3747 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3748 return std::min(Tmp, Tmp2); 3749 } 3750 case ISD::UMIN: 3751 case ISD::UMAX: 3752 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3753 if (Tmp == 1) 3754 return 1; // Early out. 3755 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3756 return std::min(Tmp, Tmp2); 3757 case ISD::SADDO: 3758 case ISD::UADDO: 3759 case ISD::SSUBO: 3760 case ISD::USUBO: 3761 case ISD::SMULO: 3762 case ISD::UMULO: 3763 if (Op.getResNo() != 1) 3764 break; 3765 // The boolean result conforms to getBooleanContents. Fall through. 3766 // If setcc returns 0/-1, all bits are sign bits. 3767 // We know that we have an integer-based boolean since these operations 3768 // are only available for integer. 3769 if (TLI->getBooleanContents(VT.isVector(), false) == 3770 TargetLowering::ZeroOrNegativeOneBooleanContent) 3771 return VTBits; 3772 break; 3773 case ISD::SETCC: 3774 case ISD::STRICT_FSETCC: 3775 case ISD::STRICT_FSETCCS: { 3776 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3777 // If setcc returns 0/-1, all bits are sign bits. 3778 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3779 TargetLowering::ZeroOrNegativeOneBooleanContent) 3780 return VTBits; 3781 break; 3782 } 3783 case ISD::ROTL: 3784 case ISD::ROTR: 3785 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3786 3787 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 3788 if (Tmp == VTBits) 3789 return VTBits; 3790 3791 if (ConstantSDNode *C = 3792 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 3793 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 3794 3795 // Handle rotate right by N like a rotate left by 32-N. 3796 if (Opcode == ISD::ROTR) 3797 RotAmt = (VTBits - RotAmt) % VTBits; 3798 3799 // If we aren't rotating out all of the known-in sign bits, return the 3800 // number that are left. This handles rotl(sext(x), 1) for example. 3801 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 3802 } 3803 break; 3804 case ISD::ADD: 3805 case ISD::ADDC: 3806 // Add can have at most one carry bit. Thus we know that the output 3807 // is, at worst, one more bit than the inputs. 3808 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3809 if (Tmp == 1) return 1; // Early out. 3810 3811 // Special case decrementing a value (ADD X, -1): 3812 if (ConstantSDNode *CRHS = 3813 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 3814 if (CRHS->isAllOnesValue()) { 3815 KnownBits Known = 3816 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3817 3818 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3819 // sign bits set. 3820 if ((Known.Zero | 1).isAllOnesValue()) 3821 return VTBits; 3822 3823 // If we are subtracting one from a positive number, there is no carry 3824 // out of the result. 3825 if (Known.isNonNegative()) 3826 return Tmp; 3827 } 3828 3829 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3830 if (Tmp2 == 1) return 1; // Early out. 3831 return std::min(Tmp, Tmp2) - 1; 3832 case ISD::SUB: 3833 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3834 if (Tmp2 == 1) return 1; // Early out. 3835 3836 // Handle NEG. 3837 if (ConstantSDNode *CLHS = 3838 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 3839 if (CLHS->isNullValue()) { 3840 KnownBits Known = 3841 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3842 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3843 // sign bits set. 3844 if ((Known.Zero | 1).isAllOnesValue()) 3845 return VTBits; 3846 3847 // If the input is known to be positive (the sign bit is known clear), 3848 // the output of the NEG has the same number of sign bits as the input. 3849 if (Known.isNonNegative()) 3850 return Tmp2; 3851 3852 // Otherwise, we treat this like a SUB. 3853 } 3854 3855 // Sub can have at most one carry bit. Thus we know that the output 3856 // is, at worst, one more bit than the inputs. 3857 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3858 if (Tmp == 1) return 1; // Early out. 3859 return std::min(Tmp, Tmp2) - 1; 3860 case ISD::MUL: { 3861 // The output of the Mul can be at most twice the valid bits in the inputs. 3862 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3863 if (SignBitsOp0 == 1) 3864 break; 3865 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 3866 if (SignBitsOp1 == 1) 3867 break; 3868 unsigned OutValidBits = 3869 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 3870 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 3871 } 3872 case ISD::SREM: 3873 // The sign bit is the LHS's sign bit, except when the result of the 3874 // remainder is zero. The magnitude of the result should be less than or 3875 // equal to the magnitude of the LHS. Therefore, the result should have 3876 // at least as many sign bits as the left hand side. 3877 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3878 case ISD::TRUNCATE: { 3879 // Check if the sign bits of source go down as far as the truncated value. 3880 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 3881 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3882 if (NumSrcSignBits > (NumSrcBits - VTBits)) 3883 return NumSrcSignBits - (NumSrcBits - VTBits); 3884 break; 3885 } 3886 case ISD::EXTRACT_ELEMENT: { 3887 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 3888 const int BitWidth = Op.getValueSizeInBits(); 3889 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 3890 3891 // Get reverse index (starting from 1), Op1 value indexes elements from 3892 // little end. Sign starts at big end. 3893 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 3894 3895 // If the sign portion ends in our element the subtraction gives correct 3896 // result. Otherwise it gives either negative or > bitwidth result 3897 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 3898 } 3899 case ISD::INSERT_VECTOR_ELT: { 3900 // If we know the element index, split the demand between the 3901 // source vector and the inserted element, otherwise assume we need 3902 // the original demanded vector elements and the value. 3903 SDValue InVec = Op.getOperand(0); 3904 SDValue InVal = Op.getOperand(1); 3905 SDValue EltNo = Op.getOperand(2); 3906 bool DemandedVal = true; 3907 APInt DemandedVecElts = DemandedElts; 3908 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3909 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3910 unsigned EltIdx = CEltNo->getZExtValue(); 3911 DemandedVal = !!DemandedElts[EltIdx]; 3912 DemandedVecElts.clearBit(EltIdx); 3913 } 3914 Tmp = std::numeric_limits<unsigned>::max(); 3915 if (DemandedVal) { 3916 // TODO - handle implicit truncation of inserted elements. 3917 if (InVal.getScalarValueSizeInBits() != VTBits) 3918 break; 3919 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 3920 Tmp = std::min(Tmp, Tmp2); 3921 } 3922 if (!!DemandedVecElts) { 3923 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 3924 Tmp = std::min(Tmp, Tmp2); 3925 } 3926 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3927 return Tmp; 3928 } 3929 case ISD::EXTRACT_VECTOR_ELT: { 3930 SDValue InVec = Op.getOperand(0); 3931 SDValue EltNo = Op.getOperand(1); 3932 EVT VecVT = InVec.getValueType(); 3933 // ComputeNumSignBits not yet implemented for scalable vectors. 3934 if (VecVT.isScalableVector()) 3935 break; 3936 const unsigned BitWidth = Op.getValueSizeInBits(); 3937 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 3938 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3939 3940 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 3941 // anything about sign bits. But if the sizes match we can derive knowledge 3942 // about sign bits from the vector operand. 3943 if (BitWidth != EltBitWidth) 3944 break; 3945 3946 // If we know the element index, just demand that vector element, else for 3947 // an unknown element index, ignore DemandedElts and demand them all. 3948 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 3949 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3950 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3951 DemandedSrcElts = 3952 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3953 3954 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 3955 } 3956 case ISD::EXTRACT_SUBVECTOR: { 3957 // Offset the demanded elts by the subvector index. 3958 SDValue Src = Op.getOperand(0); 3959 // Bail until we can represent demanded elements for scalable vectors. 3960 if (Src.getValueType().isScalableVector()) 3961 break; 3962 uint64_t Idx = Op.getConstantOperandVal(1); 3963 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3964 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 3965 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 3966 } 3967 case ISD::CONCAT_VECTORS: { 3968 // Determine the minimum number of sign bits across all demanded 3969 // elts of the input vectors. Early out if the result is already 1. 3970 Tmp = std::numeric_limits<unsigned>::max(); 3971 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3972 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3973 unsigned NumSubVectors = Op.getNumOperands(); 3974 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 3975 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); 3976 DemandedSub = DemandedSub.trunc(NumSubVectorElts); 3977 if (!DemandedSub) 3978 continue; 3979 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 3980 Tmp = std::min(Tmp, Tmp2); 3981 } 3982 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3983 return Tmp; 3984 } 3985 case ISD::INSERT_SUBVECTOR: { 3986 // Demand any elements from the subvector and the remainder from the src its 3987 // inserted into. 3988 SDValue Src = Op.getOperand(0); 3989 SDValue Sub = Op.getOperand(1); 3990 uint64_t Idx = Op.getConstantOperandVal(2); 3991 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3992 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3993 APInt DemandedSrcElts = DemandedElts; 3994 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 3995 3996 Tmp = std::numeric_limits<unsigned>::max(); 3997 if (!!DemandedSubElts) { 3998 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 3999 if (Tmp == 1) 4000 return 1; // early-out 4001 } 4002 if (!!DemandedSrcElts) { 4003 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4004 Tmp = std::min(Tmp, Tmp2); 4005 } 4006 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4007 return Tmp; 4008 } 4009 } 4010 4011 // If we are looking at the loaded value of the SDNode. 4012 if (Op.getResNo() == 0) { 4013 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4014 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4015 unsigned ExtType = LD->getExtensionType(); 4016 switch (ExtType) { 4017 default: break; 4018 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4019 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4020 return VTBits - Tmp + 1; 4021 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4022 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4023 return VTBits - Tmp; 4024 case ISD::NON_EXTLOAD: 4025 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4026 // We only need to handle vectors - computeKnownBits should handle 4027 // scalar cases. 4028 Type *CstTy = Cst->getType(); 4029 if (CstTy->isVectorTy() && 4030 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) { 4031 Tmp = VTBits; 4032 for (unsigned i = 0; i != NumElts; ++i) { 4033 if (!DemandedElts[i]) 4034 continue; 4035 if (Constant *Elt = Cst->getAggregateElement(i)) { 4036 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4037 const APInt &Value = CInt->getValue(); 4038 Tmp = std::min(Tmp, Value.getNumSignBits()); 4039 continue; 4040 } 4041 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4042 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4043 Tmp = std::min(Tmp, Value.getNumSignBits()); 4044 continue; 4045 } 4046 } 4047 // Unknown type. Conservatively assume no bits match sign bit. 4048 return 1; 4049 } 4050 return Tmp; 4051 } 4052 } 4053 break; 4054 } 4055 } 4056 } 4057 4058 // Allow the target to implement this method for its nodes. 4059 if (Opcode >= ISD::BUILTIN_OP_END || 4060 Opcode == ISD::INTRINSIC_WO_CHAIN || 4061 Opcode == ISD::INTRINSIC_W_CHAIN || 4062 Opcode == ISD::INTRINSIC_VOID) { 4063 unsigned NumBits = 4064 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4065 if (NumBits > 1) 4066 FirstAnswer = std::max(FirstAnswer, NumBits); 4067 } 4068 4069 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4070 // use this information. 4071 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4072 4073 APInt Mask; 4074 if (Known.isNonNegative()) { // sign bit is 0 4075 Mask = Known.Zero; 4076 } else if (Known.isNegative()) { // sign bit is 1; 4077 Mask = Known.One; 4078 } else { 4079 // Nothing known. 4080 return FirstAnswer; 4081 } 4082 4083 // Okay, we know that the sign bit in Mask is set. Use CLO to determine 4084 // the number of identical bits in the top of the input value. 4085 Mask <<= Mask.getBitWidth()-VTBits; 4086 return std::max(FirstAnswer, Mask.countLeadingOnes()); 4087 } 4088 4089 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4090 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4091 !isa<ConstantSDNode>(Op.getOperand(1))) 4092 return false; 4093 4094 if (Op.getOpcode() == ISD::OR && 4095 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4096 return false; 4097 4098 return true; 4099 } 4100 4101 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4102 // If we're told that NaNs won't happen, assume they won't. 4103 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4104 return true; 4105 4106 if (Depth >= MaxRecursionDepth) 4107 return false; // Limit search depth. 4108 4109 // TODO: Handle vectors. 4110 // If the value is a constant, we can obviously see if it is a NaN or not. 4111 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4112 return !C->getValueAPF().isNaN() || 4113 (SNaN && !C->getValueAPF().isSignaling()); 4114 } 4115 4116 unsigned Opcode = Op.getOpcode(); 4117 switch (Opcode) { 4118 case ISD::FADD: 4119 case ISD::FSUB: 4120 case ISD::FMUL: 4121 case ISD::FDIV: 4122 case ISD::FREM: 4123 case ISD::FSIN: 4124 case ISD::FCOS: { 4125 if (SNaN) 4126 return true; 4127 // TODO: Need isKnownNeverInfinity 4128 return false; 4129 } 4130 case ISD::FCANONICALIZE: 4131 case ISD::FEXP: 4132 case ISD::FEXP2: 4133 case ISD::FTRUNC: 4134 case ISD::FFLOOR: 4135 case ISD::FCEIL: 4136 case ISD::FROUND: 4137 case ISD::FROUNDEVEN: 4138 case ISD::FRINT: 4139 case ISD::FNEARBYINT: { 4140 if (SNaN) 4141 return true; 4142 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4143 } 4144 case ISD::FABS: 4145 case ISD::FNEG: 4146 case ISD::FCOPYSIGN: { 4147 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4148 } 4149 case ISD::SELECT: 4150 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4151 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4152 case ISD::FP_EXTEND: 4153 case ISD::FP_ROUND: { 4154 if (SNaN) 4155 return true; 4156 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4157 } 4158 case ISD::SINT_TO_FP: 4159 case ISD::UINT_TO_FP: 4160 return true; 4161 case ISD::FMA: 4162 case ISD::FMAD: { 4163 if (SNaN) 4164 return true; 4165 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4166 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4167 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4168 } 4169 case ISD::FSQRT: // Need is known positive 4170 case ISD::FLOG: 4171 case ISD::FLOG2: 4172 case ISD::FLOG10: 4173 case ISD::FPOWI: 4174 case ISD::FPOW: { 4175 if (SNaN) 4176 return true; 4177 // TODO: Refine on operand 4178 return false; 4179 } 4180 case ISD::FMINNUM: 4181 case ISD::FMAXNUM: { 4182 // Only one needs to be known not-nan, since it will be returned if the 4183 // other ends up being one. 4184 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4185 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4186 } 4187 case ISD::FMINNUM_IEEE: 4188 case ISD::FMAXNUM_IEEE: { 4189 if (SNaN) 4190 return true; 4191 // This can return a NaN if either operand is an sNaN, or if both operands 4192 // are NaN. 4193 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4194 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4195 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4196 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4197 } 4198 case ISD::FMINIMUM: 4199 case ISD::FMAXIMUM: { 4200 // TODO: Does this quiet or return the origina NaN as-is? 4201 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4202 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4203 } 4204 case ISD::EXTRACT_VECTOR_ELT: { 4205 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4206 } 4207 default: 4208 if (Opcode >= ISD::BUILTIN_OP_END || 4209 Opcode == ISD::INTRINSIC_WO_CHAIN || 4210 Opcode == ISD::INTRINSIC_W_CHAIN || 4211 Opcode == ISD::INTRINSIC_VOID) { 4212 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4213 } 4214 4215 return false; 4216 } 4217 } 4218 4219 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4220 assert(Op.getValueType().isFloatingPoint() && 4221 "Floating point type expected"); 4222 4223 // If the value is a constant, we can obviously see if it is a zero or not. 4224 // TODO: Add BuildVector support. 4225 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4226 return !C->isZero(); 4227 return false; 4228 } 4229 4230 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4231 assert(!Op.getValueType().isFloatingPoint() && 4232 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4233 4234 // If the value is a constant, we can obviously see if it is a zero or not. 4235 if (ISD::matchUnaryPredicate( 4236 Op, [](ConstantSDNode *C) { return !C->isNullValue(); })) 4237 return true; 4238 4239 // TODO: Recognize more cases here. 4240 switch (Op.getOpcode()) { 4241 default: break; 4242 case ISD::OR: 4243 if (isKnownNeverZero(Op.getOperand(1)) || 4244 isKnownNeverZero(Op.getOperand(0))) 4245 return true; 4246 break; 4247 } 4248 4249 return false; 4250 } 4251 4252 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4253 // Check the obvious case. 4254 if (A == B) return true; 4255 4256 // For for negative and positive zero. 4257 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4258 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4259 if (CA->isZero() && CB->isZero()) return true; 4260 4261 // Otherwise they may not be equal. 4262 return false; 4263 } 4264 4265 // FIXME: unify with llvm::haveNoCommonBitsSet. 4266 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M) 4267 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4268 assert(A.getValueType() == B.getValueType() && 4269 "Values must have the same type"); 4270 return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue(); 4271 } 4272 4273 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4274 ArrayRef<SDValue> Ops, 4275 SelectionDAG &DAG) { 4276 int NumOps = Ops.size(); 4277 assert(NumOps != 0 && "Can't build an empty vector!"); 4278 assert(!VT.isScalableVector() && 4279 "BUILD_VECTOR cannot be used with scalable types"); 4280 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4281 "Incorrect element count in BUILD_VECTOR!"); 4282 4283 // BUILD_VECTOR of UNDEFs is UNDEF. 4284 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4285 return DAG.getUNDEF(VT); 4286 4287 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4288 SDValue IdentitySrc; 4289 bool IsIdentity = true; 4290 for (int i = 0; i != NumOps; ++i) { 4291 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4292 Ops[i].getOperand(0).getValueType() != VT || 4293 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4294 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4295 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4296 IsIdentity = false; 4297 break; 4298 } 4299 IdentitySrc = Ops[i].getOperand(0); 4300 } 4301 if (IsIdentity) 4302 return IdentitySrc; 4303 4304 return SDValue(); 4305 } 4306 4307 /// Try to simplify vector concatenation to an input value, undef, or build 4308 /// vector. 4309 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4310 ArrayRef<SDValue> Ops, 4311 SelectionDAG &DAG) { 4312 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4313 assert(llvm::all_of(Ops, 4314 [Ops](SDValue Op) { 4315 return Ops[0].getValueType() == Op.getValueType(); 4316 }) && 4317 "Concatenation of vectors with inconsistent value types!"); 4318 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4319 VT.getVectorElementCount() && 4320 "Incorrect element count in vector concatenation!"); 4321 4322 if (Ops.size() == 1) 4323 return Ops[0]; 4324 4325 // Concat of UNDEFs is UNDEF. 4326 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4327 return DAG.getUNDEF(VT); 4328 4329 // Scan the operands and look for extract operations from a single source 4330 // that correspond to insertion at the same location via this concatenation: 4331 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4332 SDValue IdentitySrc; 4333 bool IsIdentity = true; 4334 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4335 SDValue Op = Ops[i]; 4336 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4337 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4338 Op.getOperand(0).getValueType() != VT || 4339 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4340 Op.getConstantOperandVal(1) != IdentityIndex) { 4341 IsIdentity = false; 4342 break; 4343 } 4344 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4345 "Unexpected identity source vector for concat of extracts"); 4346 IdentitySrc = Op.getOperand(0); 4347 } 4348 if (IsIdentity) { 4349 assert(IdentitySrc && "Failed to set source vector of extracts"); 4350 return IdentitySrc; 4351 } 4352 4353 // The code below this point is only designed to work for fixed width 4354 // vectors, so we bail out for now. 4355 if (VT.isScalableVector()) 4356 return SDValue(); 4357 4358 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4359 // simplified to one big BUILD_VECTOR. 4360 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4361 EVT SVT = VT.getScalarType(); 4362 SmallVector<SDValue, 16> Elts; 4363 for (SDValue Op : Ops) { 4364 EVT OpVT = Op.getValueType(); 4365 if (Op.isUndef()) 4366 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4367 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4368 Elts.append(Op->op_begin(), Op->op_end()); 4369 else 4370 return SDValue(); 4371 } 4372 4373 // BUILD_VECTOR requires all inputs to be of the same type, find the 4374 // maximum type and extend them all. 4375 for (SDValue Op : Elts) 4376 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4377 4378 if (SVT.bitsGT(VT.getScalarType())) { 4379 for (SDValue &Op : Elts) { 4380 if (Op.isUndef()) 4381 Op = DAG.getUNDEF(SVT); 4382 else 4383 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4384 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4385 : DAG.getSExtOrTrunc(Op, DL, SVT); 4386 } 4387 } 4388 4389 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4390 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4391 return V; 4392 } 4393 4394 /// Gets or creates the specified node. 4395 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4396 FoldingSetNodeID ID; 4397 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4398 void *IP = nullptr; 4399 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4400 return SDValue(E, 0); 4401 4402 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4403 getVTList(VT)); 4404 CSEMap.InsertNode(N, IP); 4405 4406 InsertNode(N); 4407 SDValue V = SDValue(N, 0); 4408 NewSDValueDbgMsg(V, "Creating new node: ", this); 4409 return V; 4410 } 4411 4412 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4413 SDValue Operand) { 4414 SDNodeFlags Flags; 4415 if (Inserter) 4416 Flags = Inserter->getFlags(); 4417 return getNode(Opcode, DL, VT, Operand, Flags); 4418 } 4419 4420 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4421 SDValue Operand, const SDNodeFlags Flags) { 4422 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4423 "Operand is DELETED_NODE!"); 4424 // Constant fold unary operations with an integer constant operand. Even 4425 // opaque constant will be folded, because the folding of unary operations 4426 // doesn't create new constants with different values. Nevertheless, the 4427 // opaque flag is preserved during folding to prevent future folding with 4428 // other constants. 4429 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4430 const APInt &Val = C->getAPIntValue(); 4431 switch (Opcode) { 4432 default: break; 4433 case ISD::SIGN_EXTEND: 4434 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4435 C->isTargetOpcode(), C->isOpaque()); 4436 case ISD::TRUNCATE: 4437 if (C->isOpaque()) 4438 break; 4439 LLVM_FALLTHROUGH; 4440 case ISD::ANY_EXTEND: 4441 case ISD::ZERO_EXTEND: 4442 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4443 C->isTargetOpcode(), C->isOpaque()); 4444 case ISD::UINT_TO_FP: 4445 case ISD::SINT_TO_FP: { 4446 APFloat apf(EVTToAPFloatSemantics(VT), 4447 APInt::getNullValue(VT.getSizeInBits())); 4448 (void)apf.convertFromAPInt(Val, 4449 Opcode==ISD::SINT_TO_FP, 4450 APFloat::rmNearestTiesToEven); 4451 return getConstantFP(apf, DL, VT); 4452 } 4453 case ISD::BITCAST: 4454 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4455 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4456 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4457 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4458 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4459 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4460 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4461 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4462 break; 4463 case ISD::ABS: 4464 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4465 C->isOpaque()); 4466 case ISD::BITREVERSE: 4467 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4468 C->isOpaque()); 4469 case ISD::BSWAP: 4470 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4471 C->isOpaque()); 4472 case ISD::CTPOP: 4473 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4474 C->isOpaque()); 4475 case ISD::CTLZ: 4476 case ISD::CTLZ_ZERO_UNDEF: 4477 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4478 C->isOpaque()); 4479 case ISD::CTTZ: 4480 case ISD::CTTZ_ZERO_UNDEF: 4481 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4482 C->isOpaque()); 4483 case ISD::FP16_TO_FP: { 4484 bool Ignored; 4485 APFloat FPV(APFloat::IEEEhalf(), 4486 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4487 4488 // This can return overflow, underflow, or inexact; we don't care. 4489 // FIXME need to be more flexible about rounding mode. 4490 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4491 APFloat::rmNearestTiesToEven, &Ignored); 4492 return getConstantFP(FPV, DL, VT); 4493 } 4494 } 4495 } 4496 4497 // Constant fold unary operations with a floating point constant operand. 4498 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4499 APFloat V = C->getValueAPF(); // make copy 4500 switch (Opcode) { 4501 case ISD::FNEG: 4502 V.changeSign(); 4503 return getConstantFP(V, DL, VT); 4504 case ISD::FABS: 4505 V.clearSign(); 4506 return getConstantFP(V, DL, VT); 4507 case ISD::FCEIL: { 4508 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4509 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4510 return getConstantFP(V, DL, VT); 4511 break; 4512 } 4513 case ISD::FTRUNC: { 4514 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4515 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4516 return getConstantFP(V, DL, VT); 4517 break; 4518 } 4519 case ISD::FFLOOR: { 4520 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4521 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4522 return getConstantFP(V, DL, VT); 4523 break; 4524 } 4525 case ISD::FP_EXTEND: { 4526 bool ignored; 4527 // This can return overflow, underflow, or inexact; we don't care. 4528 // FIXME need to be more flexible about rounding mode. 4529 (void)V.convert(EVTToAPFloatSemantics(VT), 4530 APFloat::rmNearestTiesToEven, &ignored); 4531 return getConstantFP(V, DL, VT); 4532 } 4533 case ISD::FP_TO_SINT: 4534 case ISD::FP_TO_UINT: { 4535 bool ignored; 4536 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4537 // FIXME need to be more flexible about rounding mode. 4538 APFloat::opStatus s = 4539 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4540 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4541 break; 4542 return getConstant(IntVal, DL, VT); 4543 } 4544 case ISD::BITCAST: 4545 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4546 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4547 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4548 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4549 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4550 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4551 break; 4552 case ISD::FP_TO_FP16: { 4553 bool Ignored; 4554 // This can return overflow, underflow, or inexact; we don't care. 4555 // FIXME need to be more flexible about rounding mode. 4556 (void)V.convert(APFloat::IEEEhalf(), 4557 APFloat::rmNearestTiesToEven, &Ignored); 4558 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4559 } 4560 } 4561 } 4562 4563 // Constant fold unary operations with a vector integer or float operand. 4564 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) { 4565 if (BV->isConstant()) { 4566 switch (Opcode) { 4567 default: 4568 // FIXME: Entirely reasonable to perform folding of other unary 4569 // operations here as the need arises. 4570 break; 4571 case ISD::FNEG: 4572 case ISD::FABS: 4573 case ISD::FCEIL: 4574 case ISD::FTRUNC: 4575 case ISD::FFLOOR: 4576 case ISD::FP_EXTEND: 4577 case ISD::FP_TO_SINT: 4578 case ISD::FP_TO_UINT: 4579 case ISD::TRUNCATE: 4580 case ISD::ANY_EXTEND: 4581 case ISD::ZERO_EXTEND: 4582 case ISD::SIGN_EXTEND: 4583 case ISD::UINT_TO_FP: 4584 case ISD::SINT_TO_FP: 4585 case ISD::ABS: 4586 case ISD::BITREVERSE: 4587 case ISD::BSWAP: 4588 case ISD::CTLZ: 4589 case ISD::CTLZ_ZERO_UNDEF: 4590 case ISD::CTTZ: 4591 case ISD::CTTZ_ZERO_UNDEF: 4592 case ISD::CTPOP: { 4593 SDValue Ops = { Operand }; 4594 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 4595 return Fold; 4596 } 4597 } 4598 } 4599 } 4600 4601 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4602 switch (Opcode) { 4603 case ISD::FREEZE: 4604 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4605 break; 4606 case ISD::TokenFactor: 4607 case ISD::MERGE_VALUES: 4608 case ISD::CONCAT_VECTORS: 4609 return Operand; // Factor, merge or concat of one node? No need. 4610 case ISD::BUILD_VECTOR: { 4611 // Attempt to simplify BUILD_VECTOR. 4612 SDValue Ops[] = {Operand}; 4613 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4614 return V; 4615 break; 4616 } 4617 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4618 case ISD::FP_EXTEND: 4619 assert(VT.isFloatingPoint() && 4620 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4621 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4622 assert((!VT.isVector() || 4623 VT.getVectorElementCount() == 4624 Operand.getValueType().getVectorElementCount()) && 4625 "Vector element count mismatch!"); 4626 assert(Operand.getValueType().bitsLT(VT) && 4627 "Invalid fpext node, dst < src!"); 4628 if (Operand.isUndef()) 4629 return getUNDEF(VT); 4630 break; 4631 case ISD::FP_TO_SINT: 4632 case ISD::FP_TO_UINT: 4633 if (Operand.isUndef()) 4634 return getUNDEF(VT); 4635 break; 4636 case ISD::SINT_TO_FP: 4637 case ISD::UINT_TO_FP: 4638 // [us]itofp(undef) = 0, because the result value is bounded. 4639 if (Operand.isUndef()) 4640 return getConstantFP(0.0, DL, VT); 4641 break; 4642 case ISD::SIGN_EXTEND: 4643 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4644 "Invalid SIGN_EXTEND!"); 4645 assert(VT.isVector() == Operand.getValueType().isVector() && 4646 "SIGN_EXTEND result type type should be vector iff the operand " 4647 "type is vector!"); 4648 if (Operand.getValueType() == VT) return Operand; // noop extension 4649 assert((!VT.isVector() || 4650 VT.getVectorElementCount() == 4651 Operand.getValueType().getVectorElementCount()) && 4652 "Vector element count mismatch!"); 4653 assert(Operand.getValueType().bitsLT(VT) && 4654 "Invalid sext node, dst < src!"); 4655 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 4656 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4657 else if (OpOpcode == ISD::UNDEF) 4658 // sext(undef) = 0, because the top bits will all be the same. 4659 return getConstant(0, DL, VT); 4660 break; 4661 case ISD::ZERO_EXTEND: 4662 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4663 "Invalid ZERO_EXTEND!"); 4664 assert(VT.isVector() == Operand.getValueType().isVector() && 4665 "ZERO_EXTEND result type type should be vector iff the operand " 4666 "type is vector!"); 4667 if (Operand.getValueType() == VT) return Operand; // noop extension 4668 assert((!VT.isVector() || 4669 VT.getVectorElementCount() == 4670 Operand.getValueType().getVectorElementCount()) && 4671 "Vector element count mismatch!"); 4672 assert(Operand.getValueType().bitsLT(VT) && 4673 "Invalid zext node, dst < src!"); 4674 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 4675 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 4676 else if (OpOpcode == ISD::UNDEF) 4677 // zext(undef) = 0, because the top bits will be zero. 4678 return getConstant(0, DL, VT); 4679 break; 4680 case ISD::ANY_EXTEND: 4681 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4682 "Invalid ANY_EXTEND!"); 4683 assert(VT.isVector() == Operand.getValueType().isVector() && 4684 "ANY_EXTEND result type type should be vector iff the operand " 4685 "type is vector!"); 4686 if (Operand.getValueType() == VT) return Operand; // noop extension 4687 assert((!VT.isVector() || 4688 VT.getVectorElementCount() == 4689 Operand.getValueType().getVectorElementCount()) && 4690 "Vector element count mismatch!"); 4691 assert(Operand.getValueType().bitsLT(VT) && 4692 "Invalid anyext node, dst < src!"); 4693 4694 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4695 OpOpcode == ISD::ANY_EXTEND) 4696 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 4697 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4698 else if (OpOpcode == ISD::UNDEF) 4699 return getUNDEF(VT); 4700 4701 // (ext (trunc x)) -> x 4702 if (OpOpcode == ISD::TRUNCATE) { 4703 SDValue OpOp = Operand.getOperand(0); 4704 if (OpOp.getValueType() == VT) { 4705 transferDbgValues(Operand, OpOp); 4706 return OpOp; 4707 } 4708 } 4709 break; 4710 case ISD::TRUNCATE: 4711 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4712 "Invalid TRUNCATE!"); 4713 assert(VT.isVector() == Operand.getValueType().isVector() && 4714 "TRUNCATE result type type should be vector iff the operand " 4715 "type is vector!"); 4716 if (Operand.getValueType() == VT) return Operand; // noop truncate 4717 assert((!VT.isVector() || 4718 VT.getVectorElementCount() == 4719 Operand.getValueType().getVectorElementCount()) && 4720 "Vector element count mismatch!"); 4721 assert(Operand.getValueType().bitsGT(VT) && 4722 "Invalid truncate node, src < dst!"); 4723 if (OpOpcode == ISD::TRUNCATE) 4724 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4725 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4726 OpOpcode == ISD::ANY_EXTEND) { 4727 // If the source is smaller than the dest, we still need an extend. 4728 if (Operand.getOperand(0).getValueType().getScalarType() 4729 .bitsLT(VT.getScalarType())) 4730 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4731 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 4732 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4733 return Operand.getOperand(0); 4734 } 4735 if (OpOpcode == ISD::UNDEF) 4736 return getUNDEF(VT); 4737 break; 4738 case ISD::ANY_EXTEND_VECTOR_INREG: 4739 case ISD::ZERO_EXTEND_VECTOR_INREG: 4740 case ISD::SIGN_EXTEND_VECTOR_INREG: 4741 assert(VT.isVector() && "This DAG node is restricted to vector types."); 4742 assert(Operand.getValueType().bitsLE(VT) && 4743 "The input must be the same size or smaller than the result."); 4744 assert(VT.getVectorNumElements() < 4745 Operand.getValueType().getVectorNumElements() && 4746 "The destination vector type must have fewer lanes than the input."); 4747 break; 4748 case ISD::ABS: 4749 assert(VT.isInteger() && VT == Operand.getValueType() && 4750 "Invalid ABS!"); 4751 if (OpOpcode == ISD::UNDEF) 4752 return getUNDEF(VT); 4753 break; 4754 case ISD::BSWAP: 4755 assert(VT.isInteger() && VT == Operand.getValueType() && 4756 "Invalid BSWAP!"); 4757 assert((VT.getScalarSizeInBits() % 16 == 0) && 4758 "BSWAP types must be a multiple of 16 bits!"); 4759 if (OpOpcode == ISD::UNDEF) 4760 return getUNDEF(VT); 4761 break; 4762 case ISD::BITREVERSE: 4763 assert(VT.isInteger() && VT == Operand.getValueType() && 4764 "Invalid BITREVERSE!"); 4765 if (OpOpcode == ISD::UNDEF) 4766 return getUNDEF(VT); 4767 break; 4768 case ISD::BITCAST: 4769 // Basic sanity checking. 4770 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 4771 "Cannot BITCAST between types of different sizes!"); 4772 if (VT == Operand.getValueType()) return Operand; // noop conversion. 4773 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 4774 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 4775 if (OpOpcode == ISD::UNDEF) 4776 return getUNDEF(VT); 4777 break; 4778 case ISD::SCALAR_TO_VECTOR: 4779 assert(VT.isVector() && !Operand.getValueType().isVector() && 4780 (VT.getVectorElementType() == Operand.getValueType() || 4781 (VT.getVectorElementType().isInteger() && 4782 Operand.getValueType().isInteger() && 4783 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 4784 "Illegal SCALAR_TO_VECTOR node!"); 4785 if (OpOpcode == ISD::UNDEF) 4786 return getUNDEF(VT); 4787 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 4788 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 4789 isa<ConstantSDNode>(Operand.getOperand(1)) && 4790 Operand.getConstantOperandVal(1) == 0 && 4791 Operand.getOperand(0).getValueType() == VT) 4792 return Operand.getOperand(0); 4793 break; 4794 case ISD::FNEG: 4795 // Negation of an unknown bag of bits is still completely undefined. 4796 if (OpOpcode == ISD::UNDEF) 4797 return getUNDEF(VT); 4798 4799 if (OpOpcode == ISD::FNEG) // --X -> X 4800 return Operand.getOperand(0); 4801 break; 4802 case ISD::FABS: 4803 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 4804 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 4805 break; 4806 case ISD::VSCALE: 4807 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4808 break; 4809 case ISD::CTPOP: 4810 if (Operand.getValueType().getScalarType() == MVT::i1) 4811 return Operand; 4812 break; 4813 case ISD::CTLZ: 4814 case ISD::CTTZ: 4815 if (Operand.getValueType().getScalarType() == MVT::i1) 4816 return getNOT(DL, Operand, Operand.getValueType()); 4817 break; 4818 case ISD::VECREDUCE_SMIN: 4819 case ISD::VECREDUCE_UMAX: 4820 if (Operand.getValueType().getScalarType() == MVT::i1) 4821 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 4822 break; 4823 case ISD::VECREDUCE_SMAX: 4824 case ISD::VECREDUCE_UMIN: 4825 if (Operand.getValueType().getScalarType() == MVT::i1) 4826 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 4827 break; 4828 } 4829 4830 SDNode *N; 4831 SDVTList VTs = getVTList(VT); 4832 SDValue Ops[] = {Operand}; 4833 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 4834 FoldingSetNodeID ID; 4835 AddNodeIDNode(ID, Opcode, VTs, Ops); 4836 void *IP = nullptr; 4837 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 4838 E->intersectFlagsWith(Flags); 4839 return SDValue(E, 0); 4840 } 4841 4842 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4843 N->setFlags(Flags); 4844 createOperands(N, Ops); 4845 CSEMap.InsertNode(N, IP); 4846 } else { 4847 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4848 createOperands(N, Ops); 4849 } 4850 4851 InsertNode(N); 4852 SDValue V = SDValue(N, 0); 4853 NewSDValueDbgMsg(V, "Creating new node: ", this); 4854 return V; 4855 } 4856 4857 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 4858 const APInt &C2) { 4859 switch (Opcode) { 4860 case ISD::ADD: return C1 + C2; 4861 case ISD::SUB: return C1 - C2; 4862 case ISD::MUL: return C1 * C2; 4863 case ISD::AND: return C1 & C2; 4864 case ISD::OR: return C1 | C2; 4865 case ISD::XOR: return C1 ^ C2; 4866 case ISD::SHL: return C1 << C2; 4867 case ISD::SRL: return C1.lshr(C2); 4868 case ISD::SRA: return C1.ashr(C2); 4869 case ISD::ROTL: return C1.rotl(C2); 4870 case ISD::ROTR: return C1.rotr(C2); 4871 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 4872 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 4873 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 4874 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 4875 case ISD::SADDSAT: return C1.sadd_sat(C2); 4876 case ISD::UADDSAT: return C1.uadd_sat(C2); 4877 case ISD::SSUBSAT: return C1.ssub_sat(C2); 4878 case ISD::USUBSAT: return C1.usub_sat(C2); 4879 case ISD::UDIV: 4880 if (!C2.getBoolValue()) 4881 break; 4882 return C1.udiv(C2); 4883 case ISD::UREM: 4884 if (!C2.getBoolValue()) 4885 break; 4886 return C1.urem(C2); 4887 case ISD::SDIV: 4888 if (!C2.getBoolValue()) 4889 break; 4890 return C1.sdiv(C2); 4891 case ISD::SREM: 4892 if (!C2.getBoolValue()) 4893 break; 4894 return C1.srem(C2); 4895 } 4896 return llvm::None; 4897 } 4898 4899 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 4900 const GlobalAddressSDNode *GA, 4901 const SDNode *N2) { 4902 if (GA->getOpcode() != ISD::GlobalAddress) 4903 return SDValue(); 4904 if (!TLI->isOffsetFoldingLegal(GA)) 4905 return SDValue(); 4906 auto *C2 = dyn_cast<ConstantSDNode>(N2); 4907 if (!C2) 4908 return SDValue(); 4909 int64_t Offset = C2->getSExtValue(); 4910 switch (Opcode) { 4911 case ISD::ADD: break; 4912 case ISD::SUB: Offset = -uint64_t(Offset); break; 4913 default: return SDValue(); 4914 } 4915 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 4916 GA->getOffset() + uint64_t(Offset)); 4917 } 4918 4919 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 4920 switch (Opcode) { 4921 case ISD::SDIV: 4922 case ISD::UDIV: 4923 case ISD::SREM: 4924 case ISD::UREM: { 4925 // If a divisor is zero/undef or any element of a divisor vector is 4926 // zero/undef, the whole op is undef. 4927 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 4928 SDValue Divisor = Ops[1]; 4929 if (Divisor.isUndef() || isNullConstant(Divisor)) 4930 return true; 4931 4932 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 4933 llvm::any_of(Divisor->op_values(), 4934 [](SDValue V) { return V.isUndef() || 4935 isNullConstant(V); }); 4936 // TODO: Handle signed overflow. 4937 } 4938 // TODO: Handle oversized shifts. 4939 default: 4940 return false; 4941 } 4942 } 4943 4944 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 4945 EVT VT, ArrayRef<SDValue> Ops) { 4946 // If the opcode is a target-specific ISD node, there's nothing we can 4947 // do here and the operand rules may not line up with the below, so 4948 // bail early. 4949 if (Opcode >= ISD::BUILTIN_OP_END) 4950 return SDValue(); 4951 4952 // For now, the array Ops should only contain two values. 4953 // This enforcement will be removed once this function is merged with 4954 // FoldConstantVectorArithmetic 4955 if (Ops.size() != 2) 4956 return SDValue(); 4957 4958 if (isUndef(Opcode, Ops)) 4959 return getUNDEF(VT); 4960 4961 SDNode *N1 = Ops[0].getNode(); 4962 SDNode *N2 = Ops[1].getNode(); 4963 4964 // Handle the case of two scalars. 4965 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) { 4966 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) { 4967 if (C1->isOpaque() || C2->isOpaque()) 4968 return SDValue(); 4969 4970 Optional<APInt> FoldAttempt = 4971 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 4972 if (!FoldAttempt) 4973 return SDValue(); 4974 4975 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 4976 assert((!Folded || !VT.isVector()) && 4977 "Can't fold vectors ops with scalar operands"); 4978 return Folded; 4979 } 4980 } 4981 4982 // fold (add Sym, c) -> Sym+c 4983 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1)) 4984 return FoldSymbolOffset(Opcode, VT, GA, N2); 4985 if (TLI->isCommutativeBinOp(Opcode)) 4986 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2)) 4987 return FoldSymbolOffset(Opcode, VT, GA, N1); 4988 4989 // TODO: All the folds below are performed lane-by-lane and assume a fixed 4990 // vector width, however we should be able to do constant folds involving 4991 // splat vector nodes too. 4992 if (VT.isScalableVector()) 4993 return SDValue(); 4994 4995 // For fixed width vectors, extract each constant element and fold them 4996 // individually. Either input may be an undef value. 4997 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 4998 if (!BV1 && !N1->isUndef()) 4999 return SDValue(); 5000 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5001 if (!BV2 && !N2->isUndef()) 5002 return SDValue(); 5003 // If both operands are undef, that's handled the same way as scalars. 5004 if (!BV1 && !BV2) 5005 return SDValue(); 5006 5007 assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) && 5008 "Vector binop with different number of elements in operands?"); 5009 5010 EVT SVT = VT.getScalarType(); 5011 EVT LegalSVT = SVT; 5012 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5013 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5014 if (LegalSVT.bitsLT(SVT)) 5015 return SDValue(); 5016 } 5017 SmallVector<SDValue, 4> Outputs; 5018 unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands(); 5019 for (unsigned I = 0; I != NumOps; ++I) { 5020 SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT); 5021 SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT); 5022 if (SVT.isInteger()) { 5023 if (V1->getValueType(0).bitsGT(SVT)) 5024 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1); 5025 if (V2->getValueType(0).bitsGT(SVT)) 5026 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2); 5027 } 5028 5029 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT) 5030 return SDValue(); 5031 5032 // Fold one vector element. 5033 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2); 5034 if (LegalSVT != SVT) 5035 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5036 5037 // Scalar folding only succeeded if the result is a constant or UNDEF. 5038 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5039 ScalarResult.getOpcode() != ISD::ConstantFP) 5040 return SDValue(); 5041 Outputs.push_back(ScalarResult); 5042 } 5043 5044 assert(VT.getVectorNumElements() == Outputs.size() && 5045 "Vector size mismatch!"); 5046 5047 // We may have a vector type but a scalar result. Create a splat. 5048 Outputs.resize(VT.getVectorNumElements(), Outputs.back()); 5049 5050 // Build a big vector out of the scalar elements we generated. 5051 return getBuildVector(VT, SDLoc(), Outputs); 5052 } 5053 5054 // TODO: Merge with FoldConstantArithmetic 5055 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 5056 const SDLoc &DL, EVT VT, 5057 ArrayRef<SDValue> Ops, 5058 const SDNodeFlags Flags) { 5059 // If the opcode is a target-specific ISD node, there's nothing we can 5060 // do here and the operand rules may not line up with the below, so 5061 // bail early. 5062 if (Opcode >= ISD::BUILTIN_OP_END) 5063 return SDValue(); 5064 5065 if (isUndef(Opcode, Ops)) 5066 return getUNDEF(VT); 5067 5068 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 5069 if (!VT.isVector()) 5070 return SDValue(); 5071 5072 // TODO: All the folds below are performed lane-by-lane and assume a fixed 5073 // vector width, however we should be able to do constant folds involving 5074 // splat vector nodes too. 5075 if (VT.isScalableVector()) 5076 return SDValue(); 5077 5078 // From this point onwards all vectors are assumed to be fixed width. 5079 unsigned NumElts = VT.getVectorNumElements(); 5080 5081 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) { 5082 return !Op.getValueType().isVector() || 5083 Op.getValueType().getVectorNumElements() == NumElts; 5084 }; 5085 5086 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) { 5087 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 5088 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) || 5089 (BV && BV->isConstant()); 5090 }; 5091 5092 // All operands must be vector types with the same number of elements as 5093 // the result type and must be either UNDEF or a build vector of constant 5094 // or UNDEF scalars. 5095 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) || 5096 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5097 return SDValue(); 5098 5099 // If we are comparing vectors, then the result needs to be a i1 boolean 5100 // that is then sign-extended back to the legal result type. 5101 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5102 5103 // Find legal integer scalar type for constant promotion and 5104 // ensure that its scalar size is at least as large as source. 5105 EVT LegalSVT = VT.getScalarType(); 5106 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5107 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5108 if (LegalSVT.bitsLT(VT.getScalarType())) 5109 return SDValue(); 5110 } 5111 5112 // Constant fold each scalar lane separately. 5113 SmallVector<SDValue, 4> ScalarResults; 5114 for (unsigned i = 0; i != NumElts; i++) { 5115 SmallVector<SDValue, 4> ScalarOps; 5116 for (SDValue Op : Ops) { 5117 EVT InSVT = Op.getValueType().getScalarType(); 5118 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op); 5119 if (!InBV) { 5120 // We've checked that this is UNDEF or a constant of some kind. 5121 if (Op.isUndef()) 5122 ScalarOps.push_back(getUNDEF(InSVT)); 5123 else 5124 ScalarOps.push_back(Op); 5125 continue; 5126 } 5127 5128 SDValue ScalarOp = InBV->getOperand(i); 5129 EVT ScalarVT = ScalarOp.getValueType(); 5130 5131 // Build vector (integer) scalar operands may need implicit 5132 // truncation - do this before constant folding. 5133 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5134 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5135 5136 ScalarOps.push_back(ScalarOp); 5137 } 5138 5139 // Constant fold the scalar operands. 5140 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 5141 5142 // Legalize the (integer) scalar constant if necessary. 5143 if (LegalSVT != SVT) 5144 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5145 5146 // Scalar folding only succeeded if the result is a constant or UNDEF. 5147 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5148 ScalarResult.getOpcode() != ISD::ConstantFP) 5149 return SDValue(); 5150 ScalarResults.push_back(ScalarResult); 5151 } 5152 5153 SDValue V = getBuildVector(VT, DL, ScalarResults); 5154 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5155 return V; 5156 } 5157 5158 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5159 EVT VT, SDValue N1, SDValue N2) { 5160 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5161 // should. That will require dealing with a potentially non-default 5162 // rounding mode, checking the "opStatus" return value from the APFloat 5163 // math calculations, and possibly other variations. 5164 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 5165 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 5166 if (N1CFP && N2CFP) { 5167 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF(); 5168 switch (Opcode) { 5169 case ISD::FADD: 5170 C1.add(C2, APFloat::rmNearestTiesToEven); 5171 return getConstantFP(C1, DL, VT); 5172 case ISD::FSUB: 5173 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5174 return getConstantFP(C1, DL, VT); 5175 case ISD::FMUL: 5176 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5177 return getConstantFP(C1, DL, VT); 5178 case ISD::FDIV: 5179 C1.divide(C2, APFloat::rmNearestTiesToEven); 5180 return getConstantFP(C1, DL, VT); 5181 case ISD::FREM: 5182 C1.mod(C2); 5183 return getConstantFP(C1, DL, VT); 5184 case ISD::FCOPYSIGN: 5185 C1.copySign(C2); 5186 return getConstantFP(C1, DL, VT); 5187 default: break; 5188 } 5189 } 5190 if (N1CFP && Opcode == ISD::FP_ROUND) { 5191 APFloat C1 = N1CFP->getValueAPF(); // make copy 5192 bool Unused; 5193 // This can return overflow, underflow, or inexact; we don't care. 5194 // FIXME need to be more flexible about rounding mode. 5195 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5196 &Unused); 5197 return getConstantFP(C1, DL, VT); 5198 } 5199 5200 switch (Opcode) { 5201 case ISD::FSUB: 5202 // -0.0 - undef --> undef (consistent with "fneg undef") 5203 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef()) 5204 return getUNDEF(VT); 5205 LLVM_FALLTHROUGH; 5206 5207 case ISD::FADD: 5208 case ISD::FMUL: 5209 case ISD::FDIV: 5210 case ISD::FREM: 5211 // If both operands are undef, the result is undef. If 1 operand is undef, 5212 // the result is NaN. This should match the behavior of the IR optimizer. 5213 if (N1.isUndef() && N2.isUndef()) 5214 return getUNDEF(VT); 5215 if (N1.isUndef() || N2.isUndef()) 5216 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5217 } 5218 return SDValue(); 5219 } 5220 5221 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5222 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5223 5224 // There's no need to assert on a byte-aligned pointer. All pointers are at 5225 // least byte aligned. 5226 if (A == Align(1)) 5227 return Val; 5228 5229 FoldingSetNodeID ID; 5230 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5231 ID.AddInteger(A.value()); 5232 5233 void *IP = nullptr; 5234 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5235 return SDValue(E, 0); 5236 5237 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5238 Val.getValueType(), A); 5239 createOperands(N, {Val}); 5240 5241 CSEMap.InsertNode(N, IP); 5242 InsertNode(N); 5243 5244 SDValue V(N, 0); 5245 NewSDValueDbgMsg(V, "Creating new node: ", this); 5246 return V; 5247 } 5248 5249 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5250 SDValue N1, SDValue N2) { 5251 SDNodeFlags Flags; 5252 if (Inserter) 5253 Flags = Inserter->getFlags(); 5254 return getNode(Opcode, DL, VT, N1, N2, Flags); 5255 } 5256 5257 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5258 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5259 assert(N1.getOpcode() != ISD::DELETED_NODE && 5260 N2.getOpcode() != ISD::DELETED_NODE && 5261 "Operand is DELETED_NODE!"); 5262 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5263 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5264 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5265 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5266 5267 // Canonicalize constant to RHS if commutative. 5268 if (TLI->isCommutativeBinOp(Opcode)) { 5269 if (N1C && !N2C) { 5270 std::swap(N1C, N2C); 5271 std::swap(N1, N2); 5272 } else if (N1CFP && !N2CFP) { 5273 std::swap(N1CFP, N2CFP); 5274 std::swap(N1, N2); 5275 } 5276 } 5277 5278 switch (Opcode) { 5279 default: break; 5280 case ISD::TokenFactor: 5281 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5282 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5283 // Fold trivial token factors. 5284 if (N1.getOpcode() == ISD::EntryToken) return N2; 5285 if (N2.getOpcode() == ISD::EntryToken) return N1; 5286 if (N1 == N2) return N1; 5287 break; 5288 case ISD::BUILD_VECTOR: { 5289 // Attempt to simplify BUILD_VECTOR. 5290 SDValue Ops[] = {N1, N2}; 5291 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5292 return V; 5293 break; 5294 } 5295 case ISD::CONCAT_VECTORS: { 5296 SDValue Ops[] = {N1, N2}; 5297 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5298 return V; 5299 break; 5300 } 5301 case ISD::AND: 5302 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5303 assert(N1.getValueType() == N2.getValueType() && 5304 N1.getValueType() == VT && "Binary operator types must match!"); 5305 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5306 // worth handling here. 5307 if (N2C && N2C->isNullValue()) 5308 return N2; 5309 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 5310 return N1; 5311 break; 5312 case ISD::OR: 5313 case ISD::XOR: 5314 case ISD::ADD: 5315 case ISD::SUB: 5316 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5317 assert(N1.getValueType() == N2.getValueType() && 5318 N1.getValueType() == VT && "Binary operator types must match!"); 5319 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5320 // it's worth handling here. 5321 if (N2C && N2C->isNullValue()) 5322 return N1; 5323 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5324 VT.getVectorElementType() == MVT::i1) 5325 return getNode(ISD::XOR, DL, VT, N1, N2); 5326 break; 5327 case ISD::MUL: 5328 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5329 assert(N1.getValueType() == N2.getValueType() && 5330 N1.getValueType() == VT && "Binary operator types must match!"); 5331 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5332 return getNode(ISD::AND, DL, VT, N1, N2); 5333 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5334 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5335 const APInt &N2CImm = N2C->getAPIntValue(); 5336 return getVScale(DL, VT, MulImm * N2CImm); 5337 } 5338 break; 5339 case ISD::UDIV: 5340 case ISD::UREM: 5341 case ISD::MULHU: 5342 case ISD::MULHS: 5343 case ISD::SDIV: 5344 case ISD::SREM: 5345 case ISD::SADDSAT: 5346 case ISD::SSUBSAT: 5347 case ISD::UADDSAT: 5348 case ISD::USUBSAT: 5349 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5350 assert(N1.getValueType() == N2.getValueType() && 5351 N1.getValueType() == VT && "Binary operator types must match!"); 5352 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5353 // fold (add_sat x, y) -> (or x, y) for bool types. 5354 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5355 return getNode(ISD::OR, DL, VT, N1, N2); 5356 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5357 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5358 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5359 } 5360 break; 5361 case ISD::SMIN: 5362 case ISD::UMAX: 5363 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5364 assert(N1.getValueType() == N2.getValueType() && 5365 N1.getValueType() == VT && "Binary operator types must match!"); 5366 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5367 return getNode(ISD::OR, DL, VT, N1, N2); 5368 break; 5369 case ISD::SMAX: 5370 case ISD::UMIN: 5371 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5372 assert(N1.getValueType() == N2.getValueType() && 5373 N1.getValueType() == VT && "Binary operator types must match!"); 5374 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5375 return getNode(ISD::AND, DL, VT, N1, N2); 5376 break; 5377 case ISD::FADD: 5378 case ISD::FSUB: 5379 case ISD::FMUL: 5380 case ISD::FDIV: 5381 case ISD::FREM: 5382 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5383 assert(N1.getValueType() == N2.getValueType() && 5384 N1.getValueType() == VT && "Binary operator types must match!"); 5385 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5386 return V; 5387 break; 5388 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5389 assert(N1.getValueType() == VT && 5390 N1.getValueType().isFloatingPoint() && 5391 N2.getValueType().isFloatingPoint() && 5392 "Invalid FCOPYSIGN!"); 5393 break; 5394 case ISD::SHL: 5395 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5396 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5397 const APInt &ShiftImm = N2C->getAPIntValue(); 5398 return getVScale(DL, VT, MulImm << ShiftImm); 5399 } 5400 LLVM_FALLTHROUGH; 5401 case ISD::SRA: 5402 case ISD::SRL: 5403 if (SDValue V = simplifyShift(N1, N2)) 5404 return V; 5405 LLVM_FALLTHROUGH; 5406 case ISD::ROTL: 5407 case ISD::ROTR: 5408 assert(VT == N1.getValueType() && 5409 "Shift operators return type must be the same as their first arg"); 5410 assert(VT.isInteger() && N2.getValueType().isInteger() && 5411 "Shifts only work on integers"); 5412 assert((!VT.isVector() || VT == N2.getValueType()) && 5413 "Vector shift amounts must be in the same as their first arg"); 5414 // Verify that the shift amount VT is big enough to hold valid shift 5415 // amounts. This catches things like trying to shift an i1024 value by an 5416 // i8, which is easy to fall into in generic code that uses 5417 // TLI.getShiftAmount(). 5418 assert(N2.getValueType().getScalarSizeInBits() >= 5419 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5420 "Invalid use of small shift amount with oversized value!"); 5421 5422 // Always fold shifts of i1 values so the code generator doesn't need to 5423 // handle them. Since we know the size of the shift has to be less than the 5424 // size of the value, the shift/rotate count is guaranteed to be zero. 5425 if (VT == MVT::i1) 5426 return N1; 5427 if (N2C && N2C->isNullValue()) 5428 return N1; 5429 break; 5430 case ISD::FP_ROUND: 5431 assert(VT.isFloatingPoint() && 5432 N1.getValueType().isFloatingPoint() && 5433 VT.bitsLE(N1.getValueType()) && 5434 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5435 "Invalid FP_ROUND!"); 5436 if (N1.getValueType() == VT) return N1; // noop conversion. 5437 break; 5438 case ISD::AssertSext: 5439 case ISD::AssertZext: { 5440 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5441 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5442 assert(VT.isInteger() && EVT.isInteger() && 5443 "Cannot *_EXTEND_INREG FP types"); 5444 assert(!EVT.isVector() && 5445 "AssertSExt/AssertZExt type should be the vector element type " 5446 "rather than the vector type!"); 5447 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5448 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5449 break; 5450 } 5451 case ISD::SIGN_EXTEND_INREG: { 5452 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5453 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5454 assert(VT.isInteger() && EVT.isInteger() && 5455 "Cannot *_EXTEND_INREG FP types"); 5456 assert(EVT.isVector() == VT.isVector() && 5457 "SIGN_EXTEND_INREG type should be vector iff the operand " 5458 "type is vector!"); 5459 assert((!EVT.isVector() || 5460 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5461 "Vector element counts must match in SIGN_EXTEND_INREG"); 5462 assert(EVT.bitsLE(VT) && "Not extending!"); 5463 if (EVT == VT) return N1; // Not actually extending 5464 5465 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5466 unsigned FromBits = EVT.getScalarSizeInBits(); 5467 Val <<= Val.getBitWidth() - FromBits; 5468 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5469 return getConstant(Val, DL, ConstantVT); 5470 }; 5471 5472 if (N1C) { 5473 const APInt &Val = N1C->getAPIntValue(); 5474 return SignExtendInReg(Val, VT); 5475 } 5476 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5477 SmallVector<SDValue, 8> Ops; 5478 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5479 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5480 SDValue Op = N1.getOperand(i); 5481 if (Op.isUndef()) { 5482 Ops.push_back(getUNDEF(OpVT)); 5483 continue; 5484 } 5485 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5486 APInt Val = C->getAPIntValue(); 5487 Ops.push_back(SignExtendInReg(Val, OpVT)); 5488 } 5489 return getBuildVector(VT, DL, Ops); 5490 } 5491 break; 5492 } 5493 case ISD::EXTRACT_VECTOR_ELT: 5494 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5495 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5496 element type of the vector."); 5497 5498 // Extract from an undefined value or using an undefined index is undefined. 5499 if (N1.isUndef() || N2.isUndef()) 5500 return getUNDEF(VT); 5501 5502 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5503 // vectors. For scalable vectors we will provide appropriate support for 5504 // dealing with arbitrary indices. 5505 if (N2C && N1.getValueType().isFixedLengthVector() && 5506 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5507 return getUNDEF(VT); 5508 5509 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5510 // expanding copies of large vectors from registers. This only works for 5511 // fixed length vectors, since we need to know the exact number of 5512 // elements. 5513 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5514 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5515 unsigned Factor = 5516 N1.getOperand(0).getValueType().getVectorNumElements(); 5517 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5518 N1.getOperand(N2C->getZExtValue() / Factor), 5519 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5520 } 5521 5522 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5523 // lowering is expanding large vector constants. 5524 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5525 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5526 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5527 N1.getValueType().isFixedLengthVector()) && 5528 "BUILD_VECTOR used for scalable vectors"); 5529 unsigned Index = 5530 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5531 SDValue Elt = N1.getOperand(Index); 5532 5533 if (VT != Elt.getValueType()) 5534 // If the vector element type is not legal, the BUILD_VECTOR operands 5535 // are promoted and implicitly truncated, and the result implicitly 5536 // extended. Make that explicit here. 5537 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5538 5539 return Elt; 5540 } 5541 5542 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5543 // operations are lowered to scalars. 5544 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5545 // If the indices are the same, return the inserted element else 5546 // if the indices are known different, extract the element from 5547 // the original vector. 5548 SDValue N1Op2 = N1.getOperand(2); 5549 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5550 5551 if (N1Op2C && N2C) { 5552 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5553 if (VT == N1.getOperand(1).getValueType()) 5554 return N1.getOperand(1); 5555 else 5556 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5557 } 5558 5559 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5560 } 5561 } 5562 5563 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5564 // when vector types are scalarized and v1iX is legal. 5565 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5566 // Here we are completely ignoring the extract element index (N2), 5567 // which is fine for fixed width vectors, since any index other than 0 5568 // is undefined anyway. However, this cannot be ignored for scalable 5569 // vectors - in theory we could support this, but we don't want to do this 5570 // without a profitability check. 5571 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5572 N1.getValueType().isFixedLengthVector() && 5573 N1.getValueType().getVectorNumElements() == 1) { 5574 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5575 N1.getOperand(1)); 5576 } 5577 break; 5578 case ISD::EXTRACT_ELEMENT: 5579 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5580 assert(!N1.getValueType().isVector() && !VT.isVector() && 5581 (N1.getValueType().isInteger() == VT.isInteger()) && 5582 N1.getValueType() != VT && 5583 "Wrong types for EXTRACT_ELEMENT!"); 5584 5585 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5586 // 64-bit integers into 32-bit parts. Instead of building the extract of 5587 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5588 if (N1.getOpcode() == ISD::BUILD_PAIR) 5589 return N1.getOperand(N2C->getZExtValue()); 5590 5591 // EXTRACT_ELEMENT of a constant int is also very common. 5592 if (N1C) { 5593 unsigned ElementSize = VT.getSizeInBits(); 5594 unsigned Shift = ElementSize * N2C->getZExtValue(); 5595 const APInt &Val = N1C->getAPIntValue(); 5596 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 5597 } 5598 break; 5599 case ISD::EXTRACT_SUBVECTOR: 5600 EVT N1VT = N1.getValueType(); 5601 assert(VT.isVector() && N1VT.isVector() && 5602 "Extract subvector VTs must be vectors!"); 5603 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5604 "Extract subvector VTs must have the same element type!"); 5605 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5606 "Cannot extract a scalable vector from a fixed length vector!"); 5607 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5608 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5609 "Extract subvector must be from larger vector to smaller vector!"); 5610 assert(N2C && "Extract subvector index must be a constant"); 5611 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5612 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5613 N1VT.getVectorMinNumElements()) && 5614 "Extract subvector overflow!"); 5615 assert(N2C->getAPIntValue().getBitWidth() == 5616 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5617 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 5618 5619 // Trivial extraction. 5620 if (VT == N1VT) 5621 return N1; 5622 5623 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 5624 if (N1.isUndef()) 5625 return getUNDEF(VT); 5626 5627 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 5628 // the concat have the same type as the extract. 5629 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 5630 VT == N1.getOperand(0).getValueType()) { 5631 unsigned Factor = VT.getVectorMinNumElements(); 5632 return N1.getOperand(N2C->getZExtValue() / Factor); 5633 } 5634 5635 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 5636 // during shuffle legalization. 5637 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 5638 VT == N1.getOperand(1).getValueType()) 5639 return N1.getOperand(1); 5640 break; 5641 } 5642 5643 // Perform trivial constant folding. 5644 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 5645 return SV; 5646 5647 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2)) 5648 return V; 5649 5650 // Canonicalize an UNDEF to the RHS, even over a constant. 5651 if (N1.isUndef()) { 5652 if (TLI->isCommutativeBinOp(Opcode)) { 5653 std::swap(N1, N2); 5654 } else { 5655 switch (Opcode) { 5656 case ISD::SIGN_EXTEND_INREG: 5657 case ISD::SUB: 5658 return getUNDEF(VT); // fold op(undef, arg2) -> undef 5659 case ISD::UDIV: 5660 case ISD::SDIV: 5661 case ISD::UREM: 5662 case ISD::SREM: 5663 case ISD::SSUBSAT: 5664 case ISD::USUBSAT: 5665 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 5666 } 5667 } 5668 } 5669 5670 // Fold a bunch of operators when the RHS is undef. 5671 if (N2.isUndef()) { 5672 switch (Opcode) { 5673 case ISD::XOR: 5674 if (N1.isUndef()) 5675 // Handle undef ^ undef -> 0 special case. This is a common 5676 // idiom (misuse). 5677 return getConstant(0, DL, VT); 5678 LLVM_FALLTHROUGH; 5679 case ISD::ADD: 5680 case ISD::SUB: 5681 case ISD::UDIV: 5682 case ISD::SDIV: 5683 case ISD::UREM: 5684 case ISD::SREM: 5685 return getUNDEF(VT); // fold op(arg1, undef) -> undef 5686 case ISD::MUL: 5687 case ISD::AND: 5688 case ISD::SSUBSAT: 5689 case ISD::USUBSAT: 5690 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 5691 case ISD::OR: 5692 case ISD::SADDSAT: 5693 case ISD::UADDSAT: 5694 return getAllOnesConstant(DL, VT); 5695 } 5696 } 5697 5698 // Memoize this node if possible. 5699 SDNode *N; 5700 SDVTList VTs = getVTList(VT); 5701 SDValue Ops[] = {N1, N2}; 5702 if (VT != MVT::Glue) { 5703 FoldingSetNodeID ID; 5704 AddNodeIDNode(ID, Opcode, VTs, Ops); 5705 void *IP = nullptr; 5706 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5707 E->intersectFlagsWith(Flags); 5708 return SDValue(E, 0); 5709 } 5710 5711 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5712 N->setFlags(Flags); 5713 createOperands(N, Ops); 5714 CSEMap.InsertNode(N, IP); 5715 } else { 5716 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5717 createOperands(N, Ops); 5718 } 5719 5720 InsertNode(N); 5721 SDValue V = SDValue(N, 0); 5722 NewSDValueDbgMsg(V, "Creating new node: ", this); 5723 return V; 5724 } 5725 5726 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5727 SDValue N1, SDValue N2, SDValue N3) { 5728 SDNodeFlags Flags; 5729 if (Inserter) 5730 Flags = Inserter->getFlags(); 5731 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 5732 } 5733 5734 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5735 SDValue N1, SDValue N2, SDValue N3, 5736 const SDNodeFlags Flags) { 5737 assert(N1.getOpcode() != ISD::DELETED_NODE && 5738 N2.getOpcode() != ISD::DELETED_NODE && 5739 N3.getOpcode() != ISD::DELETED_NODE && 5740 "Operand is DELETED_NODE!"); 5741 // Perform various simplifications. 5742 switch (Opcode) { 5743 case ISD::FMA: { 5744 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5745 assert(N1.getValueType() == VT && N2.getValueType() == VT && 5746 N3.getValueType() == VT && "FMA types must match!"); 5747 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5748 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5749 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 5750 if (N1CFP && N2CFP && N3CFP) { 5751 APFloat V1 = N1CFP->getValueAPF(); 5752 const APFloat &V2 = N2CFP->getValueAPF(); 5753 const APFloat &V3 = N3CFP->getValueAPF(); 5754 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 5755 return getConstantFP(V1, DL, VT); 5756 } 5757 break; 5758 } 5759 case ISD::BUILD_VECTOR: { 5760 // Attempt to simplify BUILD_VECTOR. 5761 SDValue Ops[] = {N1, N2, N3}; 5762 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5763 return V; 5764 break; 5765 } 5766 case ISD::CONCAT_VECTORS: { 5767 SDValue Ops[] = {N1, N2, N3}; 5768 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5769 return V; 5770 break; 5771 } 5772 case ISD::SETCC: { 5773 assert(VT.isInteger() && "SETCC result type must be an integer!"); 5774 assert(N1.getValueType() == N2.getValueType() && 5775 "SETCC operands must have the same type!"); 5776 assert(VT.isVector() == N1.getValueType().isVector() && 5777 "SETCC type should be vector iff the operand type is vector!"); 5778 assert((!VT.isVector() || VT.getVectorElementCount() == 5779 N1.getValueType().getVectorElementCount()) && 5780 "SETCC vector element counts must match!"); 5781 // Use FoldSetCC to simplify SETCC's. 5782 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 5783 return V; 5784 // Vector constant folding. 5785 SDValue Ops[] = {N1, N2, N3}; 5786 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) { 5787 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 5788 return V; 5789 } 5790 break; 5791 } 5792 case ISD::SELECT: 5793 case ISD::VSELECT: 5794 if (SDValue V = simplifySelect(N1, N2, N3)) 5795 return V; 5796 break; 5797 case ISD::VECTOR_SHUFFLE: 5798 llvm_unreachable("should use getVectorShuffle constructor!"); 5799 case ISD::INSERT_VECTOR_ELT: { 5800 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 5801 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 5802 // for scalable vectors where we will generate appropriate code to 5803 // deal with out-of-bounds cases correctly. 5804 if (N3C && N1.getValueType().isFixedLengthVector() && 5805 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 5806 return getUNDEF(VT); 5807 5808 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 5809 if (N3.isUndef()) 5810 return getUNDEF(VT); 5811 5812 // If the inserted element is an UNDEF, just use the input vector. 5813 if (N2.isUndef()) 5814 return N1; 5815 5816 break; 5817 } 5818 case ISD::INSERT_SUBVECTOR: { 5819 // Inserting undef into undef is still undef. 5820 if (N1.isUndef() && N2.isUndef()) 5821 return getUNDEF(VT); 5822 5823 EVT N2VT = N2.getValueType(); 5824 assert(VT == N1.getValueType() && 5825 "Dest and insert subvector source types must match!"); 5826 assert(VT.isVector() && N2VT.isVector() && 5827 "Insert subvector VTs must be vectors!"); 5828 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 5829 "Cannot insert a scalable vector into a fixed length vector!"); 5830 assert((VT.isScalableVector() != N2VT.isScalableVector() || 5831 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 5832 "Insert subvector must be from smaller vector to larger vector!"); 5833 assert(isa<ConstantSDNode>(N3) && 5834 "Insert subvector index must be constant"); 5835 assert((VT.isScalableVector() != N2VT.isScalableVector() || 5836 (N2VT.getVectorMinNumElements() + 5837 cast<ConstantSDNode>(N3)->getZExtValue()) <= 5838 VT.getVectorMinNumElements()) && 5839 "Insert subvector overflow!"); 5840 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 5841 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5842 "Constant index for INSERT_SUBVECTOR has an invalid size"); 5843 5844 // Trivial insertion. 5845 if (VT == N2VT) 5846 return N2; 5847 5848 // If this is an insert of an extracted vector into an undef vector, we 5849 // can just use the input to the extract. 5850 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5851 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 5852 return N2.getOperand(0); 5853 break; 5854 } 5855 case ISD::BITCAST: 5856 // Fold bit_convert nodes from a type to themselves. 5857 if (N1.getValueType() == VT) 5858 return N1; 5859 break; 5860 } 5861 5862 // Memoize node if it doesn't produce a flag. 5863 SDNode *N; 5864 SDVTList VTs = getVTList(VT); 5865 SDValue Ops[] = {N1, N2, N3}; 5866 if (VT != MVT::Glue) { 5867 FoldingSetNodeID ID; 5868 AddNodeIDNode(ID, Opcode, VTs, Ops); 5869 void *IP = nullptr; 5870 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5871 E->intersectFlagsWith(Flags); 5872 return SDValue(E, 0); 5873 } 5874 5875 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5876 N->setFlags(Flags); 5877 createOperands(N, Ops); 5878 CSEMap.InsertNode(N, IP); 5879 } else { 5880 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5881 createOperands(N, Ops); 5882 } 5883 5884 InsertNode(N); 5885 SDValue V = SDValue(N, 0); 5886 NewSDValueDbgMsg(V, "Creating new node: ", this); 5887 return V; 5888 } 5889 5890 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5891 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 5892 SDValue Ops[] = { N1, N2, N3, N4 }; 5893 return getNode(Opcode, DL, VT, Ops); 5894 } 5895 5896 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5897 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 5898 SDValue N5) { 5899 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 5900 return getNode(Opcode, DL, VT, Ops); 5901 } 5902 5903 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 5904 /// the incoming stack arguments to be loaded from the stack. 5905 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 5906 SmallVector<SDValue, 8> ArgChains; 5907 5908 // Include the original chain at the beginning of the list. When this is 5909 // used by target LowerCall hooks, this helps legalize find the 5910 // CALLSEQ_BEGIN node. 5911 ArgChains.push_back(Chain); 5912 5913 // Add a chain value for each stack argument. 5914 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 5915 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 5916 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 5917 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 5918 if (FI->getIndex() < 0) 5919 ArgChains.push_back(SDValue(L, 1)); 5920 5921 // Build a tokenfactor for all the chains. 5922 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 5923 } 5924 5925 /// getMemsetValue - Vectorized representation of the memset value 5926 /// operand. 5927 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 5928 const SDLoc &dl) { 5929 assert(!Value.isUndef()); 5930 5931 unsigned NumBits = VT.getScalarSizeInBits(); 5932 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 5933 assert(C->getAPIntValue().getBitWidth() == 8); 5934 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 5935 if (VT.isInteger()) { 5936 bool IsOpaque = VT.getSizeInBits() > 64 || 5937 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 5938 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 5939 } 5940 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 5941 VT); 5942 } 5943 5944 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 5945 EVT IntVT = VT.getScalarType(); 5946 if (!IntVT.isInteger()) 5947 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 5948 5949 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 5950 if (NumBits > 8) { 5951 // Use a multiplication with 0x010101... to extend the input to the 5952 // required length. 5953 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 5954 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 5955 DAG.getConstant(Magic, dl, IntVT)); 5956 } 5957 5958 if (VT != Value.getValueType() && !VT.isInteger()) 5959 Value = DAG.getBitcast(VT.getScalarType(), Value); 5960 if (VT != Value.getValueType()) 5961 Value = DAG.getSplatBuildVector(VT, dl, Value); 5962 5963 return Value; 5964 } 5965 5966 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 5967 /// used when a memcpy is turned into a memset when the source is a constant 5968 /// string ptr. 5969 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 5970 const TargetLowering &TLI, 5971 const ConstantDataArraySlice &Slice) { 5972 // Handle vector with all elements zero. 5973 if (Slice.Array == nullptr) { 5974 if (VT.isInteger()) 5975 return DAG.getConstant(0, dl, VT); 5976 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 5977 return DAG.getConstantFP(0.0, dl, VT); 5978 else if (VT.isVector()) { 5979 unsigned NumElts = VT.getVectorNumElements(); 5980 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 5981 return DAG.getNode(ISD::BITCAST, dl, VT, 5982 DAG.getConstant(0, dl, 5983 EVT::getVectorVT(*DAG.getContext(), 5984 EltVT, NumElts))); 5985 } else 5986 llvm_unreachable("Expected type!"); 5987 } 5988 5989 assert(!VT.isVector() && "Can't handle vector type here!"); 5990 unsigned NumVTBits = VT.getSizeInBits(); 5991 unsigned NumVTBytes = NumVTBits / 8; 5992 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 5993 5994 APInt Val(NumVTBits, 0); 5995 if (DAG.getDataLayout().isLittleEndian()) { 5996 for (unsigned i = 0; i != NumBytes; ++i) 5997 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 5998 } else { 5999 for (unsigned i = 0; i != NumBytes; ++i) 6000 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6001 } 6002 6003 // If the "cost" of materializing the integer immediate is less than the cost 6004 // of a load, then it is cost effective to turn the load into the immediate. 6005 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6006 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6007 return DAG.getConstant(Val, dl, VT); 6008 return SDValue(nullptr, 0); 6009 } 6010 6011 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6012 const SDLoc &DL, 6013 const SDNodeFlags Flags) { 6014 EVT VT = Base.getValueType(); 6015 SDValue Index; 6016 6017 if (Offset.isScalable()) 6018 Index = getVScale(DL, Base.getValueType(), 6019 APInt(Base.getValueSizeInBits().getFixedSize(), 6020 Offset.getKnownMinSize())); 6021 else 6022 Index = getConstant(Offset.getFixedSize(), DL, VT); 6023 6024 return getMemBasePlusOffset(Base, Index, DL, Flags); 6025 } 6026 6027 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6028 const SDLoc &DL, 6029 const SDNodeFlags Flags) { 6030 assert(Offset.getValueType().isInteger()); 6031 EVT BasePtrVT = Ptr.getValueType(); 6032 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6033 } 6034 6035 /// Returns true if memcpy source is constant data. 6036 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6037 uint64_t SrcDelta = 0; 6038 GlobalAddressSDNode *G = nullptr; 6039 if (Src.getOpcode() == ISD::GlobalAddress) 6040 G = cast<GlobalAddressSDNode>(Src); 6041 else if (Src.getOpcode() == ISD::ADD && 6042 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6043 Src.getOperand(1).getOpcode() == ISD::Constant) { 6044 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6045 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6046 } 6047 if (!G) 6048 return false; 6049 6050 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6051 SrcDelta + G->getOffset()); 6052 } 6053 6054 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6055 SelectionDAG &DAG) { 6056 // On Darwin, -Os means optimize for size without hurting performance, so 6057 // only really optimize for size when -Oz (MinSize) is used. 6058 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6059 return MF.getFunction().hasMinSize(); 6060 return DAG.shouldOptForSize(); 6061 } 6062 6063 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6064 SmallVector<SDValue, 32> &OutChains, unsigned From, 6065 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6066 SmallVector<SDValue, 16> &OutStoreChains) { 6067 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6068 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6069 SmallVector<SDValue, 16> GluedLoadChains; 6070 for (unsigned i = From; i < To; ++i) { 6071 OutChains.push_back(OutLoadChains[i]); 6072 GluedLoadChains.push_back(OutLoadChains[i]); 6073 } 6074 6075 // Chain for all loads. 6076 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6077 GluedLoadChains); 6078 6079 for (unsigned i = From; i < To; ++i) { 6080 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6081 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6082 ST->getBasePtr(), ST->getMemoryVT(), 6083 ST->getMemOperand()); 6084 OutChains.push_back(NewStore); 6085 } 6086 } 6087 6088 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6089 SDValue Chain, SDValue Dst, SDValue Src, 6090 uint64_t Size, Align Alignment, 6091 bool isVol, bool AlwaysInline, 6092 MachinePointerInfo DstPtrInfo, 6093 MachinePointerInfo SrcPtrInfo) { 6094 // Turn a memcpy of undef to nop. 6095 // FIXME: We need to honor volatile even is Src is undef. 6096 if (Src.isUndef()) 6097 return Chain; 6098 6099 // Expand memcpy to a series of load and store ops if the size operand falls 6100 // below a certain threshold. 6101 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6102 // rather than maybe a humongous number of loads and stores. 6103 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6104 const DataLayout &DL = DAG.getDataLayout(); 6105 LLVMContext &C = *DAG.getContext(); 6106 std::vector<EVT> MemOps; 6107 bool DstAlignCanChange = false; 6108 MachineFunction &MF = DAG.getMachineFunction(); 6109 MachineFrameInfo &MFI = MF.getFrameInfo(); 6110 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6111 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6112 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6113 DstAlignCanChange = true; 6114 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6115 if (!SrcAlign || Alignment > *SrcAlign) 6116 SrcAlign = Alignment; 6117 assert(SrcAlign && "SrcAlign must be set"); 6118 ConstantDataArraySlice Slice; 6119 // If marked as volatile, perform a copy even when marked as constant. 6120 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6121 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6122 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6123 const MemOp Op = isZeroConstant 6124 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6125 /*IsZeroMemset*/ true, isVol) 6126 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6127 *SrcAlign, isVol, CopyFromConstant); 6128 if (!TLI.findOptimalMemOpLowering( 6129 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6130 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6131 return SDValue(); 6132 6133 if (DstAlignCanChange) { 6134 Type *Ty = MemOps[0].getTypeForEVT(C); 6135 Align NewAlign = DL.getABITypeAlign(Ty); 6136 6137 // Don't promote to an alignment that would require dynamic stack 6138 // realignment. 6139 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6140 if (!TRI->needsStackRealignment(MF)) 6141 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6142 NewAlign = NewAlign / 2; 6143 6144 if (NewAlign > Alignment) { 6145 // Give the stack frame object a larger alignment if needed. 6146 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6147 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6148 Alignment = NewAlign; 6149 } 6150 } 6151 6152 MachineMemOperand::Flags MMOFlags = 6153 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6154 SmallVector<SDValue, 16> OutLoadChains; 6155 SmallVector<SDValue, 16> OutStoreChains; 6156 SmallVector<SDValue, 32> OutChains; 6157 unsigned NumMemOps = MemOps.size(); 6158 uint64_t SrcOff = 0, DstOff = 0; 6159 for (unsigned i = 0; i != NumMemOps; ++i) { 6160 EVT VT = MemOps[i]; 6161 unsigned VTSize = VT.getSizeInBits() / 8; 6162 SDValue Value, Store; 6163 6164 if (VTSize > Size) { 6165 // Issuing an unaligned load / store pair that overlaps with the previous 6166 // pair. Adjust the offset accordingly. 6167 assert(i == NumMemOps-1 && i != 0); 6168 SrcOff -= VTSize - Size; 6169 DstOff -= VTSize - Size; 6170 } 6171 6172 if (CopyFromConstant && 6173 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6174 // It's unlikely a store of a vector immediate can be done in a single 6175 // instruction. It would require a load from a constantpool first. 6176 // We only handle zero vectors here. 6177 // FIXME: Handle other cases where store of vector immediate is done in 6178 // a single instruction. 6179 ConstantDataArraySlice SubSlice; 6180 if (SrcOff < Slice.Length) { 6181 SubSlice = Slice; 6182 SubSlice.move(SrcOff); 6183 } else { 6184 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6185 SubSlice.Array = nullptr; 6186 SubSlice.Offset = 0; 6187 SubSlice.Length = VTSize; 6188 } 6189 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6190 if (Value.getNode()) { 6191 Store = DAG.getStore( 6192 Chain, dl, Value, 6193 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6194 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6195 OutChains.push_back(Store); 6196 } 6197 } 6198 6199 if (!Store.getNode()) { 6200 // The type might not be legal for the target. This should only happen 6201 // if the type is smaller than a legal type, as on PPC, so the right 6202 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6203 // to Load/Store if NVT==VT. 6204 // FIXME does the case above also need this? 6205 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6206 assert(NVT.bitsGE(VT)); 6207 6208 bool isDereferenceable = 6209 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6210 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6211 if (isDereferenceable) 6212 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6213 6214 Value = DAG.getExtLoad( 6215 ISD::EXTLOAD, dl, NVT, Chain, 6216 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6217 SrcPtrInfo.getWithOffset(SrcOff), VT, 6218 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags); 6219 OutLoadChains.push_back(Value.getValue(1)); 6220 6221 Store = DAG.getTruncStore( 6222 Chain, dl, Value, 6223 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6224 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags); 6225 OutStoreChains.push_back(Store); 6226 } 6227 SrcOff += VTSize; 6228 DstOff += VTSize; 6229 Size -= VTSize; 6230 } 6231 6232 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6233 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6234 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6235 6236 if (NumLdStInMemcpy) { 6237 // It may be that memcpy might be converted to memset if it's memcpy 6238 // of constants. In such a case, we won't have loads and stores, but 6239 // just stores. In the absence of loads, there is nothing to gang up. 6240 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6241 // If target does not care, just leave as it. 6242 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6243 OutChains.push_back(OutLoadChains[i]); 6244 OutChains.push_back(OutStoreChains[i]); 6245 } 6246 } else { 6247 // Ld/St less than/equal limit set by target. 6248 if (NumLdStInMemcpy <= GluedLdStLimit) { 6249 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6250 NumLdStInMemcpy, OutLoadChains, 6251 OutStoreChains); 6252 } else { 6253 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6254 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6255 unsigned GlueIter = 0; 6256 6257 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6258 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6259 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6260 6261 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6262 OutLoadChains, OutStoreChains); 6263 GlueIter += GluedLdStLimit; 6264 } 6265 6266 // Residual ld/st. 6267 if (RemainingLdStInMemcpy) { 6268 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6269 RemainingLdStInMemcpy, OutLoadChains, 6270 OutStoreChains); 6271 } 6272 } 6273 } 6274 } 6275 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6276 } 6277 6278 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6279 SDValue Chain, SDValue Dst, SDValue Src, 6280 uint64_t Size, Align Alignment, 6281 bool isVol, bool AlwaysInline, 6282 MachinePointerInfo DstPtrInfo, 6283 MachinePointerInfo SrcPtrInfo) { 6284 // Turn a memmove of undef to nop. 6285 // FIXME: We need to honor volatile even is Src is undef. 6286 if (Src.isUndef()) 6287 return Chain; 6288 6289 // Expand memmove to a series of load and store ops if the size operand falls 6290 // below a certain threshold. 6291 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6292 const DataLayout &DL = DAG.getDataLayout(); 6293 LLVMContext &C = *DAG.getContext(); 6294 std::vector<EVT> MemOps; 6295 bool DstAlignCanChange = false; 6296 MachineFunction &MF = DAG.getMachineFunction(); 6297 MachineFrameInfo &MFI = MF.getFrameInfo(); 6298 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6299 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6300 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6301 DstAlignCanChange = true; 6302 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6303 if (!SrcAlign || Alignment > *SrcAlign) 6304 SrcAlign = Alignment; 6305 assert(SrcAlign && "SrcAlign must be set"); 6306 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6307 if (!TLI.findOptimalMemOpLowering( 6308 MemOps, Limit, 6309 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6310 /*IsVolatile*/ true), 6311 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6312 MF.getFunction().getAttributes())) 6313 return SDValue(); 6314 6315 if (DstAlignCanChange) { 6316 Type *Ty = MemOps[0].getTypeForEVT(C); 6317 Align NewAlign = DL.getABITypeAlign(Ty); 6318 if (NewAlign > Alignment) { 6319 // Give the stack frame object a larger alignment if needed. 6320 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6321 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6322 Alignment = NewAlign; 6323 } 6324 } 6325 6326 MachineMemOperand::Flags MMOFlags = 6327 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6328 uint64_t SrcOff = 0, DstOff = 0; 6329 SmallVector<SDValue, 8> LoadValues; 6330 SmallVector<SDValue, 8> LoadChains; 6331 SmallVector<SDValue, 8> OutChains; 6332 unsigned NumMemOps = MemOps.size(); 6333 for (unsigned i = 0; i < NumMemOps; i++) { 6334 EVT VT = MemOps[i]; 6335 unsigned VTSize = VT.getSizeInBits() / 8; 6336 SDValue Value; 6337 6338 bool isDereferenceable = 6339 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6340 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6341 if (isDereferenceable) 6342 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6343 6344 Value = 6345 DAG.getLoad(VT, dl, Chain, 6346 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6347 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags); 6348 LoadValues.push_back(Value); 6349 LoadChains.push_back(Value.getValue(1)); 6350 SrcOff += VTSize; 6351 } 6352 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6353 OutChains.clear(); 6354 for (unsigned i = 0; i < NumMemOps; i++) { 6355 EVT VT = MemOps[i]; 6356 unsigned VTSize = VT.getSizeInBits() / 8; 6357 SDValue Store; 6358 6359 Store = 6360 DAG.getStore(Chain, dl, LoadValues[i], 6361 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6362 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6363 OutChains.push_back(Store); 6364 DstOff += VTSize; 6365 } 6366 6367 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6368 } 6369 6370 /// Lower the call to 'memset' intrinsic function into a series of store 6371 /// operations. 6372 /// 6373 /// \param DAG Selection DAG where lowered code is placed. 6374 /// \param dl Link to corresponding IR location. 6375 /// \param Chain Control flow dependency. 6376 /// \param Dst Pointer to destination memory location. 6377 /// \param Src Value of byte to write into the memory. 6378 /// \param Size Number of bytes to write. 6379 /// \param Alignment Alignment of the destination in bytes. 6380 /// \param isVol True if destination is volatile. 6381 /// \param DstPtrInfo IR information on the memory pointer. 6382 /// \returns New head in the control flow, if lowering was successful, empty 6383 /// SDValue otherwise. 6384 /// 6385 /// The function tries to replace 'llvm.memset' intrinsic with several store 6386 /// operations and value calculation code. This is usually profitable for small 6387 /// memory size. 6388 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6389 SDValue Chain, SDValue Dst, SDValue Src, 6390 uint64_t Size, Align Alignment, bool isVol, 6391 MachinePointerInfo DstPtrInfo) { 6392 // Turn a memset of undef to nop. 6393 // FIXME: We need to honor volatile even is Src is undef. 6394 if (Src.isUndef()) 6395 return Chain; 6396 6397 // Expand memset to a series of load/store ops if the size operand 6398 // falls below a certain threshold. 6399 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6400 std::vector<EVT> MemOps; 6401 bool DstAlignCanChange = false; 6402 MachineFunction &MF = DAG.getMachineFunction(); 6403 MachineFrameInfo &MFI = MF.getFrameInfo(); 6404 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6405 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6406 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6407 DstAlignCanChange = true; 6408 bool IsZeroVal = 6409 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 6410 if (!TLI.findOptimalMemOpLowering( 6411 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6412 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6413 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6414 return SDValue(); 6415 6416 if (DstAlignCanChange) { 6417 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6418 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6419 if (NewAlign > Alignment) { 6420 // Give the stack frame object a larger alignment if needed. 6421 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6422 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6423 Alignment = NewAlign; 6424 } 6425 } 6426 6427 SmallVector<SDValue, 8> OutChains; 6428 uint64_t DstOff = 0; 6429 unsigned NumMemOps = MemOps.size(); 6430 6431 // Find the largest store and generate the bit pattern for it. 6432 EVT LargestVT = MemOps[0]; 6433 for (unsigned i = 1; i < NumMemOps; i++) 6434 if (MemOps[i].bitsGT(LargestVT)) 6435 LargestVT = MemOps[i]; 6436 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6437 6438 for (unsigned i = 0; i < NumMemOps; i++) { 6439 EVT VT = MemOps[i]; 6440 unsigned VTSize = VT.getSizeInBits() / 8; 6441 if (VTSize > Size) { 6442 // Issuing an unaligned load / store pair that overlaps with the previous 6443 // pair. Adjust the offset accordingly. 6444 assert(i == NumMemOps-1 && i != 0); 6445 DstOff -= VTSize - Size; 6446 } 6447 6448 // If this store is smaller than the largest store see whether we can get 6449 // the smaller value for free with a truncate. 6450 SDValue Value = MemSetValue; 6451 if (VT.bitsLT(LargestVT)) { 6452 if (!LargestVT.isVector() && !VT.isVector() && 6453 TLI.isTruncateFree(LargestVT, VT)) 6454 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6455 else 6456 Value = getMemsetValue(Src, VT, DAG, dl); 6457 } 6458 assert(Value.getValueType() == VT && "Value with wrong type."); 6459 SDValue Store = DAG.getStore( 6460 Chain, dl, Value, 6461 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6462 DstPtrInfo.getWithOffset(DstOff), Alignment, 6463 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone); 6464 OutChains.push_back(Store); 6465 DstOff += VT.getSizeInBits() / 8; 6466 Size -= VTSize; 6467 } 6468 6469 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6470 } 6471 6472 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6473 unsigned AS) { 6474 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6475 // pointer operands can be losslessly bitcasted to pointers of address space 0 6476 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6477 report_fatal_error("cannot lower memory intrinsic in address space " + 6478 Twine(AS)); 6479 } 6480 } 6481 6482 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6483 SDValue Src, SDValue Size, Align Alignment, 6484 bool isVol, bool AlwaysInline, bool isTailCall, 6485 MachinePointerInfo DstPtrInfo, 6486 MachinePointerInfo SrcPtrInfo) { 6487 // Check to see if we should lower the memcpy to loads and stores first. 6488 // For cases within the target-specified limits, this is the best choice. 6489 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6490 if (ConstantSize) { 6491 // Memcpy with size zero? Just return the original chain. 6492 if (ConstantSize->isNullValue()) 6493 return Chain; 6494 6495 SDValue Result = getMemcpyLoadsAndStores( 6496 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6497 isVol, false, DstPtrInfo, SrcPtrInfo); 6498 if (Result.getNode()) 6499 return Result; 6500 } 6501 6502 // Then check to see if we should lower the memcpy with target-specific 6503 // code. If the target chooses to do this, this is the next best. 6504 if (TSI) { 6505 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6506 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6507 DstPtrInfo, SrcPtrInfo); 6508 if (Result.getNode()) 6509 return Result; 6510 } 6511 6512 // If we really need inline code and the target declined to provide it, 6513 // use a (potentially long) sequence of loads and stores. 6514 if (AlwaysInline) { 6515 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6516 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6517 ConstantSize->getZExtValue(), Alignment, 6518 isVol, true, DstPtrInfo, SrcPtrInfo); 6519 } 6520 6521 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6522 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6523 6524 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6525 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6526 // respect volatile, so they may do things like read or write memory 6527 // beyond the given memory regions. But fixing this isn't easy, and most 6528 // people don't care. 6529 6530 // Emit a library call. 6531 TargetLowering::ArgListTy Args; 6532 TargetLowering::ArgListEntry Entry; 6533 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6534 Entry.Node = Dst; Args.push_back(Entry); 6535 Entry.Node = Src; Args.push_back(Entry); 6536 6537 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6538 Entry.Node = Size; Args.push_back(Entry); 6539 // FIXME: pass in SDLoc 6540 TargetLowering::CallLoweringInfo CLI(*this); 6541 CLI.setDebugLoc(dl) 6542 .setChain(Chain) 6543 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6544 Dst.getValueType().getTypeForEVT(*getContext()), 6545 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6546 TLI->getPointerTy(getDataLayout())), 6547 std::move(Args)) 6548 .setDiscardResult() 6549 .setTailCall(isTailCall); 6550 6551 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6552 return CallResult.second; 6553 } 6554 6555 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6556 SDValue Dst, unsigned DstAlign, 6557 SDValue Src, unsigned SrcAlign, 6558 SDValue Size, Type *SizeTy, 6559 unsigned ElemSz, bool isTailCall, 6560 MachinePointerInfo DstPtrInfo, 6561 MachinePointerInfo SrcPtrInfo) { 6562 // Emit a library call. 6563 TargetLowering::ArgListTy Args; 6564 TargetLowering::ArgListEntry Entry; 6565 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6566 Entry.Node = Dst; 6567 Args.push_back(Entry); 6568 6569 Entry.Node = Src; 6570 Args.push_back(Entry); 6571 6572 Entry.Ty = SizeTy; 6573 Entry.Node = Size; 6574 Args.push_back(Entry); 6575 6576 RTLIB::Libcall LibraryCall = 6577 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6578 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6579 report_fatal_error("Unsupported element size"); 6580 6581 TargetLowering::CallLoweringInfo CLI(*this); 6582 CLI.setDebugLoc(dl) 6583 .setChain(Chain) 6584 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6585 Type::getVoidTy(*getContext()), 6586 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6587 TLI->getPointerTy(getDataLayout())), 6588 std::move(Args)) 6589 .setDiscardResult() 6590 .setTailCall(isTailCall); 6591 6592 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6593 return CallResult.second; 6594 } 6595 6596 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6597 SDValue Src, SDValue Size, Align Alignment, 6598 bool isVol, bool isTailCall, 6599 MachinePointerInfo DstPtrInfo, 6600 MachinePointerInfo SrcPtrInfo) { 6601 // Check to see if we should lower the memmove to loads and stores first. 6602 // For cases within the target-specified limits, this is the best choice. 6603 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6604 if (ConstantSize) { 6605 // Memmove with size zero? Just return the original chain. 6606 if (ConstantSize->isNullValue()) 6607 return Chain; 6608 6609 SDValue Result = getMemmoveLoadsAndStores( 6610 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6611 isVol, false, DstPtrInfo, SrcPtrInfo); 6612 if (Result.getNode()) 6613 return Result; 6614 } 6615 6616 // Then check to see if we should lower the memmove with target-specific 6617 // code. If the target chooses to do this, this is the next best. 6618 if (TSI) { 6619 SDValue Result = 6620 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 6621 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 6622 if (Result.getNode()) 6623 return Result; 6624 } 6625 6626 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6627 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6628 6629 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 6630 // not be safe. See memcpy above for more details. 6631 6632 // Emit a library call. 6633 TargetLowering::ArgListTy Args; 6634 TargetLowering::ArgListEntry Entry; 6635 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6636 Entry.Node = Dst; Args.push_back(Entry); 6637 Entry.Node = Src; Args.push_back(Entry); 6638 6639 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6640 Entry.Node = Size; Args.push_back(Entry); 6641 // FIXME: pass in SDLoc 6642 TargetLowering::CallLoweringInfo CLI(*this); 6643 CLI.setDebugLoc(dl) 6644 .setChain(Chain) 6645 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 6646 Dst.getValueType().getTypeForEVT(*getContext()), 6647 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 6648 TLI->getPointerTy(getDataLayout())), 6649 std::move(Args)) 6650 .setDiscardResult() 6651 .setTailCall(isTailCall); 6652 6653 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6654 return CallResult.second; 6655 } 6656 6657 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 6658 SDValue Dst, unsigned DstAlign, 6659 SDValue Src, unsigned SrcAlign, 6660 SDValue Size, Type *SizeTy, 6661 unsigned ElemSz, bool isTailCall, 6662 MachinePointerInfo DstPtrInfo, 6663 MachinePointerInfo SrcPtrInfo) { 6664 // Emit a library call. 6665 TargetLowering::ArgListTy Args; 6666 TargetLowering::ArgListEntry Entry; 6667 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6668 Entry.Node = Dst; 6669 Args.push_back(Entry); 6670 6671 Entry.Node = Src; 6672 Args.push_back(Entry); 6673 6674 Entry.Ty = SizeTy; 6675 Entry.Node = Size; 6676 Args.push_back(Entry); 6677 6678 RTLIB::Libcall LibraryCall = 6679 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6680 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6681 report_fatal_error("Unsupported element size"); 6682 6683 TargetLowering::CallLoweringInfo CLI(*this); 6684 CLI.setDebugLoc(dl) 6685 .setChain(Chain) 6686 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6687 Type::getVoidTy(*getContext()), 6688 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6689 TLI->getPointerTy(getDataLayout())), 6690 std::move(Args)) 6691 .setDiscardResult() 6692 .setTailCall(isTailCall); 6693 6694 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6695 return CallResult.second; 6696 } 6697 6698 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 6699 SDValue Src, SDValue Size, Align Alignment, 6700 bool isVol, bool isTailCall, 6701 MachinePointerInfo DstPtrInfo) { 6702 // Check to see if we should lower the memset to stores first. 6703 // For cases within the target-specified limits, this is the best choice. 6704 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6705 if (ConstantSize) { 6706 // Memset with size zero? Just return the original chain. 6707 if (ConstantSize->isNullValue()) 6708 return Chain; 6709 6710 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 6711 ConstantSize->getZExtValue(), Alignment, 6712 isVol, DstPtrInfo); 6713 6714 if (Result.getNode()) 6715 return Result; 6716 } 6717 6718 // Then check to see if we should lower the memset with target-specific 6719 // code. If the target chooses to do this, this is the next best. 6720 if (TSI) { 6721 SDValue Result = TSI->EmitTargetCodeForMemset( 6722 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 6723 if (Result.getNode()) 6724 return Result; 6725 } 6726 6727 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6728 6729 // Emit a library call. 6730 TargetLowering::ArgListTy Args; 6731 TargetLowering::ArgListEntry Entry; 6732 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 6733 Args.push_back(Entry); 6734 Entry.Node = Src; 6735 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 6736 Args.push_back(Entry); 6737 Entry.Node = Size; 6738 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6739 Args.push_back(Entry); 6740 6741 // FIXME: pass in SDLoc 6742 TargetLowering::CallLoweringInfo CLI(*this); 6743 CLI.setDebugLoc(dl) 6744 .setChain(Chain) 6745 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 6746 Dst.getValueType().getTypeForEVT(*getContext()), 6747 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 6748 TLI->getPointerTy(getDataLayout())), 6749 std::move(Args)) 6750 .setDiscardResult() 6751 .setTailCall(isTailCall); 6752 6753 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6754 return CallResult.second; 6755 } 6756 6757 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 6758 SDValue Dst, unsigned DstAlign, 6759 SDValue Value, SDValue Size, Type *SizeTy, 6760 unsigned ElemSz, bool isTailCall, 6761 MachinePointerInfo DstPtrInfo) { 6762 // Emit a library call. 6763 TargetLowering::ArgListTy Args; 6764 TargetLowering::ArgListEntry Entry; 6765 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6766 Entry.Node = Dst; 6767 Args.push_back(Entry); 6768 6769 Entry.Ty = Type::getInt8Ty(*getContext()); 6770 Entry.Node = Value; 6771 Args.push_back(Entry); 6772 6773 Entry.Ty = SizeTy; 6774 Entry.Node = Size; 6775 Args.push_back(Entry); 6776 6777 RTLIB::Libcall LibraryCall = 6778 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6779 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6780 report_fatal_error("Unsupported element size"); 6781 6782 TargetLowering::CallLoweringInfo CLI(*this); 6783 CLI.setDebugLoc(dl) 6784 .setChain(Chain) 6785 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6786 Type::getVoidTy(*getContext()), 6787 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6788 TLI->getPointerTy(getDataLayout())), 6789 std::move(Args)) 6790 .setDiscardResult() 6791 .setTailCall(isTailCall); 6792 6793 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6794 return CallResult.second; 6795 } 6796 6797 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6798 SDVTList VTList, ArrayRef<SDValue> Ops, 6799 MachineMemOperand *MMO) { 6800 FoldingSetNodeID ID; 6801 ID.AddInteger(MemVT.getRawBits()); 6802 AddNodeIDNode(ID, Opcode, VTList, Ops); 6803 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6804 void* IP = nullptr; 6805 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6806 cast<AtomicSDNode>(E)->refineAlignment(MMO); 6807 return SDValue(E, 0); 6808 } 6809 6810 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6811 VTList, MemVT, MMO); 6812 createOperands(N, Ops); 6813 6814 CSEMap.InsertNode(N, IP); 6815 InsertNode(N); 6816 return SDValue(N, 0); 6817 } 6818 6819 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 6820 EVT MemVT, SDVTList VTs, SDValue Chain, 6821 SDValue Ptr, SDValue Cmp, SDValue Swp, 6822 MachineMemOperand *MMO) { 6823 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 6824 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 6825 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 6826 6827 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 6828 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6829 } 6830 6831 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6832 SDValue Chain, SDValue Ptr, SDValue Val, 6833 MachineMemOperand *MMO) { 6834 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 6835 Opcode == ISD::ATOMIC_LOAD_SUB || 6836 Opcode == ISD::ATOMIC_LOAD_AND || 6837 Opcode == ISD::ATOMIC_LOAD_CLR || 6838 Opcode == ISD::ATOMIC_LOAD_OR || 6839 Opcode == ISD::ATOMIC_LOAD_XOR || 6840 Opcode == ISD::ATOMIC_LOAD_NAND || 6841 Opcode == ISD::ATOMIC_LOAD_MIN || 6842 Opcode == ISD::ATOMIC_LOAD_MAX || 6843 Opcode == ISD::ATOMIC_LOAD_UMIN || 6844 Opcode == ISD::ATOMIC_LOAD_UMAX || 6845 Opcode == ISD::ATOMIC_LOAD_FADD || 6846 Opcode == ISD::ATOMIC_LOAD_FSUB || 6847 Opcode == ISD::ATOMIC_SWAP || 6848 Opcode == ISD::ATOMIC_STORE) && 6849 "Invalid Atomic Op"); 6850 6851 EVT VT = Val.getValueType(); 6852 6853 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 6854 getVTList(VT, MVT::Other); 6855 SDValue Ops[] = {Chain, Ptr, Val}; 6856 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6857 } 6858 6859 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6860 EVT VT, SDValue Chain, SDValue Ptr, 6861 MachineMemOperand *MMO) { 6862 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 6863 6864 SDVTList VTs = getVTList(VT, MVT::Other); 6865 SDValue Ops[] = {Chain, Ptr}; 6866 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6867 } 6868 6869 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 6870 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 6871 if (Ops.size() == 1) 6872 return Ops[0]; 6873 6874 SmallVector<EVT, 4> VTs; 6875 VTs.reserve(Ops.size()); 6876 for (const SDValue &Op : Ops) 6877 VTs.push_back(Op.getValueType()); 6878 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 6879 } 6880 6881 SDValue SelectionDAG::getMemIntrinsicNode( 6882 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 6883 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 6884 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 6885 if (!Size && MemVT.isScalableVector()) 6886 Size = MemoryLocation::UnknownSize; 6887 else if (!Size) 6888 Size = MemVT.getStoreSize(); 6889 6890 MachineFunction &MF = getMachineFunction(); 6891 MachineMemOperand *MMO = 6892 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 6893 6894 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 6895 } 6896 6897 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 6898 SDVTList VTList, 6899 ArrayRef<SDValue> Ops, EVT MemVT, 6900 MachineMemOperand *MMO) { 6901 assert((Opcode == ISD::INTRINSIC_VOID || 6902 Opcode == ISD::INTRINSIC_W_CHAIN || 6903 Opcode == ISD::PREFETCH || 6904 ((int)Opcode <= std::numeric_limits<int>::max() && 6905 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 6906 "Opcode is not a memory-accessing opcode!"); 6907 6908 // Memoize the node unless it returns a flag. 6909 MemIntrinsicSDNode *N; 6910 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 6911 FoldingSetNodeID ID; 6912 AddNodeIDNode(ID, Opcode, VTList, Ops); 6913 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 6914 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 6915 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6916 void *IP = nullptr; 6917 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6918 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 6919 return SDValue(E, 0); 6920 } 6921 6922 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6923 VTList, MemVT, MMO); 6924 createOperands(N, Ops); 6925 6926 CSEMap.InsertNode(N, IP); 6927 } else { 6928 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6929 VTList, MemVT, MMO); 6930 createOperands(N, Ops); 6931 } 6932 InsertNode(N); 6933 SDValue V(N, 0); 6934 NewSDValueDbgMsg(V, "Creating new node: ", this); 6935 return V; 6936 } 6937 6938 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 6939 SDValue Chain, int FrameIndex, 6940 int64_t Size, int64_t Offset) { 6941 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 6942 const auto VTs = getVTList(MVT::Other); 6943 SDValue Ops[2] = { 6944 Chain, 6945 getFrameIndex(FrameIndex, 6946 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 6947 true)}; 6948 6949 FoldingSetNodeID ID; 6950 AddNodeIDNode(ID, Opcode, VTs, Ops); 6951 ID.AddInteger(FrameIndex); 6952 ID.AddInteger(Size); 6953 ID.AddInteger(Offset); 6954 void *IP = nullptr; 6955 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 6956 return SDValue(E, 0); 6957 6958 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 6959 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 6960 createOperands(N, Ops); 6961 CSEMap.InsertNode(N, IP); 6962 InsertNode(N); 6963 SDValue V(N, 0); 6964 NewSDValueDbgMsg(V, "Creating new node: ", this); 6965 return V; 6966 } 6967 6968 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 6969 uint64_t Guid, uint64_t Index, 6970 uint32_t Attr) { 6971 const unsigned Opcode = ISD::PSEUDO_PROBE; 6972 const auto VTs = getVTList(MVT::Other); 6973 SDValue Ops[] = {Chain}; 6974 FoldingSetNodeID ID; 6975 AddNodeIDNode(ID, Opcode, VTs, Ops); 6976 ID.AddInteger(Guid); 6977 ID.AddInteger(Index); 6978 void *IP = nullptr; 6979 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 6980 return SDValue(E, 0); 6981 6982 auto *N = newSDNode<PseudoProbeSDNode>( 6983 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 6984 createOperands(N, Ops); 6985 CSEMap.InsertNode(N, IP); 6986 InsertNode(N); 6987 SDValue V(N, 0); 6988 NewSDValueDbgMsg(V, "Creating new node: ", this); 6989 return V; 6990 } 6991 6992 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 6993 /// MachinePointerInfo record from it. This is particularly useful because the 6994 /// code generator has many cases where it doesn't bother passing in a 6995 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 6996 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 6997 SelectionDAG &DAG, SDValue Ptr, 6998 int64_t Offset = 0) { 6999 // If this is FI+Offset, we can model it. 7000 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7001 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7002 FI->getIndex(), Offset); 7003 7004 // If this is (FI+Offset1)+Offset2, we can model it. 7005 if (Ptr.getOpcode() != ISD::ADD || 7006 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7007 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7008 return Info; 7009 7010 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7011 return MachinePointerInfo::getFixedStack( 7012 DAG.getMachineFunction(), FI, 7013 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7014 } 7015 7016 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7017 /// MachinePointerInfo record from it. This is particularly useful because the 7018 /// code generator has many cases where it doesn't bother passing in a 7019 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7020 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7021 SelectionDAG &DAG, SDValue Ptr, 7022 SDValue OffsetOp) { 7023 // If the 'Offset' value isn't a constant, we can't handle this. 7024 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7025 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7026 if (OffsetOp.isUndef()) 7027 return InferPointerInfo(Info, DAG, Ptr); 7028 return Info; 7029 } 7030 7031 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7032 EVT VT, const SDLoc &dl, SDValue Chain, 7033 SDValue Ptr, SDValue Offset, 7034 MachinePointerInfo PtrInfo, EVT MemVT, 7035 Align Alignment, 7036 MachineMemOperand::Flags MMOFlags, 7037 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7038 assert(Chain.getValueType() == MVT::Other && 7039 "Invalid chain type"); 7040 7041 MMOFlags |= MachineMemOperand::MOLoad; 7042 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7043 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7044 // clients. 7045 if (PtrInfo.V.isNull()) 7046 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7047 7048 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7049 MachineFunction &MF = getMachineFunction(); 7050 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7051 Alignment, AAInfo, Ranges); 7052 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7053 } 7054 7055 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7056 EVT VT, const SDLoc &dl, SDValue Chain, 7057 SDValue Ptr, SDValue Offset, EVT MemVT, 7058 MachineMemOperand *MMO) { 7059 if (VT == MemVT) { 7060 ExtType = ISD::NON_EXTLOAD; 7061 } else if (ExtType == ISD::NON_EXTLOAD) { 7062 assert(VT == MemVT && "Non-extending load from different memory type!"); 7063 } else { 7064 // Extending load. 7065 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7066 "Should only be an extending load, not truncating!"); 7067 assert(VT.isInteger() == MemVT.isInteger() && 7068 "Cannot convert from FP to Int or Int -> FP!"); 7069 assert(VT.isVector() == MemVT.isVector() && 7070 "Cannot use an ext load to convert to or from a vector!"); 7071 assert((!VT.isVector() || 7072 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7073 "Cannot use an ext load to change the number of vector elements!"); 7074 } 7075 7076 bool Indexed = AM != ISD::UNINDEXED; 7077 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7078 7079 SDVTList VTs = Indexed ? 7080 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7081 SDValue Ops[] = { Chain, Ptr, Offset }; 7082 FoldingSetNodeID ID; 7083 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7084 ID.AddInteger(MemVT.getRawBits()); 7085 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7086 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7087 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7088 void *IP = nullptr; 7089 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7090 cast<LoadSDNode>(E)->refineAlignment(MMO); 7091 return SDValue(E, 0); 7092 } 7093 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7094 ExtType, MemVT, MMO); 7095 createOperands(N, Ops); 7096 7097 CSEMap.InsertNode(N, IP); 7098 InsertNode(N); 7099 SDValue V(N, 0); 7100 NewSDValueDbgMsg(V, "Creating new node: ", this); 7101 return V; 7102 } 7103 7104 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7105 SDValue Ptr, MachinePointerInfo PtrInfo, 7106 MaybeAlign Alignment, 7107 MachineMemOperand::Flags MMOFlags, 7108 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7109 SDValue Undef = getUNDEF(Ptr.getValueType()); 7110 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7111 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7112 } 7113 7114 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7115 SDValue Ptr, MachineMemOperand *MMO) { 7116 SDValue Undef = getUNDEF(Ptr.getValueType()); 7117 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7118 VT, MMO); 7119 } 7120 7121 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7122 EVT VT, SDValue Chain, SDValue Ptr, 7123 MachinePointerInfo PtrInfo, EVT MemVT, 7124 MaybeAlign Alignment, 7125 MachineMemOperand::Flags MMOFlags, 7126 const AAMDNodes &AAInfo) { 7127 SDValue Undef = getUNDEF(Ptr.getValueType()); 7128 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7129 MemVT, Alignment, MMOFlags, AAInfo); 7130 } 7131 7132 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7133 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7134 MachineMemOperand *MMO) { 7135 SDValue Undef = getUNDEF(Ptr.getValueType()); 7136 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7137 MemVT, MMO); 7138 } 7139 7140 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7141 SDValue Base, SDValue Offset, 7142 ISD::MemIndexedMode AM) { 7143 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7144 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7145 // Don't propagate the invariant or dereferenceable flags. 7146 auto MMOFlags = 7147 LD->getMemOperand()->getFlags() & 7148 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7149 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7150 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7151 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7152 } 7153 7154 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7155 SDValue Ptr, MachinePointerInfo PtrInfo, 7156 Align Alignment, 7157 MachineMemOperand::Flags MMOFlags, 7158 const AAMDNodes &AAInfo) { 7159 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7160 7161 MMOFlags |= MachineMemOperand::MOStore; 7162 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7163 7164 if (PtrInfo.V.isNull()) 7165 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7166 7167 MachineFunction &MF = getMachineFunction(); 7168 uint64_t Size = 7169 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7170 MachineMemOperand *MMO = 7171 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7172 return getStore(Chain, dl, Val, Ptr, MMO); 7173 } 7174 7175 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7176 SDValue Ptr, MachineMemOperand *MMO) { 7177 assert(Chain.getValueType() == MVT::Other && 7178 "Invalid chain type"); 7179 EVT VT = Val.getValueType(); 7180 SDVTList VTs = getVTList(MVT::Other); 7181 SDValue Undef = getUNDEF(Ptr.getValueType()); 7182 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7183 FoldingSetNodeID ID; 7184 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7185 ID.AddInteger(VT.getRawBits()); 7186 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7187 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7188 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7189 void *IP = nullptr; 7190 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7191 cast<StoreSDNode>(E)->refineAlignment(MMO); 7192 return SDValue(E, 0); 7193 } 7194 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7195 ISD::UNINDEXED, false, VT, MMO); 7196 createOperands(N, Ops); 7197 7198 CSEMap.InsertNode(N, IP); 7199 InsertNode(N); 7200 SDValue V(N, 0); 7201 NewSDValueDbgMsg(V, "Creating new node: ", this); 7202 return V; 7203 } 7204 7205 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7206 SDValue Ptr, MachinePointerInfo PtrInfo, 7207 EVT SVT, Align Alignment, 7208 MachineMemOperand::Flags MMOFlags, 7209 const AAMDNodes &AAInfo) { 7210 assert(Chain.getValueType() == MVT::Other && 7211 "Invalid chain type"); 7212 7213 MMOFlags |= MachineMemOperand::MOStore; 7214 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7215 7216 if (PtrInfo.V.isNull()) 7217 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7218 7219 MachineFunction &MF = getMachineFunction(); 7220 MachineMemOperand *MMO = MF.getMachineMemOperand( 7221 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7222 Alignment, AAInfo); 7223 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7224 } 7225 7226 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7227 SDValue Ptr, EVT SVT, 7228 MachineMemOperand *MMO) { 7229 EVT VT = Val.getValueType(); 7230 7231 assert(Chain.getValueType() == MVT::Other && 7232 "Invalid chain type"); 7233 if (VT == SVT) 7234 return getStore(Chain, dl, Val, Ptr, MMO); 7235 7236 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7237 "Should only be a truncating store, not extending!"); 7238 assert(VT.isInteger() == SVT.isInteger() && 7239 "Can't do FP-INT conversion!"); 7240 assert(VT.isVector() == SVT.isVector() && 7241 "Cannot use trunc store to convert to or from a vector!"); 7242 assert((!VT.isVector() || 7243 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7244 "Cannot use trunc store to change the number of vector elements!"); 7245 7246 SDVTList VTs = getVTList(MVT::Other); 7247 SDValue Undef = getUNDEF(Ptr.getValueType()); 7248 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7249 FoldingSetNodeID ID; 7250 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7251 ID.AddInteger(SVT.getRawBits()); 7252 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7253 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7254 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7255 void *IP = nullptr; 7256 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7257 cast<StoreSDNode>(E)->refineAlignment(MMO); 7258 return SDValue(E, 0); 7259 } 7260 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7261 ISD::UNINDEXED, true, SVT, MMO); 7262 createOperands(N, Ops); 7263 7264 CSEMap.InsertNode(N, IP); 7265 InsertNode(N); 7266 SDValue V(N, 0); 7267 NewSDValueDbgMsg(V, "Creating new node: ", this); 7268 return V; 7269 } 7270 7271 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7272 SDValue Base, SDValue Offset, 7273 ISD::MemIndexedMode AM) { 7274 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7275 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7276 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7277 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7278 FoldingSetNodeID ID; 7279 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7280 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7281 ID.AddInteger(ST->getRawSubclassData()); 7282 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7283 void *IP = nullptr; 7284 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7285 return SDValue(E, 0); 7286 7287 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7288 ST->isTruncatingStore(), ST->getMemoryVT(), 7289 ST->getMemOperand()); 7290 createOperands(N, Ops); 7291 7292 CSEMap.InsertNode(N, IP); 7293 InsertNode(N); 7294 SDValue V(N, 0); 7295 NewSDValueDbgMsg(V, "Creating new node: ", this); 7296 return V; 7297 } 7298 7299 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7300 SDValue Base, SDValue Offset, SDValue Mask, 7301 SDValue PassThru, EVT MemVT, 7302 MachineMemOperand *MMO, 7303 ISD::MemIndexedMode AM, 7304 ISD::LoadExtType ExtTy, bool isExpanding) { 7305 bool Indexed = AM != ISD::UNINDEXED; 7306 assert((Indexed || Offset.isUndef()) && 7307 "Unindexed masked load with an offset!"); 7308 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 7309 : getVTList(VT, MVT::Other); 7310 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 7311 FoldingSetNodeID ID; 7312 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 7313 ID.AddInteger(MemVT.getRawBits()); 7314 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 7315 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 7316 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7317 void *IP = nullptr; 7318 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7319 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 7320 return SDValue(E, 0); 7321 } 7322 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7323 AM, ExtTy, isExpanding, MemVT, MMO); 7324 createOperands(N, Ops); 7325 7326 CSEMap.InsertNode(N, IP); 7327 InsertNode(N); 7328 SDValue V(N, 0); 7329 NewSDValueDbgMsg(V, "Creating new node: ", this); 7330 return V; 7331 } 7332 7333 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 7334 SDValue Base, SDValue Offset, 7335 ISD::MemIndexedMode AM) { 7336 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 7337 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 7338 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 7339 Offset, LD->getMask(), LD->getPassThru(), 7340 LD->getMemoryVT(), LD->getMemOperand(), AM, 7341 LD->getExtensionType(), LD->isExpandingLoad()); 7342 } 7343 7344 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 7345 SDValue Val, SDValue Base, SDValue Offset, 7346 SDValue Mask, EVT MemVT, 7347 MachineMemOperand *MMO, 7348 ISD::MemIndexedMode AM, bool IsTruncating, 7349 bool IsCompressing) { 7350 assert(Chain.getValueType() == MVT::Other && 7351 "Invalid chain type"); 7352 bool Indexed = AM != ISD::UNINDEXED; 7353 assert((Indexed || Offset.isUndef()) && 7354 "Unindexed masked store with an offset!"); 7355 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 7356 : getVTList(MVT::Other); 7357 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 7358 FoldingSetNodeID ID; 7359 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 7360 ID.AddInteger(MemVT.getRawBits()); 7361 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 7362 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7363 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7364 void *IP = nullptr; 7365 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7366 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 7367 return SDValue(E, 0); 7368 } 7369 auto *N = 7370 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7371 IsTruncating, IsCompressing, MemVT, MMO); 7372 createOperands(N, Ops); 7373 7374 CSEMap.InsertNode(N, IP); 7375 InsertNode(N); 7376 SDValue V(N, 0); 7377 NewSDValueDbgMsg(V, "Creating new node: ", this); 7378 return V; 7379 } 7380 7381 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 7382 SDValue Base, SDValue Offset, 7383 ISD::MemIndexedMode AM) { 7384 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 7385 assert(ST->getOffset().isUndef() && 7386 "Masked store is already a indexed store!"); 7387 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 7388 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 7389 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 7390 } 7391 7392 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl, 7393 ArrayRef<SDValue> Ops, 7394 MachineMemOperand *MMO, 7395 ISD::MemIndexType IndexType, 7396 ISD::LoadExtType ExtTy) { 7397 assert(Ops.size() == 6 && "Incompatible number of operands"); 7398 7399 FoldingSetNodeID ID; 7400 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 7401 ID.AddInteger(VT.getRawBits()); 7402 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 7403 dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy)); 7404 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7405 void *IP = nullptr; 7406 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7407 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 7408 return SDValue(E, 0); 7409 } 7410 7411 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7412 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7413 VTs, VT, MMO, IndexType, ExtTy); 7414 createOperands(N, Ops); 7415 7416 assert(N->getPassThru().getValueType() == N->getValueType(0) && 7417 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 7418 assert(N->getMask().getValueType().getVectorElementCount() == 7419 N->getValueType(0).getVectorElementCount() && 7420 "Vector width mismatch between mask and data"); 7421 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7422 N->getValueType(0).getVectorElementCount().isScalable() && 7423 "Scalable flags of index and data do not match"); 7424 assert(ElementCount::isKnownGE( 7425 N->getIndex().getValueType().getVectorElementCount(), 7426 N->getValueType(0).getVectorElementCount()) && 7427 "Vector width mismatch between index and data"); 7428 assert(isa<ConstantSDNode>(N->getScale()) && 7429 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7430 "Scale should be a constant power of 2"); 7431 7432 CSEMap.InsertNode(N, IP); 7433 InsertNode(N); 7434 SDValue V(N, 0); 7435 NewSDValueDbgMsg(V, "Creating new node: ", this); 7436 return V; 7437 } 7438 7439 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl, 7440 ArrayRef<SDValue> Ops, 7441 MachineMemOperand *MMO, 7442 ISD::MemIndexType IndexType, 7443 bool IsTrunc) { 7444 assert(Ops.size() == 6 && "Incompatible number of operands"); 7445 7446 FoldingSetNodeID ID; 7447 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 7448 ID.AddInteger(VT.getRawBits()); 7449 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 7450 dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc)); 7451 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7452 void *IP = nullptr; 7453 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7454 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 7455 return SDValue(E, 0); 7456 } 7457 7458 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7459 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7460 VTs, VT, MMO, IndexType, IsTrunc); 7461 createOperands(N, Ops); 7462 7463 assert(N->getMask().getValueType().getVectorElementCount() == 7464 N->getValue().getValueType().getVectorElementCount() && 7465 "Vector width mismatch between mask and data"); 7466 assert( 7467 N->getIndex().getValueType().getVectorElementCount().isScalable() == 7468 N->getValue().getValueType().getVectorElementCount().isScalable() && 7469 "Scalable flags of index and data do not match"); 7470 assert(ElementCount::isKnownGE( 7471 N->getIndex().getValueType().getVectorElementCount(), 7472 N->getValue().getValueType().getVectorElementCount()) && 7473 "Vector width mismatch between index and data"); 7474 assert(isa<ConstantSDNode>(N->getScale()) && 7475 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7476 "Scale should be a constant power of 2"); 7477 7478 CSEMap.InsertNode(N, IP); 7479 InsertNode(N); 7480 SDValue V(N, 0); 7481 NewSDValueDbgMsg(V, "Creating new node: ", this); 7482 return V; 7483 } 7484 7485 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 7486 // select undef, T, F --> T (if T is a constant), otherwise F 7487 // select, ?, undef, F --> F 7488 // select, ?, T, undef --> T 7489 if (Cond.isUndef()) 7490 return isConstantValueOfAnyType(T) ? T : F; 7491 if (T.isUndef()) 7492 return F; 7493 if (F.isUndef()) 7494 return T; 7495 7496 // select true, T, F --> T 7497 // select false, T, F --> F 7498 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 7499 return CondC->isNullValue() ? F : T; 7500 7501 // TODO: This should simplify VSELECT with constant condition using something 7502 // like this (but check boolean contents to be complete?): 7503 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 7504 // return T; 7505 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 7506 // return F; 7507 7508 // select ?, T, T --> T 7509 if (T == F) 7510 return T; 7511 7512 return SDValue(); 7513 } 7514 7515 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 7516 // shift undef, Y --> 0 (can always assume that the undef value is 0) 7517 if (X.isUndef()) 7518 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 7519 // shift X, undef --> undef (because it may shift by the bitwidth) 7520 if (Y.isUndef()) 7521 return getUNDEF(X.getValueType()); 7522 7523 // shift 0, Y --> 0 7524 // shift X, 0 --> X 7525 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 7526 return X; 7527 7528 // shift X, C >= bitwidth(X) --> undef 7529 // All vector elements must be too big (or undef) to avoid partial undefs. 7530 auto isShiftTooBig = [X](ConstantSDNode *Val) { 7531 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 7532 }; 7533 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 7534 return getUNDEF(X.getValueType()); 7535 7536 return SDValue(); 7537 } 7538 7539 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 7540 SDNodeFlags Flags) { 7541 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 7542 // (an undef operand can be chosen to be Nan/Inf), then the result of this 7543 // operation is poison. That result can be relaxed to undef. 7544 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 7545 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 7546 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 7547 (YC && YC->getValueAPF().isNaN()); 7548 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 7549 (YC && YC->getValueAPF().isInfinity()); 7550 7551 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 7552 return getUNDEF(X.getValueType()); 7553 7554 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 7555 return getUNDEF(X.getValueType()); 7556 7557 if (!YC) 7558 return SDValue(); 7559 7560 // X + -0.0 --> X 7561 if (Opcode == ISD::FADD) 7562 if (YC->getValueAPF().isNegZero()) 7563 return X; 7564 7565 // X - +0.0 --> X 7566 if (Opcode == ISD::FSUB) 7567 if (YC->getValueAPF().isPosZero()) 7568 return X; 7569 7570 // X * 1.0 --> X 7571 // X / 1.0 --> X 7572 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 7573 if (YC->getValueAPF().isExactlyValue(1.0)) 7574 return X; 7575 7576 // X * 0.0 --> 0.0 7577 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 7578 if (YC->getValueAPF().isZero()) 7579 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 7580 7581 return SDValue(); 7582 } 7583 7584 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 7585 SDValue Ptr, SDValue SV, unsigned Align) { 7586 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 7587 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 7588 } 7589 7590 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7591 ArrayRef<SDUse> Ops) { 7592 switch (Ops.size()) { 7593 case 0: return getNode(Opcode, DL, VT); 7594 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 7595 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 7596 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 7597 default: break; 7598 } 7599 7600 // Copy from an SDUse array into an SDValue array for use with 7601 // the regular getNode logic. 7602 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 7603 return getNode(Opcode, DL, VT, NewOps); 7604 } 7605 7606 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7607 ArrayRef<SDValue> Ops) { 7608 SDNodeFlags Flags; 7609 if (Inserter) 7610 Flags = Inserter->getFlags(); 7611 return getNode(Opcode, DL, VT, Ops, Flags); 7612 } 7613 7614 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7615 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7616 unsigned NumOps = Ops.size(); 7617 switch (NumOps) { 7618 case 0: return getNode(Opcode, DL, VT); 7619 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 7620 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 7621 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 7622 default: break; 7623 } 7624 7625 #ifndef NDEBUG 7626 for (auto &Op : Ops) 7627 assert(Op.getOpcode() != ISD::DELETED_NODE && 7628 "Operand is DELETED_NODE!"); 7629 #endif 7630 7631 switch (Opcode) { 7632 default: break; 7633 case ISD::BUILD_VECTOR: 7634 // Attempt to simplify BUILD_VECTOR. 7635 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 7636 return V; 7637 break; 7638 case ISD::CONCAT_VECTORS: 7639 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 7640 return V; 7641 break; 7642 case ISD::SELECT_CC: 7643 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 7644 assert(Ops[0].getValueType() == Ops[1].getValueType() && 7645 "LHS and RHS of condition must have same type!"); 7646 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7647 "True and False arms of SelectCC must have same type!"); 7648 assert(Ops[2].getValueType() == VT && 7649 "select_cc node must be of same type as true and false value!"); 7650 break; 7651 case ISD::BR_CC: 7652 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 7653 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7654 "LHS/RHS of comparison should match types!"); 7655 break; 7656 } 7657 7658 // Memoize nodes. 7659 SDNode *N; 7660 SDVTList VTs = getVTList(VT); 7661 7662 if (VT != MVT::Glue) { 7663 FoldingSetNodeID ID; 7664 AddNodeIDNode(ID, Opcode, VTs, Ops); 7665 void *IP = nullptr; 7666 7667 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7668 return SDValue(E, 0); 7669 7670 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7671 createOperands(N, Ops); 7672 7673 CSEMap.InsertNode(N, IP); 7674 } else { 7675 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7676 createOperands(N, Ops); 7677 } 7678 7679 N->setFlags(Flags); 7680 InsertNode(N); 7681 SDValue V(N, 0); 7682 NewSDValueDbgMsg(V, "Creating new node: ", this); 7683 return V; 7684 } 7685 7686 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7687 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 7688 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 7689 } 7690 7691 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7692 ArrayRef<SDValue> Ops) { 7693 SDNodeFlags Flags; 7694 if (Inserter) 7695 Flags = Inserter->getFlags(); 7696 return getNode(Opcode, DL, VTList, Ops, Flags); 7697 } 7698 7699 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7700 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7701 if (VTList.NumVTs == 1) 7702 return getNode(Opcode, DL, VTList.VTs[0], Ops); 7703 7704 #ifndef NDEBUG 7705 for (auto &Op : Ops) 7706 assert(Op.getOpcode() != ISD::DELETED_NODE && 7707 "Operand is DELETED_NODE!"); 7708 #endif 7709 7710 switch (Opcode) { 7711 case ISD::STRICT_FP_EXTEND: 7712 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 7713 "Invalid STRICT_FP_EXTEND!"); 7714 assert(VTList.VTs[0].isFloatingPoint() && 7715 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 7716 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7717 "STRICT_FP_EXTEND result type should be vector iff the operand " 7718 "type is vector!"); 7719 assert((!VTList.VTs[0].isVector() || 7720 VTList.VTs[0].getVectorNumElements() == 7721 Ops[1].getValueType().getVectorNumElements()) && 7722 "Vector element count mismatch!"); 7723 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 7724 "Invalid fpext node, dst <= src!"); 7725 break; 7726 case ISD::STRICT_FP_ROUND: 7727 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 7728 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7729 "STRICT_FP_ROUND result type should be vector iff the operand " 7730 "type is vector!"); 7731 assert((!VTList.VTs[0].isVector() || 7732 VTList.VTs[0].getVectorNumElements() == 7733 Ops[1].getValueType().getVectorNumElements()) && 7734 "Vector element count mismatch!"); 7735 assert(VTList.VTs[0].isFloatingPoint() && 7736 Ops[1].getValueType().isFloatingPoint() && 7737 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 7738 isa<ConstantSDNode>(Ops[2]) && 7739 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 7740 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 7741 "Invalid STRICT_FP_ROUND!"); 7742 break; 7743 #if 0 7744 // FIXME: figure out how to safely handle things like 7745 // int foo(int x) { return 1 << (x & 255); } 7746 // int bar() { return foo(256); } 7747 case ISD::SRA_PARTS: 7748 case ISD::SRL_PARTS: 7749 case ISD::SHL_PARTS: 7750 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 7751 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 7752 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7753 else if (N3.getOpcode() == ISD::AND) 7754 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 7755 // If the and is only masking out bits that cannot effect the shift, 7756 // eliminate the and. 7757 unsigned NumBits = VT.getScalarSizeInBits()*2; 7758 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 7759 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7760 } 7761 break; 7762 #endif 7763 } 7764 7765 // Memoize the node unless it returns a flag. 7766 SDNode *N; 7767 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7768 FoldingSetNodeID ID; 7769 AddNodeIDNode(ID, Opcode, VTList, Ops); 7770 void *IP = nullptr; 7771 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7772 return SDValue(E, 0); 7773 7774 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7775 createOperands(N, Ops); 7776 CSEMap.InsertNode(N, IP); 7777 } else { 7778 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7779 createOperands(N, Ops); 7780 } 7781 7782 N->setFlags(Flags); 7783 InsertNode(N); 7784 SDValue V(N, 0); 7785 NewSDValueDbgMsg(V, "Creating new node: ", this); 7786 return V; 7787 } 7788 7789 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7790 SDVTList VTList) { 7791 return getNode(Opcode, DL, VTList, None); 7792 } 7793 7794 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7795 SDValue N1) { 7796 SDValue Ops[] = { N1 }; 7797 return getNode(Opcode, DL, VTList, Ops); 7798 } 7799 7800 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7801 SDValue N1, SDValue N2) { 7802 SDValue Ops[] = { N1, N2 }; 7803 return getNode(Opcode, DL, VTList, Ops); 7804 } 7805 7806 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7807 SDValue N1, SDValue N2, SDValue N3) { 7808 SDValue Ops[] = { N1, N2, N3 }; 7809 return getNode(Opcode, DL, VTList, Ops); 7810 } 7811 7812 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7813 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 7814 SDValue Ops[] = { N1, N2, N3, N4 }; 7815 return getNode(Opcode, DL, VTList, Ops); 7816 } 7817 7818 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7819 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 7820 SDValue N5) { 7821 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 7822 return getNode(Opcode, DL, VTList, Ops); 7823 } 7824 7825 SDVTList SelectionDAG::getVTList(EVT VT) { 7826 return makeVTList(SDNode::getValueTypeList(VT), 1); 7827 } 7828 7829 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 7830 FoldingSetNodeID ID; 7831 ID.AddInteger(2U); 7832 ID.AddInteger(VT1.getRawBits()); 7833 ID.AddInteger(VT2.getRawBits()); 7834 7835 void *IP = nullptr; 7836 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7837 if (!Result) { 7838 EVT *Array = Allocator.Allocate<EVT>(2); 7839 Array[0] = VT1; 7840 Array[1] = VT2; 7841 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 7842 VTListMap.InsertNode(Result, IP); 7843 } 7844 return Result->getSDVTList(); 7845 } 7846 7847 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 7848 FoldingSetNodeID ID; 7849 ID.AddInteger(3U); 7850 ID.AddInteger(VT1.getRawBits()); 7851 ID.AddInteger(VT2.getRawBits()); 7852 ID.AddInteger(VT3.getRawBits()); 7853 7854 void *IP = nullptr; 7855 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7856 if (!Result) { 7857 EVT *Array = Allocator.Allocate<EVT>(3); 7858 Array[0] = VT1; 7859 Array[1] = VT2; 7860 Array[2] = VT3; 7861 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 7862 VTListMap.InsertNode(Result, IP); 7863 } 7864 return Result->getSDVTList(); 7865 } 7866 7867 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 7868 FoldingSetNodeID ID; 7869 ID.AddInteger(4U); 7870 ID.AddInteger(VT1.getRawBits()); 7871 ID.AddInteger(VT2.getRawBits()); 7872 ID.AddInteger(VT3.getRawBits()); 7873 ID.AddInteger(VT4.getRawBits()); 7874 7875 void *IP = nullptr; 7876 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7877 if (!Result) { 7878 EVT *Array = Allocator.Allocate<EVT>(4); 7879 Array[0] = VT1; 7880 Array[1] = VT2; 7881 Array[2] = VT3; 7882 Array[3] = VT4; 7883 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 7884 VTListMap.InsertNode(Result, IP); 7885 } 7886 return Result->getSDVTList(); 7887 } 7888 7889 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 7890 unsigned NumVTs = VTs.size(); 7891 FoldingSetNodeID ID; 7892 ID.AddInteger(NumVTs); 7893 for (unsigned index = 0; index < NumVTs; index++) { 7894 ID.AddInteger(VTs[index].getRawBits()); 7895 } 7896 7897 void *IP = nullptr; 7898 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7899 if (!Result) { 7900 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 7901 llvm::copy(VTs, Array); 7902 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 7903 VTListMap.InsertNode(Result, IP); 7904 } 7905 return Result->getSDVTList(); 7906 } 7907 7908 7909 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 7910 /// specified operands. If the resultant node already exists in the DAG, 7911 /// this does not modify the specified node, instead it returns the node that 7912 /// already exists. If the resultant node does not exist in the DAG, the 7913 /// input node is returned. As a degenerate case, if you specify the same 7914 /// input operands as the node already has, the input node is returned. 7915 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 7916 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 7917 7918 // Check to see if there is no change. 7919 if (Op == N->getOperand(0)) return N; 7920 7921 // See if the modified node already exists. 7922 void *InsertPos = nullptr; 7923 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 7924 return Existing; 7925 7926 // Nope it doesn't. Remove the node from its current place in the maps. 7927 if (InsertPos) 7928 if (!RemoveNodeFromCSEMaps(N)) 7929 InsertPos = nullptr; 7930 7931 // Now we update the operands. 7932 N->OperandList[0].set(Op); 7933 7934 updateDivergence(N); 7935 // If this gets put into a CSE map, add it. 7936 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7937 return N; 7938 } 7939 7940 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 7941 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 7942 7943 // Check to see if there is no change. 7944 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 7945 return N; // No operands changed, just return the input node. 7946 7947 // See if the modified node already exists. 7948 void *InsertPos = nullptr; 7949 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 7950 return Existing; 7951 7952 // Nope it doesn't. Remove the node from its current place in the maps. 7953 if (InsertPos) 7954 if (!RemoveNodeFromCSEMaps(N)) 7955 InsertPos = nullptr; 7956 7957 // Now we update the operands. 7958 if (N->OperandList[0] != Op1) 7959 N->OperandList[0].set(Op1); 7960 if (N->OperandList[1] != Op2) 7961 N->OperandList[1].set(Op2); 7962 7963 updateDivergence(N); 7964 // If this gets put into a CSE map, add it. 7965 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7966 return N; 7967 } 7968 7969 SDNode *SelectionDAG:: 7970 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 7971 SDValue Ops[] = { Op1, Op2, Op3 }; 7972 return UpdateNodeOperands(N, Ops); 7973 } 7974 7975 SDNode *SelectionDAG:: 7976 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 7977 SDValue Op3, SDValue Op4) { 7978 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 7979 return UpdateNodeOperands(N, Ops); 7980 } 7981 7982 SDNode *SelectionDAG:: 7983 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 7984 SDValue Op3, SDValue Op4, SDValue Op5) { 7985 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 7986 return UpdateNodeOperands(N, Ops); 7987 } 7988 7989 SDNode *SelectionDAG:: 7990 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 7991 unsigned NumOps = Ops.size(); 7992 assert(N->getNumOperands() == NumOps && 7993 "Update with wrong number of operands"); 7994 7995 // If no operands changed just return the input node. 7996 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 7997 return N; 7998 7999 // See if the modified node already exists. 8000 void *InsertPos = nullptr; 8001 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8002 return Existing; 8003 8004 // Nope it doesn't. Remove the node from its current place in the maps. 8005 if (InsertPos) 8006 if (!RemoveNodeFromCSEMaps(N)) 8007 InsertPos = nullptr; 8008 8009 // Now we update the operands. 8010 for (unsigned i = 0; i != NumOps; ++i) 8011 if (N->OperandList[i] != Ops[i]) 8012 N->OperandList[i].set(Ops[i]); 8013 8014 updateDivergence(N); 8015 // If this gets put into a CSE map, add it. 8016 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8017 return N; 8018 } 8019 8020 /// DropOperands - Release the operands and set this node to have 8021 /// zero operands. 8022 void SDNode::DropOperands() { 8023 // Unlike the code in MorphNodeTo that does this, we don't need to 8024 // watch for dead nodes here. 8025 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8026 SDUse &Use = *I++; 8027 Use.set(SDValue()); 8028 } 8029 } 8030 8031 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8032 ArrayRef<MachineMemOperand *> NewMemRefs) { 8033 if (NewMemRefs.empty()) { 8034 N->clearMemRefs(); 8035 return; 8036 } 8037 8038 // Check if we can avoid allocating by storing a single reference directly. 8039 if (NewMemRefs.size() == 1) { 8040 N->MemRefs = NewMemRefs[0]; 8041 N->NumMemRefs = 1; 8042 return; 8043 } 8044 8045 MachineMemOperand **MemRefsBuffer = 8046 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8047 llvm::copy(NewMemRefs, MemRefsBuffer); 8048 N->MemRefs = MemRefsBuffer; 8049 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8050 } 8051 8052 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8053 /// machine opcode. 8054 /// 8055 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8056 EVT VT) { 8057 SDVTList VTs = getVTList(VT); 8058 return SelectNodeTo(N, MachineOpc, VTs, None); 8059 } 8060 8061 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8062 EVT VT, SDValue Op1) { 8063 SDVTList VTs = getVTList(VT); 8064 SDValue Ops[] = { Op1 }; 8065 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8066 } 8067 8068 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8069 EVT VT, SDValue Op1, 8070 SDValue Op2) { 8071 SDVTList VTs = getVTList(VT); 8072 SDValue Ops[] = { Op1, Op2 }; 8073 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8074 } 8075 8076 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8077 EVT VT, SDValue Op1, 8078 SDValue Op2, SDValue Op3) { 8079 SDVTList VTs = getVTList(VT); 8080 SDValue Ops[] = { Op1, Op2, Op3 }; 8081 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8082 } 8083 8084 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8085 EVT VT, ArrayRef<SDValue> Ops) { 8086 SDVTList VTs = getVTList(VT); 8087 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8088 } 8089 8090 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8091 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8092 SDVTList VTs = getVTList(VT1, VT2); 8093 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8094 } 8095 8096 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8097 EVT VT1, EVT VT2) { 8098 SDVTList VTs = getVTList(VT1, VT2); 8099 return SelectNodeTo(N, MachineOpc, VTs, None); 8100 } 8101 8102 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8103 EVT VT1, EVT VT2, EVT VT3, 8104 ArrayRef<SDValue> Ops) { 8105 SDVTList VTs = getVTList(VT1, VT2, VT3); 8106 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8107 } 8108 8109 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8110 EVT VT1, EVT VT2, 8111 SDValue Op1, SDValue Op2) { 8112 SDVTList VTs = getVTList(VT1, VT2); 8113 SDValue Ops[] = { Op1, Op2 }; 8114 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8115 } 8116 8117 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8118 SDVTList VTs,ArrayRef<SDValue> Ops) { 8119 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8120 // Reset the NodeID to -1. 8121 New->setNodeId(-1); 8122 if (New != N) { 8123 ReplaceAllUsesWith(N, New); 8124 RemoveDeadNode(N); 8125 } 8126 return New; 8127 } 8128 8129 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8130 /// the line number information on the merged node since it is not possible to 8131 /// preserve the information that operation is associated with multiple lines. 8132 /// This will make the debugger working better at -O0, were there is a higher 8133 /// probability having other instructions associated with that line. 8134 /// 8135 /// For IROrder, we keep the smaller of the two 8136 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8137 DebugLoc NLoc = N->getDebugLoc(); 8138 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8139 N->setDebugLoc(DebugLoc()); 8140 } 8141 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8142 N->setIROrder(Order); 8143 return N; 8144 } 8145 8146 /// MorphNodeTo - This *mutates* the specified node to have the specified 8147 /// return type, opcode, and operands. 8148 /// 8149 /// Note that MorphNodeTo returns the resultant node. If there is already a 8150 /// node of the specified opcode and operands, it returns that node instead of 8151 /// the current one. Note that the SDLoc need not be the same. 8152 /// 8153 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8154 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8155 /// node, and because it doesn't require CSE recalculation for any of 8156 /// the node's users. 8157 /// 8158 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8159 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8160 /// the legalizer which maintain worklists that would need to be updated when 8161 /// deleting things. 8162 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8163 SDVTList VTs, ArrayRef<SDValue> Ops) { 8164 // If an identical node already exists, use it. 8165 void *IP = nullptr; 8166 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8167 FoldingSetNodeID ID; 8168 AddNodeIDNode(ID, Opc, VTs, Ops); 8169 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8170 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8171 } 8172 8173 if (!RemoveNodeFromCSEMaps(N)) 8174 IP = nullptr; 8175 8176 // Start the morphing. 8177 N->NodeType = Opc; 8178 N->ValueList = VTs.VTs; 8179 N->NumValues = VTs.NumVTs; 8180 8181 // Clear the operands list, updating used nodes to remove this from their 8182 // use list. Keep track of any operands that become dead as a result. 8183 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8184 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8185 SDUse &Use = *I++; 8186 SDNode *Used = Use.getNode(); 8187 Use.set(SDValue()); 8188 if (Used->use_empty()) 8189 DeadNodeSet.insert(Used); 8190 } 8191 8192 // For MachineNode, initialize the memory references information. 8193 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8194 MN->clearMemRefs(); 8195 8196 // Swap for an appropriately sized array from the recycler. 8197 removeOperands(N); 8198 createOperands(N, Ops); 8199 8200 // Delete any nodes that are still dead after adding the uses for the 8201 // new operands. 8202 if (!DeadNodeSet.empty()) { 8203 SmallVector<SDNode *, 16> DeadNodes; 8204 for (SDNode *N : DeadNodeSet) 8205 if (N->use_empty()) 8206 DeadNodes.push_back(N); 8207 RemoveDeadNodes(DeadNodes); 8208 } 8209 8210 if (IP) 8211 CSEMap.InsertNode(N, IP); // Memoize the new node. 8212 return N; 8213 } 8214 8215 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8216 unsigned OrigOpc = Node->getOpcode(); 8217 unsigned NewOpc; 8218 switch (OrigOpc) { 8219 default: 8220 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8221 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8222 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8223 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8224 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8225 #include "llvm/IR/ConstrainedOps.def" 8226 } 8227 8228 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8229 8230 // We're taking this node out of the chain, so we need to re-link things. 8231 SDValue InputChain = Node->getOperand(0); 8232 SDValue OutputChain = SDValue(Node, 1); 8233 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8234 8235 SmallVector<SDValue, 3> Ops; 8236 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8237 Ops.push_back(Node->getOperand(i)); 8238 8239 SDVTList VTs = getVTList(Node->getValueType(0)); 8240 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8241 8242 // MorphNodeTo can operate in two ways: if an existing node with the 8243 // specified operands exists, it can just return it. Otherwise, it 8244 // updates the node in place to have the requested operands. 8245 if (Res == Node) { 8246 // If we updated the node in place, reset the node ID. To the isel, 8247 // this should be just like a newly allocated machine node. 8248 Res->setNodeId(-1); 8249 } else { 8250 ReplaceAllUsesWith(Node, Res); 8251 RemoveDeadNode(Node); 8252 } 8253 8254 return Res; 8255 } 8256 8257 /// getMachineNode - These are used for target selectors to create a new node 8258 /// with specified return type(s), MachineInstr opcode, and operands. 8259 /// 8260 /// Note that getMachineNode returns the resultant node. If there is already a 8261 /// node of the specified opcode and operands, it returns that node instead of 8262 /// the current one. 8263 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8264 EVT VT) { 8265 SDVTList VTs = getVTList(VT); 8266 return getMachineNode(Opcode, dl, VTs, None); 8267 } 8268 8269 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8270 EVT VT, SDValue Op1) { 8271 SDVTList VTs = getVTList(VT); 8272 SDValue Ops[] = { Op1 }; 8273 return getMachineNode(Opcode, dl, VTs, Ops); 8274 } 8275 8276 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8277 EVT VT, SDValue Op1, SDValue Op2) { 8278 SDVTList VTs = getVTList(VT); 8279 SDValue Ops[] = { Op1, Op2 }; 8280 return getMachineNode(Opcode, dl, VTs, Ops); 8281 } 8282 8283 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8284 EVT VT, SDValue Op1, SDValue Op2, 8285 SDValue Op3) { 8286 SDVTList VTs = getVTList(VT); 8287 SDValue Ops[] = { Op1, Op2, Op3 }; 8288 return getMachineNode(Opcode, dl, VTs, Ops); 8289 } 8290 8291 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8292 EVT VT, ArrayRef<SDValue> Ops) { 8293 SDVTList VTs = getVTList(VT); 8294 return getMachineNode(Opcode, dl, VTs, Ops); 8295 } 8296 8297 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8298 EVT VT1, EVT VT2, SDValue Op1, 8299 SDValue Op2) { 8300 SDVTList VTs = getVTList(VT1, VT2); 8301 SDValue Ops[] = { Op1, Op2 }; 8302 return getMachineNode(Opcode, dl, VTs, Ops); 8303 } 8304 8305 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8306 EVT VT1, EVT VT2, SDValue Op1, 8307 SDValue Op2, SDValue Op3) { 8308 SDVTList VTs = getVTList(VT1, VT2); 8309 SDValue Ops[] = { Op1, Op2, Op3 }; 8310 return getMachineNode(Opcode, dl, VTs, Ops); 8311 } 8312 8313 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8314 EVT VT1, EVT VT2, 8315 ArrayRef<SDValue> Ops) { 8316 SDVTList VTs = getVTList(VT1, VT2); 8317 return getMachineNode(Opcode, dl, VTs, Ops); 8318 } 8319 8320 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8321 EVT VT1, EVT VT2, EVT VT3, 8322 SDValue Op1, SDValue Op2) { 8323 SDVTList VTs = getVTList(VT1, VT2, VT3); 8324 SDValue Ops[] = { Op1, Op2 }; 8325 return getMachineNode(Opcode, dl, VTs, Ops); 8326 } 8327 8328 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8329 EVT VT1, EVT VT2, EVT VT3, 8330 SDValue Op1, SDValue Op2, 8331 SDValue Op3) { 8332 SDVTList VTs = getVTList(VT1, VT2, VT3); 8333 SDValue Ops[] = { Op1, Op2, Op3 }; 8334 return getMachineNode(Opcode, dl, VTs, Ops); 8335 } 8336 8337 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8338 EVT VT1, EVT VT2, EVT VT3, 8339 ArrayRef<SDValue> Ops) { 8340 SDVTList VTs = getVTList(VT1, VT2, VT3); 8341 return getMachineNode(Opcode, dl, VTs, Ops); 8342 } 8343 8344 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8345 ArrayRef<EVT> ResultTys, 8346 ArrayRef<SDValue> Ops) { 8347 SDVTList VTs = getVTList(ResultTys); 8348 return getMachineNode(Opcode, dl, VTs, Ops); 8349 } 8350 8351 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 8352 SDVTList VTs, 8353 ArrayRef<SDValue> Ops) { 8354 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 8355 MachineSDNode *N; 8356 void *IP = nullptr; 8357 8358 if (DoCSE) { 8359 FoldingSetNodeID ID; 8360 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 8361 IP = nullptr; 8362 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8363 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 8364 } 8365 } 8366 8367 // Allocate a new MachineSDNode. 8368 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8369 createOperands(N, Ops); 8370 8371 if (DoCSE) 8372 CSEMap.InsertNode(N, IP); 8373 8374 InsertNode(N); 8375 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 8376 return N; 8377 } 8378 8379 /// getTargetExtractSubreg - A convenience function for creating 8380 /// TargetOpcode::EXTRACT_SUBREG nodes. 8381 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8382 SDValue Operand) { 8383 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8384 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 8385 VT, Operand, SRIdxVal); 8386 return SDValue(Subreg, 0); 8387 } 8388 8389 /// getTargetInsertSubreg - A convenience function for creating 8390 /// TargetOpcode::INSERT_SUBREG nodes. 8391 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8392 SDValue Operand, SDValue Subreg) { 8393 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8394 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 8395 VT, Operand, Subreg, SRIdxVal); 8396 return SDValue(Result, 0); 8397 } 8398 8399 /// getNodeIfExists - Get the specified node if it's already available, or 8400 /// else return NULL. 8401 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8402 ArrayRef<SDValue> Ops) { 8403 SDNodeFlags Flags; 8404 if (Inserter) 8405 Flags = Inserter->getFlags(); 8406 return getNodeIfExists(Opcode, VTList, Ops, Flags); 8407 } 8408 8409 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8410 ArrayRef<SDValue> Ops, 8411 const SDNodeFlags Flags) { 8412 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8413 FoldingSetNodeID ID; 8414 AddNodeIDNode(ID, Opcode, VTList, Ops); 8415 void *IP = nullptr; 8416 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 8417 E->intersectFlagsWith(Flags); 8418 return E; 8419 } 8420 } 8421 return nullptr; 8422 } 8423 8424 /// doesNodeExist - Check if a node exists without modifying its flags. 8425 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 8426 ArrayRef<SDValue> Ops) { 8427 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8428 FoldingSetNodeID ID; 8429 AddNodeIDNode(ID, Opcode, VTList, Ops); 8430 void *IP = nullptr; 8431 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 8432 return true; 8433 } 8434 return false; 8435 } 8436 8437 /// getDbgValue - Creates a SDDbgValue node. 8438 /// 8439 /// SDNode 8440 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 8441 SDNode *N, unsigned R, bool IsIndirect, 8442 const DebugLoc &DL, unsigned O) { 8443 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8444 "Expected inlined-at fields to agree"); 8445 return new (DbgInfo->getAlloc()) 8446 SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O); 8447 } 8448 8449 /// Constant 8450 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 8451 DIExpression *Expr, 8452 const Value *C, 8453 const DebugLoc &DL, unsigned O) { 8454 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8455 "Expected inlined-at fields to agree"); 8456 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O); 8457 } 8458 8459 /// FrameIndex 8460 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8461 DIExpression *Expr, unsigned FI, 8462 bool IsIndirect, 8463 const DebugLoc &DL, 8464 unsigned O) { 8465 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8466 "Expected inlined-at fields to agree"); 8467 return new (DbgInfo->getAlloc()) 8468 SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX); 8469 } 8470 8471 /// VReg 8472 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, 8473 DIExpression *Expr, 8474 unsigned VReg, bool IsIndirect, 8475 const DebugLoc &DL, unsigned O) { 8476 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8477 "Expected inlined-at fields to agree"); 8478 return new (DbgInfo->getAlloc()) 8479 SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG); 8480 } 8481 8482 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 8483 unsigned OffsetInBits, unsigned SizeInBits, 8484 bool InvalidateDbg) { 8485 SDNode *FromNode = From.getNode(); 8486 SDNode *ToNode = To.getNode(); 8487 assert(FromNode && ToNode && "Can't modify dbg values"); 8488 8489 // PR35338 8490 // TODO: assert(From != To && "Redundant dbg value transfer"); 8491 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 8492 if (From == To || FromNode == ToNode) 8493 return; 8494 8495 if (!FromNode->getHasDebugValue()) 8496 return; 8497 8498 SmallVector<SDDbgValue *, 2> ClonedDVs; 8499 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 8500 if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated()) 8501 continue; 8502 8503 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 8504 8505 // Just transfer the dbg value attached to From. 8506 if (Dbg->getResNo() != From.getResNo()) 8507 continue; 8508 8509 DIVariable *Var = Dbg->getVariable(); 8510 auto *Expr = Dbg->getExpression(); 8511 // If a fragment is requested, update the expression. 8512 if (SizeInBits) { 8513 // When splitting a larger (e.g., sign-extended) value whose 8514 // lower bits are described with an SDDbgValue, do not attempt 8515 // to transfer the SDDbgValue to the upper bits. 8516 if (auto FI = Expr->getFragmentInfo()) 8517 if (OffsetInBits + SizeInBits > FI->SizeInBits) 8518 continue; 8519 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 8520 SizeInBits); 8521 if (!Fragment) 8522 continue; 8523 Expr = *Fragment; 8524 } 8525 // Clone the SDDbgValue and move it to To. 8526 SDDbgValue *Clone = getDbgValue( 8527 Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(), Dbg->getDebugLoc(), 8528 std::max(ToNode->getIROrder(), Dbg->getOrder())); 8529 ClonedDVs.push_back(Clone); 8530 8531 if (InvalidateDbg) { 8532 // Invalidate value and indicate the SDDbgValue should not be emitted. 8533 Dbg->setIsInvalidated(); 8534 Dbg->setIsEmitted(); 8535 } 8536 } 8537 8538 for (SDDbgValue *Dbg : ClonedDVs) 8539 AddDbgValue(Dbg, ToNode, false); 8540 } 8541 8542 void SelectionDAG::salvageDebugInfo(SDNode &N) { 8543 if (!N.getHasDebugValue()) 8544 return; 8545 8546 SmallVector<SDDbgValue *, 2> ClonedDVs; 8547 for (auto DV : GetDbgValues(&N)) { 8548 if (DV->isInvalidated()) 8549 continue; 8550 switch (N.getOpcode()) { 8551 default: 8552 break; 8553 case ISD::ADD: 8554 SDValue N0 = N.getOperand(0); 8555 SDValue N1 = N.getOperand(1); 8556 if (!isConstantIntBuildVectorOrConstantInt(N0) && 8557 isConstantIntBuildVectorOrConstantInt(N1)) { 8558 uint64_t Offset = N.getConstantOperandVal(1); 8559 // Rewrite an ADD constant node into a DIExpression. Since we are 8560 // performing arithmetic to compute the variable's *value* in the 8561 // DIExpression, we need to mark the expression with a 8562 // DW_OP_stack_value. 8563 auto *DIExpr = DV->getExpression(); 8564 DIExpr = 8565 DIExpression::prepend(DIExpr, DIExpression::StackValue, Offset); 8566 SDDbgValue *Clone = 8567 getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(), 8568 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder()); 8569 ClonedDVs.push_back(Clone); 8570 DV->setIsInvalidated(); 8571 DV->setIsEmitted(); 8572 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 8573 N0.getNode()->dumprFull(this); 8574 dbgs() << " into " << *DIExpr << '\n'); 8575 } 8576 } 8577 } 8578 8579 for (SDDbgValue *Dbg : ClonedDVs) 8580 AddDbgValue(Dbg, Dbg->getSDNode(), false); 8581 } 8582 8583 /// Creates a SDDbgLabel node. 8584 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 8585 const DebugLoc &DL, unsigned O) { 8586 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 8587 "Expected inlined-at fields to agree"); 8588 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 8589 } 8590 8591 namespace { 8592 8593 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 8594 /// pointed to by a use iterator is deleted, increment the use iterator 8595 /// so that it doesn't dangle. 8596 /// 8597 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 8598 SDNode::use_iterator &UI; 8599 SDNode::use_iterator &UE; 8600 8601 void NodeDeleted(SDNode *N, SDNode *E) override { 8602 // Increment the iterator as needed. 8603 while (UI != UE && N == *UI) 8604 ++UI; 8605 } 8606 8607 public: 8608 RAUWUpdateListener(SelectionDAG &d, 8609 SDNode::use_iterator &ui, 8610 SDNode::use_iterator &ue) 8611 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 8612 }; 8613 8614 } // end anonymous namespace 8615 8616 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8617 /// This can cause recursive merging of nodes in the DAG. 8618 /// 8619 /// This version assumes From has a single result value. 8620 /// 8621 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 8622 SDNode *From = FromN.getNode(); 8623 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 8624 "Cannot replace with this method!"); 8625 assert(From != To.getNode() && "Cannot replace uses of with self"); 8626 8627 // Preserve Debug Values 8628 transferDbgValues(FromN, To); 8629 8630 // Iterate over all the existing uses of From. New uses will be added 8631 // to the beginning of the use list, which we avoid visiting. 8632 // This specifically avoids visiting uses of From that arise while the 8633 // replacement is happening, because any such uses would be the result 8634 // of CSE: If an existing node looks like From after one of its operands 8635 // is replaced by To, we don't want to replace of all its users with To 8636 // too. See PR3018 for more info. 8637 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8638 RAUWUpdateListener Listener(*this, UI, UE); 8639 while (UI != UE) { 8640 SDNode *User = *UI; 8641 8642 // This node is about to morph, remove its old self from the CSE maps. 8643 RemoveNodeFromCSEMaps(User); 8644 8645 // A user can appear in a use list multiple times, and when this 8646 // happens the uses are usually next to each other in the list. 8647 // To help reduce the number of CSE recomputations, process all 8648 // the uses of this user that we can find this way. 8649 do { 8650 SDUse &Use = UI.getUse(); 8651 ++UI; 8652 Use.set(To); 8653 if (To->isDivergent() != From->isDivergent()) 8654 updateDivergence(User); 8655 } while (UI != UE && *UI == User); 8656 // Now that we have modified User, add it back to the CSE maps. If it 8657 // already exists there, recursively merge the results together. 8658 AddModifiedNodeToCSEMaps(User); 8659 } 8660 8661 // If we just RAUW'd the root, take note. 8662 if (FromN == getRoot()) 8663 setRoot(To); 8664 } 8665 8666 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8667 /// This can cause recursive merging of nodes in the DAG. 8668 /// 8669 /// This version assumes that for each value of From, there is a 8670 /// corresponding value in To in the same position with the same type. 8671 /// 8672 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 8673 #ifndef NDEBUG 8674 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8675 assert((!From->hasAnyUseOfValue(i) || 8676 From->getValueType(i) == To->getValueType(i)) && 8677 "Cannot use this version of ReplaceAllUsesWith!"); 8678 #endif 8679 8680 // Handle the trivial case. 8681 if (From == To) 8682 return; 8683 8684 // Preserve Debug Info. Only do this if there's a use. 8685 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8686 if (From->hasAnyUseOfValue(i)) { 8687 assert((i < To->getNumValues()) && "Invalid To location"); 8688 transferDbgValues(SDValue(From, i), SDValue(To, i)); 8689 } 8690 8691 // Iterate over just the existing users of From. See the comments in 8692 // the ReplaceAllUsesWith above. 8693 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8694 RAUWUpdateListener Listener(*this, UI, UE); 8695 while (UI != UE) { 8696 SDNode *User = *UI; 8697 8698 // This node is about to morph, remove its old self from the CSE maps. 8699 RemoveNodeFromCSEMaps(User); 8700 8701 // A user can appear in a use list multiple times, and when this 8702 // happens the uses are usually next to each other in the list. 8703 // To help reduce the number of CSE recomputations, process all 8704 // the uses of this user that we can find this way. 8705 do { 8706 SDUse &Use = UI.getUse(); 8707 ++UI; 8708 Use.setNode(To); 8709 if (To->isDivergent() != From->isDivergent()) 8710 updateDivergence(User); 8711 } while (UI != UE && *UI == User); 8712 8713 // Now that we have modified User, add it back to the CSE maps. If it 8714 // already exists there, recursively merge the results together. 8715 AddModifiedNodeToCSEMaps(User); 8716 } 8717 8718 // If we just RAUW'd the root, take note. 8719 if (From == getRoot().getNode()) 8720 setRoot(SDValue(To, getRoot().getResNo())); 8721 } 8722 8723 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8724 /// This can cause recursive merging of nodes in the DAG. 8725 /// 8726 /// This version can replace From with any result values. To must match the 8727 /// number and types of values returned by From. 8728 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 8729 if (From->getNumValues() == 1) // Handle the simple case efficiently. 8730 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 8731 8732 // Preserve Debug Info. 8733 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8734 transferDbgValues(SDValue(From, i), To[i]); 8735 8736 // Iterate over just the existing users of From. See the comments in 8737 // the ReplaceAllUsesWith above. 8738 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8739 RAUWUpdateListener Listener(*this, UI, UE); 8740 while (UI != UE) { 8741 SDNode *User = *UI; 8742 8743 // This node is about to morph, remove its old self from the CSE maps. 8744 RemoveNodeFromCSEMaps(User); 8745 8746 // A user can appear in a use list multiple times, and when this happens the 8747 // uses are usually next to each other in the list. To help reduce the 8748 // number of CSE and divergence recomputations, process all the uses of this 8749 // user that we can find this way. 8750 bool To_IsDivergent = false; 8751 do { 8752 SDUse &Use = UI.getUse(); 8753 const SDValue &ToOp = To[Use.getResNo()]; 8754 ++UI; 8755 Use.set(ToOp); 8756 To_IsDivergent |= ToOp->isDivergent(); 8757 } while (UI != UE && *UI == User); 8758 8759 if (To_IsDivergent != From->isDivergent()) 8760 updateDivergence(User); 8761 8762 // Now that we have modified User, add it back to the CSE maps. If it 8763 // already exists there, recursively merge the results together. 8764 AddModifiedNodeToCSEMaps(User); 8765 } 8766 8767 // If we just RAUW'd the root, take note. 8768 if (From == getRoot().getNode()) 8769 setRoot(SDValue(To[getRoot().getResNo()])); 8770 } 8771 8772 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 8773 /// uses of other values produced by From.getNode() alone. The Deleted 8774 /// vector is handled the same way as for ReplaceAllUsesWith. 8775 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 8776 // Handle the really simple, really trivial case efficiently. 8777 if (From == To) return; 8778 8779 // Handle the simple, trivial, case efficiently. 8780 if (From.getNode()->getNumValues() == 1) { 8781 ReplaceAllUsesWith(From, To); 8782 return; 8783 } 8784 8785 // Preserve Debug Info. 8786 transferDbgValues(From, To); 8787 8788 // Iterate over just the existing users of From. See the comments in 8789 // the ReplaceAllUsesWith above. 8790 SDNode::use_iterator UI = From.getNode()->use_begin(), 8791 UE = From.getNode()->use_end(); 8792 RAUWUpdateListener Listener(*this, UI, UE); 8793 while (UI != UE) { 8794 SDNode *User = *UI; 8795 bool UserRemovedFromCSEMaps = false; 8796 8797 // A user can appear in a use list multiple times, and when this 8798 // happens the uses are usually next to each other in the list. 8799 // To help reduce the number of CSE recomputations, process all 8800 // the uses of this user that we can find this way. 8801 do { 8802 SDUse &Use = UI.getUse(); 8803 8804 // Skip uses of different values from the same node. 8805 if (Use.getResNo() != From.getResNo()) { 8806 ++UI; 8807 continue; 8808 } 8809 8810 // If this node hasn't been modified yet, it's still in the CSE maps, 8811 // so remove its old self from the CSE maps. 8812 if (!UserRemovedFromCSEMaps) { 8813 RemoveNodeFromCSEMaps(User); 8814 UserRemovedFromCSEMaps = true; 8815 } 8816 8817 ++UI; 8818 Use.set(To); 8819 if (To->isDivergent() != From->isDivergent()) 8820 updateDivergence(User); 8821 } while (UI != UE && *UI == User); 8822 // We are iterating over all uses of the From node, so if a use 8823 // doesn't use the specific value, no changes are made. 8824 if (!UserRemovedFromCSEMaps) 8825 continue; 8826 8827 // Now that we have modified User, add it back to the CSE maps. If it 8828 // already exists there, recursively merge the results together. 8829 AddModifiedNodeToCSEMaps(User); 8830 } 8831 8832 // If we just RAUW'd the root, take note. 8833 if (From == getRoot()) 8834 setRoot(To); 8835 } 8836 8837 namespace { 8838 8839 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 8840 /// to record information about a use. 8841 struct UseMemo { 8842 SDNode *User; 8843 unsigned Index; 8844 SDUse *Use; 8845 }; 8846 8847 /// operator< - Sort Memos by User. 8848 bool operator<(const UseMemo &L, const UseMemo &R) { 8849 return (intptr_t)L.User < (intptr_t)R.User; 8850 } 8851 8852 } // end anonymous namespace 8853 8854 bool SelectionDAG::calculateDivergence(SDNode *N) { 8855 if (TLI->isSDNodeAlwaysUniform(N)) { 8856 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 8857 "Conflicting divergence information!"); 8858 return false; 8859 } 8860 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 8861 return true; 8862 for (auto &Op : N->ops()) { 8863 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 8864 return true; 8865 } 8866 return false; 8867 } 8868 8869 void SelectionDAG::updateDivergence(SDNode *N) { 8870 SmallVector<SDNode *, 16> Worklist(1, N); 8871 do { 8872 N = Worklist.pop_back_val(); 8873 bool IsDivergent = calculateDivergence(N); 8874 if (N->SDNodeBits.IsDivergent != IsDivergent) { 8875 N->SDNodeBits.IsDivergent = IsDivergent; 8876 llvm::append_range(Worklist, N->uses()); 8877 } 8878 } while (!Worklist.empty()); 8879 } 8880 8881 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 8882 DenseMap<SDNode *, unsigned> Degree; 8883 Order.reserve(AllNodes.size()); 8884 for (auto &N : allnodes()) { 8885 unsigned NOps = N.getNumOperands(); 8886 Degree[&N] = NOps; 8887 if (0 == NOps) 8888 Order.push_back(&N); 8889 } 8890 for (size_t I = 0; I != Order.size(); ++I) { 8891 SDNode *N = Order[I]; 8892 for (auto U : N->uses()) { 8893 unsigned &UnsortedOps = Degree[U]; 8894 if (0 == --UnsortedOps) 8895 Order.push_back(U); 8896 } 8897 } 8898 } 8899 8900 #ifndef NDEBUG 8901 void SelectionDAG::VerifyDAGDiverence() { 8902 std::vector<SDNode *> TopoOrder; 8903 CreateTopologicalOrder(TopoOrder); 8904 for (auto *N : TopoOrder) { 8905 assert(calculateDivergence(N) == N->isDivergent() && 8906 "Divergence bit inconsistency detected"); 8907 } 8908 } 8909 #endif 8910 8911 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 8912 /// uses of other values produced by From.getNode() alone. The same value 8913 /// may appear in both the From and To list. The Deleted vector is 8914 /// handled the same way as for ReplaceAllUsesWith. 8915 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 8916 const SDValue *To, 8917 unsigned Num){ 8918 // Handle the simple, trivial case efficiently. 8919 if (Num == 1) 8920 return ReplaceAllUsesOfValueWith(*From, *To); 8921 8922 transferDbgValues(*From, *To); 8923 8924 // Read up all the uses and make records of them. This helps 8925 // processing new uses that are introduced during the 8926 // replacement process. 8927 SmallVector<UseMemo, 4> Uses; 8928 for (unsigned i = 0; i != Num; ++i) { 8929 unsigned FromResNo = From[i].getResNo(); 8930 SDNode *FromNode = From[i].getNode(); 8931 for (SDNode::use_iterator UI = FromNode->use_begin(), 8932 E = FromNode->use_end(); UI != E; ++UI) { 8933 SDUse &Use = UI.getUse(); 8934 if (Use.getResNo() == FromResNo) { 8935 UseMemo Memo = { *UI, i, &Use }; 8936 Uses.push_back(Memo); 8937 } 8938 } 8939 } 8940 8941 // Sort the uses, so that all the uses from a given User are together. 8942 llvm::sort(Uses); 8943 8944 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 8945 UseIndex != UseIndexEnd; ) { 8946 // We know that this user uses some value of From. If it is the right 8947 // value, update it. 8948 SDNode *User = Uses[UseIndex].User; 8949 8950 // This node is about to morph, remove its old self from the CSE maps. 8951 RemoveNodeFromCSEMaps(User); 8952 8953 // The Uses array is sorted, so all the uses for a given User 8954 // are next to each other in the list. 8955 // To help reduce the number of CSE recomputations, process all 8956 // the uses of this user that we can find this way. 8957 do { 8958 unsigned i = Uses[UseIndex].Index; 8959 SDUse &Use = *Uses[UseIndex].Use; 8960 ++UseIndex; 8961 8962 Use.set(To[i]); 8963 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 8964 8965 // Now that we have modified User, add it back to the CSE maps. If it 8966 // already exists there, recursively merge the results together. 8967 AddModifiedNodeToCSEMaps(User); 8968 } 8969 } 8970 8971 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 8972 /// based on their topological order. It returns the maximum id and a vector 8973 /// of the SDNodes* in assigned order by reference. 8974 unsigned SelectionDAG::AssignTopologicalOrder() { 8975 unsigned DAGSize = 0; 8976 8977 // SortedPos tracks the progress of the algorithm. Nodes before it are 8978 // sorted, nodes after it are unsorted. When the algorithm completes 8979 // it is at the end of the list. 8980 allnodes_iterator SortedPos = allnodes_begin(); 8981 8982 // Visit all the nodes. Move nodes with no operands to the front of 8983 // the list immediately. Annotate nodes that do have operands with their 8984 // operand count. Before we do this, the Node Id fields of the nodes 8985 // may contain arbitrary values. After, the Node Id fields for nodes 8986 // before SortedPos will contain the topological sort index, and the 8987 // Node Id fields for nodes At SortedPos and after will contain the 8988 // count of outstanding operands. 8989 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 8990 SDNode *N = &*I++; 8991 checkForCycles(N, this); 8992 unsigned Degree = N->getNumOperands(); 8993 if (Degree == 0) { 8994 // A node with no uses, add it to the result array immediately. 8995 N->setNodeId(DAGSize++); 8996 allnodes_iterator Q(N); 8997 if (Q != SortedPos) 8998 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 8999 assert(SortedPos != AllNodes.end() && "Overran node list"); 9000 ++SortedPos; 9001 } else { 9002 // Temporarily use the Node Id as scratch space for the degree count. 9003 N->setNodeId(Degree); 9004 } 9005 } 9006 9007 // Visit all the nodes. As we iterate, move nodes into sorted order, 9008 // such that by the time the end is reached all nodes will be sorted. 9009 for (SDNode &Node : allnodes()) { 9010 SDNode *N = &Node; 9011 checkForCycles(N, this); 9012 // N is in sorted position, so all its uses have one less operand 9013 // that needs to be sorted. 9014 for (SDNode *P : N->uses()) { 9015 unsigned Degree = P->getNodeId(); 9016 assert(Degree != 0 && "Invalid node degree"); 9017 --Degree; 9018 if (Degree == 0) { 9019 // All of P's operands are sorted, so P may sorted now. 9020 P->setNodeId(DAGSize++); 9021 if (P->getIterator() != SortedPos) 9022 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9023 assert(SortedPos != AllNodes.end() && "Overran node list"); 9024 ++SortedPos; 9025 } else { 9026 // Update P's outstanding operand count. 9027 P->setNodeId(Degree); 9028 } 9029 } 9030 if (Node.getIterator() == SortedPos) { 9031 #ifndef NDEBUG 9032 allnodes_iterator I(N); 9033 SDNode *S = &*++I; 9034 dbgs() << "Overran sorted position:\n"; 9035 S->dumprFull(this); dbgs() << "\n"; 9036 dbgs() << "Checking if this is due to cycles\n"; 9037 checkForCycles(this, true); 9038 #endif 9039 llvm_unreachable(nullptr); 9040 } 9041 } 9042 9043 assert(SortedPos == AllNodes.end() && 9044 "Topological sort incomplete!"); 9045 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9046 "First node in topological sort is not the entry token!"); 9047 assert(AllNodes.front().getNodeId() == 0 && 9048 "First node in topological sort has non-zero id!"); 9049 assert(AllNodes.front().getNumOperands() == 0 && 9050 "First node in topological sort has operands!"); 9051 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9052 "Last node in topologic sort has unexpected id!"); 9053 assert(AllNodes.back().use_empty() && 9054 "Last node in topologic sort has users!"); 9055 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9056 return DAGSize; 9057 } 9058 9059 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9060 /// value is produced by SD. 9061 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) { 9062 if (SD) { 9063 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9064 SD->setHasDebugValue(true); 9065 } 9066 DbgInfo->add(DB, SD, isParameter); 9067 } 9068 9069 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { 9070 DbgInfo->add(DB); 9071 } 9072 9073 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9074 SDValue NewMemOpChain) { 9075 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9076 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9077 // The new memory operation must have the same position as the old load in 9078 // terms of memory dependency. Create a TokenFactor for the old load and new 9079 // memory operation and update uses of the old load's output chain to use that 9080 // TokenFactor. 9081 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9082 return NewMemOpChain; 9083 9084 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9085 OldChain, NewMemOpChain); 9086 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9087 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9088 return TokenFactor; 9089 } 9090 9091 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9092 SDValue NewMemOp) { 9093 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9094 SDValue OldChain = SDValue(OldLoad, 1); 9095 SDValue NewMemOpChain = NewMemOp.getValue(1); 9096 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9097 } 9098 9099 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9100 Function **OutFunction) { 9101 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9102 9103 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9104 auto *Module = MF->getFunction().getParent(); 9105 auto *Function = Module->getFunction(Symbol); 9106 9107 if (OutFunction != nullptr) 9108 *OutFunction = Function; 9109 9110 if (Function != nullptr) { 9111 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9112 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9113 } 9114 9115 std::string ErrorStr; 9116 raw_string_ostream ErrorFormatter(ErrorStr); 9117 9118 ErrorFormatter << "Undefined external symbol "; 9119 ErrorFormatter << '"' << Symbol << '"'; 9120 ErrorFormatter.flush(); 9121 9122 report_fatal_error(ErrorStr); 9123 } 9124 9125 //===----------------------------------------------------------------------===// 9126 // SDNode Class 9127 //===----------------------------------------------------------------------===// 9128 9129 bool llvm::isNullConstant(SDValue V) { 9130 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9131 return Const != nullptr && Const->isNullValue(); 9132 } 9133 9134 bool llvm::isNullFPConstant(SDValue V) { 9135 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9136 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9137 } 9138 9139 bool llvm::isAllOnesConstant(SDValue V) { 9140 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9141 return Const != nullptr && Const->isAllOnesValue(); 9142 } 9143 9144 bool llvm::isOneConstant(SDValue V) { 9145 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9146 return Const != nullptr && Const->isOne(); 9147 } 9148 9149 SDValue llvm::peekThroughBitcasts(SDValue V) { 9150 while (V.getOpcode() == ISD::BITCAST) 9151 V = V.getOperand(0); 9152 return V; 9153 } 9154 9155 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9156 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9157 V = V.getOperand(0); 9158 return V; 9159 } 9160 9161 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9162 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9163 V = V.getOperand(0); 9164 return V; 9165 } 9166 9167 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9168 if (V.getOpcode() != ISD::XOR) 9169 return false; 9170 V = peekThroughBitcasts(V.getOperand(1)); 9171 unsigned NumBits = V.getScalarValueSizeInBits(); 9172 ConstantSDNode *C = 9173 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 9174 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 9175 } 9176 9177 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 9178 bool AllowTruncation) { 9179 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9180 return CN; 9181 9182 // SplatVectors can truncate their operands. Ignore that case here unless 9183 // AllowTruncation is set. 9184 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 9185 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 9186 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9187 EVT CVT = CN->getValueType(0); 9188 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 9189 if (AllowTruncation || CVT == VecEltVT) 9190 return CN; 9191 } 9192 } 9193 9194 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9195 BitVector UndefElements; 9196 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 9197 9198 // BuildVectors can truncate their operands. Ignore that case here unless 9199 // AllowTruncation is set. 9200 if (CN && (UndefElements.none() || AllowUndefs)) { 9201 EVT CVT = CN->getValueType(0); 9202 EVT NSVT = N.getValueType().getScalarType(); 9203 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9204 if (AllowTruncation || (CVT == NSVT)) 9205 return CN; 9206 } 9207 } 9208 9209 return nullptr; 9210 } 9211 9212 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 9213 bool AllowUndefs, 9214 bool AllowTruncation) { 9215 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9216 return CN; 9217 9218 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9219 BitVector UndefElements; 9220 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 9221 9222 // BuildVectors can truncate their operands. Ignore that case here unless 9223 // AllowTruncation is set. 9224 if (CN && (UndefElements.none() || AllowUndefs)) { 9225 EVT CVT = CN->getValueType(0); 9226 EVT NSVT = N.getValueType().getScalarType(); 9227 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9228 if (AllowTruncation || (CVT == NSVT)) 9229 return CN; 9230 } 9231 } 9232 9233 return nullptr; 9234 } 9235 9236 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 9237 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9238 return CN; 9239 9240 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9241 BitVector UndefElements; 9242 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 9243 if (CN && (UndefElements.none() || AllowUndefs)) 9244 return CN; 9245 } 9246 9247 if (N.getOpcode() == ISD::SPLAT_VECTOR) 9248 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 9249 return CN; 9250 9251 return nullptr; 9252 } 9253 9254 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 9255 const APInt &DemandedElts, 9256 bool AllowUndefs) { 9257 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9258 return CN; 9259 9260 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9261 BitVector UndefElements; 9262 ConstantFPSDNode *CN = 9263 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 9264 if (CN && (UndefElements.none() || AllowUndefs)) 9265 return CN; 9266 } 9267 9268 return nullptr; 9269 } 9270 9271 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 9272 // TODO: may want to use peekThroughBitcast() here. 9273 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9274 return C && C->isNullValue(); 9275 } 9276 9277 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 9278 // TODO: may want to use peekThroughBitcast() here. 9279 unsigned BitWidth = N.getScalarValueSizeInBits(); 9280 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9281 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 9282 } 9283 9284 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 9285 N = peekThroughBitcasts(N); 9286 unsigned BitWidth = N.getScalarValueSizeInBits(); 9287 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9288 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth; 9289 } 9290 9291 HandleSDNode::~HandleSDNode() { 9292 DropOperands(); 9293 } 9294 9295 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 9296 const DebugLoc &DL, 9297 const GlobalValue *GA, EVT VT, 9298 int64_t o, unsigned TF) 9299 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 9300 TheGlobal = GA; 9301 } 9302 9303 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 9304 EVT VT, unsigned SrcAS, 9305 unsigned DestAS) 9306 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 9307 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 9308 9309 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 9310 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 9311 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 9312 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 9313 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 9314 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 9315 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 9316 9317 // We check here that the size of the memory operand fits within the size of 9318 // the MMO. This is because the MMO might indicate only a possible address 9319 // range instead of specifying the affected memory addresses precisely. 9320 // TODO: Make MachineMemOperands aware of scalable vectors. 9321 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 9322 "Size mismatch!"); 9323 } 9324 9325 /// Profile - Gather unique data for the node. 9326 /// 9327 void SDNode::Profile(FoldingSetNodeID &ID) const { 9328 AddNodeIDNode(ID, this); 9329 } 9330 9331 namespace { 9332 9333 struct EVTArray { 9334 std::vector<EVT> VTs; 9335 9336 EVTArray() { 9337 VTs.reserve(MVT::LAST_VALUETYPE); 9338 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 9339 VTs.push_back(MVT((MVT::SimpleValueType)i)); 9340 } 9341 }; 9342 9343 } // end anonymous namespace 9344 9345 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 9346 static ManagedStatic<EVTArray> SimpleVTArray; 9347 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 9348 9349 /// getValueTypeList - Return a pointer to the specified value type. 9350 /// 9351 const EVT *SDNode::getValueTypeList(EVT VT) { 9352 if (VT.isExtended()) { 9353 sys::SmartScopedLock<true> Lock(*VTMutex); 9354 return &(*EVTs->insert(VT).first); 9355 } else { 9356 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 9357 "Value type out of range!"); 9358 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 9359 } 9360 } 9361 9362 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 9363 /// indicated value. This method ignores uses of other values defined by this 9364 /// operation. 9365 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 9366 assert(Value < getNumValues() && "Bad value!"); 9367 9368 // TODO: Only iterate over uses of a given value of the node 9369 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 9370 if (UI.getUse().getResNo() == Value) { 9371 if (NUses == 0) 9372 return false; 9373 --NUses; 9374 } 9375 } 9376 9377 // Found exactly the right number of uses? 9378 return NUses == 0; 9379 } 9380 9381 /// hasAnyUseOfValue - Return true if there are any use of the indicated 9382 /// value. This method ignores uses of other values defined by this operation. 9383 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 9384 assert(Value < getNumValues() && "Bad value!"); 9385 9386 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 9387 if (UI.getUse().getResNo() == Value) 9388 return true; 9389 9390 return false; 9391 } 9392 9393 /// isOnlyUserOf - Return true if this node is the only use of N. 9394 bool SDNode::isOnlyUserOf(const SDNode *N) const { 9395 bool Seen = false; 9396 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9397 SDNode *User = *I; 9398 if (User == this) 9399 Seen = true; 9400 else 9401 return false; 9402 } 9403 9404 return Seen; 9405 } 9406 9407 /// Return true if the only users of N are contained in Nodes. 9408 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 9409 bool Seen = false; 9410 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9411 SDNode *User = *I; 9412 if (llvm::is_contained(Nodes, User)) 9413 Seen = true; 9414 else 9415 return false; 9416 } 9417 9418 return Seen; 9419 } 9420 9421 /// isOperand - Return true if this node is an operand of N. 9422 bool SDValue::isOperandOf(const SDNode *N) const { 9423 return is_contained(N->op_values(), *this); 9424 } 9425 9426 bool SDNode::isOperandOf(const SDNode *N) const { 9427 return any_of(N->op_values(), 9428 [this](SDValue Op) { return this == Op.getNode(); }); 9429 } 9430 9431 /// reachesChainWithoutSideEffects - Return true if this operand (which must 9432 /// be a chain) reaches the specified operand without crossing any 9433 /// side-effecting instructions on any chain path. In practice, this looks 9434 /// through token factors and non-volatile loads. In order to remain efficient, 9435 /// this only looks a couple of nodes in, it does not do an exhaustive search. 9436 /// 9437 /// Note that we only need to examine chains when we're searching for 9438 /// side-effects; SelectionDAG requires that all side-effects are represented 9439 /// by chains, even if another operand would force a specific ordering. This 9440 /// constraint is necessary to allow transformations like splitting loads. 9441 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 9442 unsigned Depth) const { 9443 if (*this == Dest) return true; 9444 9445 // Don't search too deeply, we just want to be able to see through 9446 // TokenFactor's etc. 9447 if (Depth == 0) return false; 9448 9449 // If this is a token factor, all inputs to the TF happen in parallel. 9450 if (getOpcode() == ISD::TokenFactor) { 9451 // First, try a shallow search. 9452 if (is_contained((*this)->ops(), Dest)) { 9453 // We found the chain we want as an operand of this TokenFactor. 9454 // Essentially, we reach the chain without side-effects if we could 9455 // serialize the TokenFactor into a simple chain of operations with 9456 // Dest as the last operation. This is automatically true if the 9457 // chain has one use: there are no other ordering constraints. 9458 // If the chain has more than one use, we give up: some other 9459 // use of Dest might force a side-effect between Dest and the current 9460 // node. 9461 if (Dest.hasOneUse()) 9462 return true; 9463 } 9464 // Next, try a deep search: check whether every operand of the TokenFactor 9465 // reaches Dest. 9466 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 9467 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 9468 }); 9469 } 9470 9471 // Loads don't have side effects, look through them. 9472 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 9473 if (Ld->isUnordered()) 9474 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 9475 } 9476 return false; 9477 } 9478 9479 bool SDNode::hasPredecessor(const SDNode *N) const { 9480 SmallPtrSet<const SDNode *, 32> Visited; 9481 SmallVector<const SDNode *, 16> Worklist; 9482 Worklist.push_back(this); 9483 return hasPredecessorHelper(N, Visited, Worklist); 9484 } 9485 9486 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 9487 this->Flags.intersectWith(Flags); 9488 } 9489 9490 SDValue 9491 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 9492 ArrayRef<ISD::NodeType> CandidateBinOps, 9493 bool AllowPartials) { 9494 // The pattern must end in an extract from index 0. 9495 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9496 !isNullConstant(Extract->getOperand(1))) 9497 return SDValue(); 9498 9499 // Match against one of the candidate binary ops. 9500 SDValue Op = Extract->getOperand(0); 9501 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 9502 return Op.getOpcode() == unsigned(BinOp); 9503 })) 9504 return SDValue(); 9505 9506 // Floating-point reductions may require relaxed constraints on the final step 9507 // of the reduction because they may reorder intermediate operations. 9508 unsigned CandidateBinOp = Op.getOpcode(); 9509 if (Op.getValueType().isFloatingPoint()) { 9510 SDNodeFlags Flags = Op->getFlags(); 9511 switch (CandidateBinOp) { 9512 case ISD::FADD: 9513 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 9514 return SDValue(); 9515 break; 9516 default: 9517 llvm_unreachable("Unhandled FP opcode for binop reduction"); 9518 } 9519 } 9520 9521 // Matching failed - attempt to see if we did enough stages that a partial 9522 // reduction from a subvector is possible. 9523 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 9524 if (!AllowPartials || !Op) 9525 return SDValue(); 9526 EVT OpVT = Op.getValueType(); 9527 EVT OpSVT = OpVT.getScalarType(); 9528 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 9529 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 9530 return SDValue(); 9531 BinOp = (ISD::NodeType)CandidateBinOp; 9532 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 9533 getVectorIdxConstant(0, SDLoc(Op))); 9534 }; 9535 9536 // At each stage, we're looking for something that looks like: 9537 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 9538 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 9539 // i32 undef, i32 undef, i32 undef, i32 undef> 9540 // %a = binop <8 x i32> %op, %s 9541 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 9542 // we expect something like: 9543 // <4,5,6,7,u,u,u,u> 9544 // <2,3,u,u,u,u,u,u> 9545 // <1,u,u,u,u,u,u,u> 9546 // While a partial reduction match would be: 9547 // <2,3,u,u,u,u,u,u> 9548 // <1,u,u,u,u,u,u,u> 9549 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 9550 SDValue PrevOp; 9551 for (unsigned i = 0; i < Stages; ++i) { 9552 unsigned MaskEnd = (1 << i); 9553 9554 if (Op.getOpcode() != CandidateBinOp) 9555 return PartialReduction(PrevOp, MaskEnd); 9556 9557 SDValue Op0 = Op.getOperand(0); 9558 SDValue Op1 = Op.getOperand(1); 9559 9560 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 9561 if (Shuffle) { 9562 Op = Op1; 9563 } else { 9564 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 9565 Op = Op0; 9566 } 9567 9568 // The first operand of the shuffle should be the same as the other operand 9569 // of the binop. 9570 if (!Shuffle || Shuffle->getOperand(0) != Op) 9571 return PartialReduction(PrevOp, MaskEnd); 9572 9573 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 9574 for (int Index = 0; Index < (int)MaskEnd; ++Index) 9575 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 9576 return PartialReduction(PrevOp, MaskEnd); 9577 9578 PrevOp = Op; 9579 } 9580 9581 // Handle subvector reductions, which tend to appear after the shuffle 9582 // reduction stages. 9583 while (Op.getOpcode() == CandidateBinOp) { 9584 unsigned NumElts = Op.getValueType().getVectorNumElements(); 9585 SDValue Op0 = Op.getOperand(0); 9586 SDValue Op1 = Op.getOperand(1); 9587 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9588 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9589 Op0.getOperand(0) != Op1.getOperand(0)) 9590 break; 9591 SDValue Src = Op0.getOperand(0); 9592 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 9593 if (NumSrcElts != (2 * NumElts)) 9594 break; 9595 if (!(Op0.getConstantOperandAPInt(1) == 0 && 9596 Op1.getConstantOperandAPInt(1) == NumElts) && 9597 !(Op1.getConstantOperandAPInt(1) == 0 && 9598 Op0.getConstantOperandAPInt(1) == NumElts)) 9599 break; 9600 Op = Src; 9601 } 9602 9603 BinOp = (ISD::NodeType)CandidateBinOp; 9604 return Op; 9605 } 9606 9607 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 9608 assert(N->getNumValues() == 1 && 9609 "Can't unroll a vector with multiple results!"); 9610 9611 EVT VT = N->getValueType(0); 9612 unsigned NE = VT.getVectorNumElements(); 9613 EVT EltVT = VT.getVectorElementType(); 9614 SDLoc dl(N); 9615 9616 SmallVector<SDValue, 8> Scalars; 9617 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 9618 9619 // If ResNE is 0, fully unroll the vector op. 9620 if (ResNE == 0) 9621 ResNE = NE; 9622 else if (NE > ResNE) 9623 NE = ResNE; 9624 9625 unsigned i; 9626 for (i= 0; i != NE; ++i) { 9627 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 9628 SDValue Operand = N->getOperand(j); 9629 EVT OperandVT = Operand.getValueType(); 9630 if (OperandVT.isVector()) { 9631 // A vector operand; extract a single element. 9632 EVT OperandEltVT = OperandVT.getVectorElementType(); 9633 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 9634 Operand, getVectorIdxConstant(i, dl)); 9635 } else { 9636 // A scalar operand; just use it as is. 9637 Operands[j] = Operand; 9638 } 9639 } 9640 9641 switch (N->getOpcode()) { 9642 default: { 9643 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 9644 N->getFlags())); 9645 break; 9646 } 9647 case ISD::VSELECT: 9648 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 9649 break; 9650 case ISD::SHL: 9651 case ISD::SRA: 9652 case ISD::SRL: 9653 case ISD::ROTL: 9654 case ISD::ROTR: 9655 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 9656 getShiftAmountOperand(Operands[0].getValueType(), 9657 Operands[1]))); 9658 break; 9659 case ISD::SIGN_EXTEND_INREG: { 9660 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 9661 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 9662 Operands[0], 9663 getValueType(ExtVT))); 9664 } 9665 } 9666 } 9667 9668 for (; i < ResNE; ++i) 9669 Scalars.push_back(getUNDEF(EltVT)); 9670 9671 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 9672 return getBuildVector(VecVT, dl, Scalars); 9673 } 9674 9675 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 9676 SDNode *N, unsigned ResNE) { 9677 unsigned Opcode = N->getOpcode(); 9678 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 9679 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 9680 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 9681 "Expected an overflow opcode"); 9682 9683 EVT ResVT = N->getValueType(0); 9684 EVT OvVT = N->getValueType(1); 9685 EVT ResEltVT = ResVT.getVectorElementType(); 9686 EVT OvEltVT = OvVT.getVectorElementType(); 9687 SDLoc dl(N); 9688 9689 // If ResNE is 0, fully unroll the vector op. 9690 unsigned NE = ResVT.getVectorNumElements(); 9691 if (ResNE == 0) 9692 ResNE = NE; 9693 else if (NE > ResNE) 9694 NE = ResNE; 9695 9696 SmallVector<SDValue, 8> LHSScalars; 9697 SmallVector<SDValue, 8> RHSScalars; 9698 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 9699 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 9700 9701 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 9702 SDVTList VTs = getVTList(ResEltVT, SVT); 9703 SmallVector<SDValue, 8> ResScalars; 9704 SmallVector<SDValue, 8> OvScalars; 9705 for (unsigned i = 0; i < NE; ++i) { 9706 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 9707 SDValue Ov = 9708 getSelect(dl, OvEltVT, Res.getValue(1), 9709 getBoolConstant(true, dl, OvEltVT, ResVT), 9710 getConstant(0, dl, OvEltVT)); 9711 9712 ResScalars.push_back(Res); 9713 OvScalars.push_back(Ov); 9714 } 9715 9716 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 9717 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 9718 9719 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 9720 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 9721 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 9722 getBuildVector(NewOvVT, dl, OvScalars)); 9723 } 9724 9725 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 9726 LoadSDNode *Base, 9727 unsigned Bytes, 9728 int Dist) const { 9729 if (LD->isVolatile() || Base->isVolatile()) 9730 return false; 9731 // TODO: probably too restrictive for atomics, revisit 9732 if (!LD->isSimple()) 9733 return false; 9734 if (LD->isIndexed() || Base->isIndexed()) 9735 return false; 9736 if (LD->getChain() != Base->getChain()) 9737 return false; 9738 EVT VT = LD->getValueType(0); 9739 if (VT.getSizeInBits() / 8 != Bytes) 9740 return false; 9741 9742 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 9743 auto LocDecomp = BaseIndexOffset::match(LD, *this); 9744 9745 int64_t Offset = 0; 9746 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 9747 return (Dist * Bytes == Offset); 9748 return false; 9749 } 9750 9751 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 9752 /// if it cannot be inferred. 9753 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 9754 // If this is a GlobalAddress + cst, return the alignment. 9755 const GlobalValue *GV = nullptr; 9756 int64_t GVOffset = 0; 9757 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 9758 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 9759 KnownBits Known(PtrWidth); 9760 llvm::computeKnownBits(GV, Known, getDataLayout()); 9761 unsigned AlignBits = Known.countMinTrailingZeros(); 9762 if (AlignBits) 9763 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 9764 } 9765 9766 // If this is a direct reference to a stack slot, use information about the 9767 // stack slot's alignment. 9768 int FrameIdx = INT_MIN; 9769 int64_t FrameOffset = 0; 9770 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 9771 FrameIdx = FI->getIndex(); 9772 } else if (isBaseWithConstantOffset(Ptr) && 9773 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 9774 // Handle FI+Cst 9775 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 9776 FrameOffset = Ptr.getConstantOperandVal(1); 9777 } 9778 9779 if (FrameIdx != INT_MIN) { 9780 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 9781 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 9782 } 9783 9784 return None; 9785 } 9786 9787 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 9788 /// which is split (or expanded) into two not necessarily identical pieces. 9789 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 9790 // Currently all types are split in half. 9791 EVT LoVT, HiVT; 9792 if (!VT.isVector()) 9793 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 9794 else 9795 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 9796 9797 return std::make_pair(LoVT, HiVT); 9798 } 9799 9800 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 9801 /// type, dependent on an enveloping VT that has been split into two identical 9802 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 9803 std::pair<EVT, EVT> 9804 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 9805 bool *HiIsEmpty) const { 9806 EVT EltTp = VT.getVectorElementType(); 9807 // Examples: 9808 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 9809 // custom VL=9 with enveloping VL=8/8 yields 8/1 9810 // custom VL=10 with enveloping VL=8/8 yields 8/2 9811 // etc. 9812 ElementCount VTNumElts = VT.getVectorElementCount(); 9813 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 9814 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 9815 "Mixing fixed width and scalable vectors when enveloping a type"); 9816 EVT LoVT, HiVT; 9817 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 9818 LoVT = EnvVT; 9819 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 9820 *HiIsEmpty = false; 9821 } else { 9822 // Flag that hi type has zero storage size, but return split envelop type 9823 // (this would be easier if vector types with zero elements were allowed). 9824 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 9825 HiVT = EnvVT; 9826 *HiIsEmpty = true; 9827 } 9828 return std::make_pair(LoVT, HiVT); 9829 } 9830 9831 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 9832 /// low/high part. 9833 std::pair<SDValue, SDValue> 9834 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 9835 const EVT &HiVT) { 9836 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 9837 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 9838 "Splitting vector with an invalid mixture of fixed and scalable " 9839 "vector types"); 9840 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 9841 N.getValueType().getVectorMinNumElements() && 9842 "More vector elements requested than available!"); 9843 SDValue Lo, Hi; 9844 Lo = 9845 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 9846 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 9847 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 9848 // IDX with the runtime scaling factor of the result vector type. For 9849 // fixed-width result vectors, that runtime scaling factor is 1. 9850 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 9851 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 9852 return std::make_pair(Lo, Hi); 9853 } 9854 9855 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 9856 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 9857 EVT VT = N.getValueType(); 9858 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 9859 NextPowerOf2(VT.getVectorNumElements())); 9860 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 9861 getVectorIdxConstant(0, DL)); 9862 } 9863 9864 void SelectionDAG::ExtractVectorElements(SDValue Op, 9865 SmallVectorImpl<SDValue> &Args, 9866 unsigned Start, unsigned Count, 9867 EVT EltVT) { 9868 EVT VT = Op.getValueType(); 9869 if (Count == 0) 9870 Count = VT.getVectorNumElements(); 9871 if (EltVT == EVT()) 9872 EltVT = VT.getVectorElementType(); 9873 SDLoc SL(Op); 9874 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 9875 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 9876 getVectorIdxConstant(i, SL))); 9877 } 9878 } 9879 9880 // getAddressSpace - Return the address space this GlobalAddress belongs to. 9881 unsigned GlobalAddressSDNode::getAddressSpace() const { 9882 return getGlobal()->getType()->getAddressSpace(); 9883 } 9884 9885 Type *ConstantPoolSDNode::getType() const { 9886 if (isMachineConstantPoolEntry()) 9887 return Val.MachineCPVal->getType(); 9888 return Val.ConstVal->getType(); 9889 } 9890 9891 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 9892 unsigned &SplatBitSize, 9893 bool &HasAnyUndefs, 9894 unsigned MinSplatBits, 9895 bool IsBigEndian) const { 9896 EVT VT = getValueType(0); 9897 assert(VT.isVector() && "Expected a vector type"); 9898 unsigned VecWidth = VT.getSizeInBits(); 9899 if (MinSplatBits > VecWidth) 9900 return false; 9901 9902 // FIXME: The widths are based on this node's type, but build vectors can 9903 // truncate their operands. 9904 SplatValue = APInt(VecWidth, 0); 9905 SplatUndef = APInt(VecWidth, 0); 9906 9907 // Get the bits. Bits with undefined values (when the corresponding element 9908 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 9909 // in SplatValue. If any of the values are not constant, give up and return 9910 // false. 9911 unsigned int NumOps = getNumOperands(); 9912 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 9913 unsigned EltWidth = VT.getScalarSizeInBits(); 9914 9915 for (unsigned j = 0; j < NumOps; ++j) { 9916 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 9917 SDValue OpVal = getOperand(i); 9918 unsigned BitPos = j * EltWidth; 9919 9920 if (OpVal.isUndef()) 9921 SplatUndef.setBits(BitPos, BitPos + EltWidth); 9922 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 9923 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 9924 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 9925 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 9926 else 9927 return false; 9928 } 9929 9930 // The build_vector is all constants or undefs. Find the smallest element 9931 // size that splats the vector. 9932 HasAnyUndefs = (SplatUndef != 0); 9933 9934 // FIXME: This does not work for vectors with elements less than 8 bits. 9935 while (VecWidth > 8) { 9936 unsigned HalfSize = VecWidth / 2; 9937 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 9938 APInt LowValue = SplatValue.trunc(HalfSize); 9939 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 9940 APInt LowUndef = SplatUndef.trunc(HalfSize); 9941 9942 // If the two halves do not match (ignoring undef bits), stop here. 9943 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 9944 MinSplatBits > HalfSize) 9945 break; 9946 9947 SplatValue = HighValue | LowValue; 9948 SplatUndef = HighUndef & LowUndef; 9949 9950 VecWidth = HalfSize; 9951 } 9952 9953 SplatBitSize = VecWidth; 9954 return true; 9955 } 9956 9957 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 9958 BitVector *UndefElements) const { 9959 unsigned NumOps = getNumOperands(); 9960 if (UndefElements) { 9961 UndefElements->clear(); 9962 UndefElements->resize(NumOps); 9963 } 9964 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 9965 if (!DemandedElts) 9966 return SDValue(); 9967 SDValue Splatted; 9968 for (unsigned i = 0; i != NumOps; ++i) { 9969 if (!DemandedElts[i]) 9970 continue; 9971 SDValue Op = getOperand(i); 9972 if (Op.isUndef()) { 9973 if (UndefElements) 9974 (*UndefElements)[i] = true; 9975 } else if (!Splatted) { 9976 Splatted = Op; 9977 } else if (Splatted != Op) { 9978 return SDValue(); 9979 } 9980 } 9981 9982 if (!Splatted) { 9983 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 9984 assert(getOperand(FirstDemandedIdx).isUndef() && 9985 "Can only have a splat without a constant for all undefs."); 9986 return getOperand(FirstDemandedIdx); 9987 } 9988 9989 return Splatted; 9990 } 9991 9992 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 9993 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 9994 return getSplatValue(DemandedElts, UndefElements); 9995 } 9996 9997 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 9998 SmallVectorImpl<SDValue> &Sequence, 9999 BitVector *UndefElements) const { 10000 unsigned NumOps = getNumOperands(); 10001 Sequence.clear(); 10002 if (UndefElements) { 10003 UndefElements->clear(); 10004 UndefElements->resize(NumOps); 10005 } 10006 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10007 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10008 return false; 10009 10010 // Set the undefs even if we don't find a sequence (like getSplatValue). 10011 if (UndefElements) 10012 for (unsigned I = 0; I != NumOps; ++I) 10013 if (DemandedElts[I] && getOperand(I).isUndef()) 10014 (*UndefElements)[I] = true; 10015 10016 // Iteratively widen the sequence length looking for repetitions. 10017 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10018 Sequence.append(SeqLen, SDValue()); 10019 for (unsigned I = 0; I != NumOps; ++I) { 10020 if (!DemandedElts[I]) 10021 continue; 10022 SDValue &SeqOp = Sequence[I % SeqLen]; 10023 SDValue Op = getOperand(I); 10024 if (Op.isUndef()) { 10025 if (!SeqOp) 10026 SeqOp = Op; 10027 continue; 10028 } 10029 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10030 Sequence.clear(); 10031 break; 10032 } 10033 SeqOp = Op; 10034 } 10035 if (!Sequence.empty()) 10036 return true; 10037 } 10038 10039 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10040 return false; 10041 } 10042 10043 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10044 BitVector *UndefElements) const { 10045 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 10046 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10047 } 10048 10049 ConstantSDNode * 10050 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10051 BitVector *UndefElements) const { 10052 return dyn_cast_or_null<ConstantSDNode>( 10053 getSplatValue(DemandedElts, UndefElements)); 10054 } 10055 10056 ConstantSDNode * 10057 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10058 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10059 } 10060 10061 ConstantFPSDNode * 10062 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10063 BitVector *UndefElements) const { 10064 return dyn_cast_or_null<ConstantFPSDNode>( 10065 getSplatValue(DemandedElts, UndefElements)); 10066 } 10067 10068 ConstantFPSDNode * 10069 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10070 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10071 } 10072 10073 int32_t 10074 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10075 uint32_t BitWidth) const { 10076 if (ConstantFPSDNode *CN = 10077 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10078 bool IsExact; 10079 APSInt IntVal(BitWidth); 10080 const APFloat &APF = CN->getValueAPF(); 10081 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10082 APFloat::opOK || 10083 !IsExact) 10084 return -1; 10085 10086 return IntVal.exactLogBase2(); 10087 } 10088 return -1; 10089 } 10090 10091 bool BuildVectorSDNode::isConstant() const { 10092 for (const SDValue &Op : op_values()) { 10093 unsigned Opc = Op.getOpcode(); 10094 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 10095 return false; 10096 } 10097 return true; 10098 } 10099 10100 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 10101 // Find the first non-undef value in the shuffle mask. 10102 unsigned i, e; 10103 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 10104 /* search */; 10105 10106 // If all elements are undefined, this shuffle can be considered a splat 10107 // (although it should eventually get simplified away completely). 10108 if (i == e) 10109 return true; 10110 10111 // Make sure all remaining elements are either undef or the same as the first 10112 // non-undef value. 10113 for (int Idx = Mask[i]; i != e; ++i) 10114 if (Mask[i] >= 0 && Mask[i] != Idx) 10115 return false; 10116 return true; 10117 } 10118 10119 // Returns the SDNode if it is a constant integer BuildVector 10120 // or constant integer. 10121 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 10122 if (isa<ConstantSDNode>(N)) 10123 return N.getNode(); 10124 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 10125 return N.getNode(); 10126 // Treat a GlobalAddress supporting constant offset folding as a 10127 // constant integer. 10128 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 10129 if (GA->getOpcode() == ISD::GlobalAddress && 10130 TLI->isOffsetFoldingLegal(GA)) 10131 return GA; 10132 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 10133 isa<ConstantSDNode>(N.getOperand(0))) 10134 return N.getNode(); 10135 return nullptr; 10136 } 10137 10138 // Returns the SDNode if it is a constant float BuildVector 10139 // or constant float. 10140 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 10141 if (isa<ConstantFPSDNode>(N)) 10142 return N.getNode(); 10143 10144 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 10145 return N.getNode(); 10146 10147 return nullptr; 10148 } 10149 10150 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 10151 assert(!Node->OperandList && "Node already has operands"); 10152 assert(SDNode::getMaxNumOperands() >= Vals.size() && 10153 "too many operands to fit into SDNode"); 10154 SDUse *Ops = OperandRecycler.allocate( 10155 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 10156 10157 bool IsDivergent = false; 10158 for (unsigned I = 0; I != Vals.size(); ++I) { 10159 Ops[I].setUser(Node); 10160 Ops[I].setInitial(Vals[I]); 10161 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 10162 IsDivergent |= Ops[I].getNode()->isDivergent(); 10163 } 10164 Node->NumOperands = Vals.size(); 10165 Node->OperandList = Ops; 10166 if (!TLI->isSDNodeAlwaysUniform(Node)) { 10167 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 10168 Node->SDNodeBits.IsDivergent = IsDivergent; 10169 } 10170 checkForCycles(Node); 10171 } 10172 10173 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 10174 SmallVectorImpl<SDValue> &Vals) { 10175 size_t Limit = SDNode::getMaxNumOperands(); 10176 while (Vals.size() > Limit) { 10177 unsigned SliceIdx = Vals.size() - Limit; 10178 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 10179 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 10180 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 10181 Vals.emplace_back(NewTF); 10182 } 10183 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 10184 } 10185 10186 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 10187 EVT VT, SDNodeFlags Flags) { 10188 switch (Opcode) { 10189 default: 10190 return SDValue(); 10191 case ISD::ADD: 10192 case ISD::OR: 10193 case ISD::XOR: 10194 case ISD::UMAX: 10195 return getConstant(0, DL, VT); 10196 case ISD::MUL: 10197 return getConstant(1, DL, VT); 10198 case ISD::AND: 10199 case ISD::UMIN: 10200 return getAllOnesConstant(DL, VT); 10201 case ISD::SMAX: 10202 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 10203 case ISD::SMIN: 10204 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 10205 case ISD::FADD: 10206 return getConstantFP(-0.0, DL, VT); 10207 case ISD::FMUL: 10208 return getConstantFP(1.0, DL, VT); 10209 case ISD::FMINNUM: 10210 case ISD::FMAXNUM: { 10211 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 10212 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 10213 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 10214 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 10215 APFloat::getLargest(Semantics); 10216 if (Opcode == ISD::FMAXNUM) 10217 NeutralAF.changeSign(); 10218 10219 return getConstantFP(NeutralAF, DL, VT); 10220 } 10221 } 10222 } 10223 10224 #ifndef NDEBUG 10225 static void checkForCyclesHelper(const SDNode *N, 10226 SmallPtrSetImpl<const SDNode*> &Visited, 10227 SmallPtrSetImpl<const SDNode*> &Checked, 10228 const llvm::SelectionDAG *DAG) { 10229 // If this node has already been checked, don't check it again. 10230 if (Checked.count(N)) 10231 return; 10232 10233 // If a node has already been visited on this depth-first walk, reject it as 10234 // a cycle. 10235 if (!Visited.insert(N).second) { 10236 errs() << "Detected cycle in SelectionDAG\n"; 10237 dbgs() << "Offending node:\n"; 10238 N->dumprFull(DAG); dbgs() << "\n"; 10239 abort(); 10240 } 10241 10242 for (const SDValue &Op : N->op_values()) 10243 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 10244 10245 Checked.insert(N); 10246 Visited.erase(N); 10247 } 10248 #endif 10249 10250 void llvm::checkForCycles(const llvm::SDNode *N, 10251 const llvm::SelectionDAG *DAG, 10252 bool force) { 10253 #ifndef NDEBUG 10254 bool check = force; 10255 #ifdef EXPENSIVE_CHECKS 10256 check = true; 10257 #endif // EXPENSIVE_CHECKS 10258 if (check) { 10259 assert(N && "Checking nonexistent SDNode"); 10260 SmallPtrSet<const SDNode*, 32> visited; 10261 SmallPtrSet<const SDNode*, 32> checked; 10262 checkForCyclesHelper(N, visited, checked, DAG); 10263 } 10264 #endif // !NDEBUG 10265 } 10266 10267 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 10268 checkForCycles(DAG->getRoot().getNode(), DAG, force); 10269 } 10270