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