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