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