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