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