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