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