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