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