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