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(VT.getSizeInBits() == Operand.getValueSizeInBits() && 4172 "The sizes of the input and result must match in order to perform the " 4173 "extend in-register."); 4174 assert(VT.getVectorNumElements() < 4175 Operand.getValueType().getVectorNumElements() && 4176 "The destination vector type must have fewer lanes than the input."); 4177 break; 4178 case ISD::ABS: 4179 assert(VT.isInteger() && VT == Operand.getValueType() && 4180 "Invalid ABS!"); 4181 if (OpOpcode == ISD::UNDEF) 4182 return getUNDEF(VT); 4183 break; 4184 case ISD::BSWAP: 4185 assert(VT.isInteger() && VT == Operand.getValueType() && 4186 "Invalid BSWAP!"); 4187 assert((VT.getScalarSizeInBits() % 16 == 0) && 4188 "BSWAP types must be a multiple of 16 bits!"); 4189 if (OpOpcode == ISD::UNDEF) 4190 return getUNDEF(VT); 4191 break; 4192 case ISD::BITREVERSE: 4193 assert(VT.isInteger() && VT == Operand.getValueType() && 4194 "Invalid BITREVERSE!"); 4195 if (OpOpcode == ISD::UNDEF) 4196 return getUNDEF(VT); 4197 break; 4198 case ISD::BITCAST: 4199 // Basic sanity checking. 4200 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 4201 "Cannot BITCAST between types of different sizes!"); 4202 if (VT == Operand.getValueType()) return Operand; // noop conversion. 4203 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 4204 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 4205 if (OpOpcode == ISD::UNDEF) 4206 return getUNDEF(VT); 4207 break; 4208 case ISD::SCALAR_TO_VECTOR: 4209 assert(VT.isVector() && !Operand.getValueType().isVector() && 4210 (VT.getVectorElementType() == Operand.getValueType() || 4211 (VT.getVectorElementType().isInteger() && 4212 Operand.getValueType().isInteger() && 4213 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 4214 "Illegal SCALAR_TO_VECTOR node!"); 4215 if (OpOpcode == ISD::UNDEF) 4216 return getUNDEF(VT); 4217 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 4218 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 4219 isa<ConstantSDNode>(Operand.getOperand(1)) && 4220 Operand.getConstantOperandVal(1) == 0 && 4221 Operand.getOperand(0).getValueType() == VT) 4222 return Operand.getOperand(0); 4223 break; 4224 case ISD::FNEG: 4225 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 4226 if ((getTarget().Options.UnsafeFPMath || Flags.hasNoSignedZeros()) && 4227 OpOpcode == ISD::FSUB) 4228 return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1), 4229 Operand.getOperand(0), Flags); 4230 if (OpOpcode == ISD::FNEG) // --X -> X 4231 return Operand.getOperand(0); 4232 break; 4233 case ISD::FABS: 4234 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 4235 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 4236 break; 4237 } 4238 4239 SDNode *N; 4240 SDVTList VTs = getVTList(VT); 4241 SDValue Ops[] = {Operand}; 4242 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 4243 FoldingSetNodeID ID; 4244 AddNodeIDNode(ID, Opcode, VTs, Ops); 4245 void *IP = nullptr; 4246 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 4247 E->intersectFlagsWith(Flags); 4248 return SDValue(E, 0); 4249 } 4250 4251 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4252 N->setFlags(Flags); 4253 createOperands(N, Ops); 4254 CSEMap.InsertNode(N, IP); 4255 } else { 4256 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4257 createOperands(N, Ops); 4258 } 4259 4260 InsertNode(N); 4261 SDValue V = SDValue(N, 0); 4262 NewSDValueDbgMsg(V, "Creating new node: ", this); 4263 return V; 4264 } 4265 4266 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1, 4267 const APInt &C2) { 4268 switch (Opcode) { 4269 case ISD::ADD: return std::make_pair(C1 + C2, true); 4270 case ISD::SUB: return std::make_pair(C1 - C2, true); 4271 case ISD::MUL: return std::make_pair(C1 * C2, true); 4272 case ISD::AND: return std::make_pair(C1 & C2, true); 4273 case ISD::OR: return std::make_pair(C1 | C2, true); 4274 case ISD::XOR: return std::make_pair(C1 ^ C2, true); 4275 case ISD::SHL: return std::make_pair(C1 << C2, true); 4276 case ISD::SRL: return std::make_pair(C1.lshr(C2), true); 4277 case ISD::SRA: return std::make_pair(C1.ashr(C2), true); 4278 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true); 4279 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true); 4280 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true); 4281 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true); 4282 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true); 4283 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true); 4284 case ISD::UDIV: 4285 if (!C2.getBoolValue()) 4286 break; 4287 return std::make_pair(C1.udiv(C2), true); 4288 case ISD::UREM: 4289 if (!C2.getBoolValue()) 4290 break; 4291 return std::make_pair(C1.urem(C2), true); 4292 case ISD::SDIV: 4293 if (!C2.getBoolValue()) 4294 break; 4295 return std::make_pair(C1.sdiv(C2), true); 4296 case ISD::SREM: 4297 if (!C2.getBoolValue()) 4298 break; 4299 return std::make_pair(C1.srem(C2), true); 4300 } 4301 return std::make_pair(APInt(1, 0), false); 4302 } 4303 4304 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 4305 EVT VT, const ConstantSDNode *Cst1, 4306 const ConstantSDNode *Cst2) { 4307 if (Cst1->isOpaque() || Cst2->isOpaque()) 4308 return SDValue(); 4309 4310 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(), 4311 Cst2->getAPIntValue()); 4312 if (!Folded.second) 4313 return SDValue(); 4314 return getConstant(Folded.first, DL, VT); 4315 } 4316 4317 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 4318 const GlobalAddressSDNode *GA, 4319 const SDNode *N2) { 4320 if (GA->getOpcode() != ISD::GlobalAddress) 4321 return SDValue(); 4322 if (!TLI->isOffsetFoldingLegal(GA)) 4323 return SDValue(); 4324 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2); 4325 if (!Cst2) 4326 return SDValue(); 4327 int64_t Offset = Cst2->getSExtValue(); 4328 switch (Opcode) { 4329 case ISD::ADD: break; 4330 case ISD::SUB: Offset = -uint64_t(Offset); break; 4331 default: return SDValue(); 4332 } 4333 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT, 4334 GA->getOffset() + uint64_t(Offset)); 4335 } 4336 4337 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 4338 switch (Opcode) { 4339 case ISD::SDIV: 4340 case ISD::UDIV: 4341 case ISD::SREM: 4342 case ISD::UREM: { 4343 // If a divisor is zero/undef or any element of a divisor vector is 4344 // zero/undef, the whole op is undef. 4345 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 4346 SDValue Divisor = Ops[1]; 4347 if (Divisor.isUndef() || isNullConstant(Divisor)) 4348 return true; 4349 4350 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 4351 llvm::any_of(Divisor->op_values(), 4352 [](SDValue V) { return V.isUndef() || 4353 isNullConstant(V); }); 4354 // TODO: Handle signed overflow. 4355 } 4356 // TODO: Handle oversized shifts. 4357 default: 4358 return false; 4359 } 4360 } 4361 4362 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 4363 EVT VT, SDNode *Cst1, 4364 SDNode *Cst2) { 4365 // If the opcode is a target-specific ISD node, there's nothing we can 4366 // do here and the operand rules may not line up with the below, so 4367 // bail early. 4368 if (Opcode >= ISD::BUILTIN_OP_END) 4369 return SDValue(); 4370 4371 if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)})) 4372 return getUNDEF(VT); 4373 4374 // Handle the case of two scalars. 4375 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) { 4376 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) { 4377 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2); 4378 assert((!Folded || !VT.isVector()) && 4379 "Can't fold vectors ops with scalar operands"); 4380 return Folded; 4381 } 4382 } 4383 4384 // fold (add Sym, c) -> Sym+c 4385 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1)) 4386 return FoldSymbolOffset(Opcode, VT, GA, Cst2); 4387 if (TLI->isCommutativeBinOp(Opcode)) 4388 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2)) 4389 return FoldSymbolOffset(Opcode, VT, GA, Cst1); 4390 4391 // For vectors extract each constant element into Inputs so we can constant 4392 // fold them individually. 4393 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1); 4394 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2); 4395 if (!BV1 || !BV2) 4396 return SDValue(); 4397 4398 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!"); 4399 4400 EVT SVT = VT.getScalarType(); 4401 EVT LegalSVT = SVT; 4402 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 4403 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 4404 if (LegalSVT.bitsLT(SVT)) 4405 return SDValue(); 4406 } 4407 SmallVector<SDValue, 4> Outputs; 4408 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) { 4409 SDValue V1 = BV1->getOperand(I); 4410 SDValue V2 = BV2->getOperand(I); 4411 4412 if (SVT.isInteger()) { 4413 if (V1->getValueType(0).bitsGT(SVT)) 4414 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1); 4415 if (V2->getValueType(0).bitsGT(SVT)) 4416 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2); 4417 } 4418 4419 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT) 4420 return SDValue(); 4421 4422 // Fold one vector element. 4423 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2); 4424 if (LegalSVT != SVT) 4425 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 4426 4427 // Scalar folding only succeeded if the result is a constant or UNDEF. 4428 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 4429 ScalarResult.getOpcode() != ISD::ConstantFP) 4430 return SDValue(); 4431 Outputs.push_back(ScalarResult); 4432 } 4433 4434 assert(VT.getVectorNumElements() == Outputs.size() && 4435 "Vector size mismatch!"); 4436 4437 // We may have a vector type but a scalar result. Create a splat. 4438 Outputs.resize(VT.getVectorNumElements(), Outputs.back()); 4439 4440 // Build a big vector out of the scalar elements we generated. 4441 return getBuildVector(VT, SDLoc(), Outputs); 4442 } 4443 4444 // TODO: Merge with FoldConstantArithmetic 4445 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 4446 const SDLoc &DL, EVT VT, 4447 ArrayRef<SDValue> Ops, 4448 const SDNodeFlags Flags) { 4449 // If the opcode is a target-specific ISD node, there's nothing we can 4450 // do here and the operand rules may not line up with the below, so 4451 // bail early. 4452 if (Opcode >= ISD::BUILTIN_OP_END) 4453 return SDValue(); 4454 4455 if (isUndef(Opcode, Ops)) 4456 return getUNDEF(VT); 4457 4458 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 4459 if (!VT.isVector()) 4460 return SDValue(); 4461 4462 unsigned NumElts = VT.getVectorNumElements(); 4463 4464 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) { 4465 return !Op.getValueType().isVector() || 4466 Op.getValueType().getVectorNumElements() == NumElts; 4467 }; 4468 4469 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) { 4470 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 4471 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) || 4472 (BV && BV->isConstant()); 4473 }; 4474 4475 // All operands must be vector types with the same number of elements as 4476 // the result type and must be either UNDEF or a build vector of constant 4477 // or UNDEF scalars. 4478 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) || 4479 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 4480 return SDValue(); 4481 4482 // If we are comparing vectors, then the result needs to be a i1 boolean 4483 // that is then sign-extended back to the legal result type. 4484 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 4485 4486 // Find legal integer scalar type for constant promotion and 4487 // ensure that its scalar size is at least as large as source. 4488 EVT LegalSVT = VT.getScalarType(); 4489 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 4490 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 4491 if (LegalSVT.bitsLT(VT.getScalarType())) 4492 return SDValue(); 4493 } 4494 4495 // Constant fold each scalar lane separately. 4496 SmallVector<SDValue, 4> ScalarResults; 4497 for (unsigned i = 0; i != NumElts; i++) { 4498 SmallVector<SDValue, 4> ScalarOps; 4499 for (SDValue Op : Ops) { 4500 EVT InSVT = Op.getValueType().getScalarType(); 4501 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op); 4502 if (!InBV) { 4503 // We've checked that this is UNDEF or a constant of some kind. 4504 if (Op.isUndef()) 4505 ScalarOps.push_back(getUNDEF(InSVT)); 4506 else 4507 ScalarOps.push_back(Op); 4508 continue; 4509 } 4510 4511 SDValue ScalarOp = InBV->getOperand(i); 4512 EVT ScalarVT = ScalarOp.getValueType(); 4513 4514 // Build vector (integer) scalar operands may need implicit 4515 // truncation - do this before constant folding. 4516 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 4517 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 4518 4519 ScalarOps.push_back(ScalarOp); 4520 } 4521 4522 // Constant fold the scalar operands. 4523 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 4524 4525 // Legalize the (integer) scalar constant if necessary. 4526 if (LegalSVT != SVT) 4527 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 4528 4529 // Scalar folding only succeeded if the result is a constant or UNDEF. 4530 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 4531 ScalarResult.getOpcode() != ISD::ConstantFP) 4532 return SDValue(); 4533 ScalarResults.push_back(ScalarResult); 4534 } 4535 4536 SDValue V = getBuildVector(VT, DL, ScalarResults); 4537 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 4538 return V; 4539 } 4540 4541 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4542 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 4543 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4544 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4545 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 4546 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 4547 4548 // Canonicalize constant to RHS if commutative. 4549 if (TLI->isCommutativeBinOp(Opcode)) { 4550 if (N1C && !N2C) { 4551 std::swap(N1C, N2C); 4552 std::swap(N1, N2); 4553 } else if (N1CFP && !N2CFP) { 4554 std::swap(N1CFP, N2CFP); 4555 std::swap(N1, N2); 4556 } 4557 } 4558 4559 switch (Opcode) { 4560 default: break; 4561 case ISD::TokenFactor: 4562 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 4563 N2.getValueType() == MVT::Other && "Invalid token factor!"); 4564 // Fold trivial token factors. 4565 if (N1.getOpcode() == ISD::EntryToken) return N2; 4566 if (N2.getOpcode() == ISD::EntryToken) return N1; 4567 if (N1 == N2) return N1; 4568 break; 4569 case ISD::BUILD_VECTOR: { 4570 // Attempt to simplify BUILD_VECTOR. 4571 SDValue Ops[] = {N1, N2}; 4572 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4573 return V; 4574 break; 4575 } 4576 case ISD::CONCAT_VECTORS: { 4577 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 4578 SDValue Ops[] = {N1, N2}; 4579 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 4580 return V; 4581 break; 4582 } 4583 case ISD::AND: 4584 assert(VT.isInteger() && "This operator does not apply to FP types!"); 4585 assert(N1.getValueType() == N2.getValueType() && 4586 N1.getValueType() == VT && "Binary operator types must match!"); 4587 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 4588 // worth handling here. 4589 if (N2C && N2C->isNullValue()) 4590 return N2; 4591 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 4592 return N1; 4593 break; 4594 case ISD::OR: 4595 case ISD::XOR: 4596 case ISD::ADD: 4597 case ISD::SUB: 4598 assert(VT.isInteger() && "This operator does not apply to FP types!"); 4599 assert(N1.getValueType() == N2.getValueType() && 4600 N1.getValueType() == VT && "Binary operator types must match!"); 4601 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 4602 // it's worth handling here. 4603 if (N2C && N2C->isNullValue()) 4604 return N1; 4605 break; 4606 case ISD::UDIV: 4607 case ISD::UREM: 4608 case ISD::MULHU: 4609 case ISD::MULHS: 4610 case ISD::MUL: 4611 case ISD::SDIV: 4612 case ISD::SREM: 4613 case ISD::SMIN: 4614 case ISD::SMAX: 4615 case ISD::UMIN: 4616 case ISD::UMAX: 4617 assert(VT.isInteger() && "This operator does not apply to FP types!"); 4618 assert(N1.getValueType() == N2.getValueType() && 4619 N1.getValueType() == VT && "Binary operator types must match!"); 4620 break; 4621 case ISD::FADD: 4622 case ISD::FSUB: 4623 case ISD::FMUL: 4624 case ISD::FDIV: 4625 case ISD::FREM: 4626 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 4627 assert(N1.getValueType() == N2.getValueType() && 4628 N1.getValueType() == VT && "Binary operator types must match!"); 4629 break; 4630 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 4631 assert(N1.getValueType() == VT && 4632 N1.getValueType().isFloatingPoint() && 4633 N2.getValueType().isFloatingPoint() && 4634 "Invalid FCOPYSIGN!"); 4635 break; 4636 case ISD::SHL: 4637 case ISD::SRA: 4638 case ISD::SRL: 4639 case ISD::ROTL: 4640 case ISD::ROTR: 4641 assert(VT == N1.getValueType() && 4642 "Shift operators return type must be the same as their first arg"); 4643 assert(VT.isInteger() && N2.getValueType().isInteger() && 4644 "Shifts only work on integers"); 4645 assert((!VT.isVector() || VT == N2.getValueType()) && 4646 "Vector shift amounts must be in the same as their first arg"); 4647 // Verify that the shift amount VT is bit enough to hold valid shift 4648 // amounts. This catches things like trying to shift an i1024 value by an 4649 // i8, which is easy to fall into in generic code that uses 4650 // TLI.getShiftAmount(). 4651 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) && 4652 "Invalid use of small shift amount with oversized value!"); 4653 4654 // Always fold shifts of i1 values so the code generator doesn't need to 4655 // handle them. Since we know the size of the shift has to be less than the 4656 // size of the value, the shift/rotate count is guaranteed to be zero. 4657 if (VT == MVT::i1) 4658 return N1; 4659 if (N2C && N2C->isNullValue()) 4660 return N1; 4661 break; 4662 case ISD::FP_ROUND_INREG: { 4663 EVT EVT = cast<VTSDNode>(N2)->getVT(); 4664 assert(VT == N1.getValueType() && "Not an inreg round!"); 4665 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() && 4666 "Cannot FP_ROUND_INREG integer types"); 4667 assert(EVT.isVector() == VT.isVector() && 4668 "FP_ROUND_INREG type should be vector iff the operand " 4669 "type is vector!"); 4670 assert((!EVT.isVector() || 4671 EVT.getVectorNumElements() == VT.getVectorNumElements()) && 4672 "Vector element counts must match in FP_ROUND_INREG"); 4673 assert(EVT.bitsLE(VT) && "Not rounding down!"); 4674 (void)EVT; 4675 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding. 4676 break; 4677 } 4678 case ISD::FP_ROUND: 4679 assert(VT.isFloatingPoint() && 4680 N1.getValueType().isFloatingPoint() && 4681 VT.bitsLE(N1.getValueType()) && 4682 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 4683 "Invalid FP_ROUND!"); 4684 if (N1.getValueType() == VT) return N1; // noop conversion. 4685 break; 4686 case ISD::AssertSext: 4687 case ISD::AssertZext: { 4688 EVT EVT = cast<VTSDNode>(N2)->getVT(); 4689 assert(VT == N1.getValueType() && "Not an inreg extend!"); 4690 assert(VT.isInteger() && EVT.isInteger() && 4691 "Cannot *_EXTEND_INREG FP types"); 4692 assert(!EVT.isVector() && 4693 "AssertSExt/AssertZExt type should be the vector element type " 4694 "rather than the vector type!"); 4695 assert(EVT.bitsLE(VT) && "Not extending!"); 4696 if (VT == EVT) return N1; // noop assertion. 4697 break; 4698 } 4699 case ISD::SIGN_EXTEND_INREG: { 4700 EVT EVT = cast<VTSDNode>(N2)->getVT(); 4701 assert(VT == N1.getValueType() && "Not an inreg extend!"); 4702 assert(VT.isInteger() && EVT.isInteger() && 4703 "Cannot *_EXTEND_INREG FP types"); 4704 assert(EVT.isVector() == VT.isVector() && 4705 "SIGN_EXTEND_INREG type should be vector iff the operand " 4706 "type is vector!"); 4707 assert((!EVT.isVector() || 4708 EVT.getVectorNumElements() == VT.getVectorNumElements()) && 4709 "Vector element counts must match in SIGN_EXTEND_INREG"); 4710 assert(EVT.bitsLE(VT) && "Not extending!"); 4711 if (EVT == VT) return N1; // Not actually extending 4712 4713 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 4714 unsigned FromBits = EVT.getScalarSizeInBits(); 4715 Val <<= Val.getBitWidth() - FromBits; 4716 Val.ashrInPlace(Val.getBitWidth() - FromBits); 4717 return getConstant(Val, DL, ConstantVT); 4718 }; 4719 4720 if (N1C) { 4721 const APInt &Val = N1C->getAPIntValue(); 4722 return SignExtendInReg(Val, VT); 4723 } 4724 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 4725 SmallVector<SDValue, 8> Ops; 4726 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 4727 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 4728 SDValue Op = N1.getOperand(i); 4729 if (Op.isUndef()) { 4730 Ops.push_back(getUNDEF(OpVT)); 4731 continue; 4732 } 4733 ConstantSDNode *C = cast<ConstantSDNode>(Op); 4734 APInt Val = C->getAPIntValue(); 4735 Ops.push_back(SignExtendInReg(Val, OpVT)); 4736 } 4737 return getBuildVector(VT, DL, Ops); 4738 } 4739 break; 4740 } 4741 case ISD::EXTRACT_VECTOR_ELT: 4742 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 4743 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 4744 element type of the vector."); 4745 4746 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF. 4747 if (N1.isUndef()) 4748 return getUNDEF(VT); 4749 4750 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF 4751 if (N2C && N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 4752 return getUNDEF(VT); 4753 4754 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 4755 // expanding copies of large vectors from registers. 4756 if (N2C && 4757 N1.getOpcode() == ISD::CONCAT_VECTORS && 4758 N1.getNumOperands() > 0) { 4759 unsigned Factor = 4760 N1.getOperand(0).getValueType().getVectorNumElements(); 4761 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 4762 N1.getOperand(N2C->getZExtValue() / Factor), 4763 getConstant(N2C->getZExtValue() % Factor, DL, 4764 N2.getValueType())); 4765 } 4766 4767 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is 4768 // expanding large vector constants. 4769 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) { 4770 SDValue Elt = N1.getOperand(N2C->getZExtValue()); 4771 4772 if (VT != Elt.getValueType()) 4773 // If the vector element type is not legal, the BUILD_VECTOR operands 4774 // are promoted and implicitly truncated, and the result implicitly 4775 // extended. Make that explicit here. 4776 Elt = getAnyExtOrTrunc(Elt, DL, VT); 4777 4778 return Elt; 4779 } 4780 4781 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 4782 // operations are lowered to scalars. 4783 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 4784 // If the indices are the same, return the inserted element else 4785 // if the indices are known different, extract the element from 4786 // the original vector. 4787 SDValue N1Op2 = N1.getOperand(2); 4788 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 4789 4790 if (N1Op2C && N2C) { 4791 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 4792 if (VT == N1.getOperand(1).getValueType()) 4793 return N1.getOperand(1); 4794 else 4795 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 4796 } 4797 4798 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 4799 } 4800 } 4801 4802 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 4803 // when vector types are scalarized and v1iX is legal. 4804 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx) 4805 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 4806 N1.getValueType().getVectorNumElements() == 1) { 4807 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 4808 N1.getOperand(1)); 4809 } 4810 break; 4811 case ISD::EXTRACT_ELEMENT: 4812 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 4813 assert(!N1.getValueType().isVector() && !VT.isVector() && 4814 (N1.getValueType().isInteger() == VT.isInteger()) && 4815 N1.getValueType() != VT && 4816 "Wrong types for EXTRACT_ELEMENT!"); 4817 4818 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 4819 // 64-bit integers into 32-bit parts. Instead of building the extract of 4820 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 4821 if (N1.getOpcode() == ISD::BUILD_PAIR) 4822 return N1.getOperand(N2C->getZExtValue()); 4823 4824 // EXTRACT_ELEMENT of a constant int is also very common. 4825 if (N1C) { 4826 unsigned ElementSize = VT.getSizeInBits(); 4827 unsigned Shift = ElementSize * N2C->getZExtValue(); 4828 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift); 4829 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT); 4830 } 4831 break; 4832 case ISD::EXTRACT_SUBVECTOR: 4833 if (VT.isSimple() && N1.getValueType().isSimple()) { 4834 assert(VT.isVector() && N1.getValueType().isVector() && 4835 "Extract subvector VTs must be a vectors!"); 4836 assert(VT.getVectorElementType() == 4837 N1.getValueType().getVectorElementType() && 4838 "Extract subvector VTs must have the same element type!"); 4839 assert(VT.getSimpleVT() <= N1.getSimpleValueType() && 4840 "Extract subvector must be from larger vector to smaller vector!"); 4841 4842 if (N2C) { 4843 assert((VT.getVectorNumElements() + N2C->getZExtValue() 4844 <= N1.getValueType().getVectorNumElements()) 4845 && "Extract subvector overflow!"); 4846 } 4847 4848 // Trivial extraction. 4849 if (VT.getSimpleVT() == N1.getSimpleValueType()) 4850 return N1; 4851 4852 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 4853 if (N1.isUndef()) 4854 return getUNDEF(VT); 4855 4856 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 4857 // the concat have the same type as the extract. 4858 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS && 4859 N1.getNumOperands() > 0 && 4860 VT == N1.getOperand(0).getValueType()) { 4861 unsigned Factor = VT.getVectorNumElements(); 4862 return N1.getOperand(N2C->getZExtValue() / Factor); 4863 } 4864 4865 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 4866 // during shuffle legalization. 4867 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 4868 VT == N1.getOperand(1).getValueType()) 4869 return N1.getOperand(1); 4870 } 4871 break; 4872 } 4873 4874 // Perform trivial constant folding. 4875 if (SDValue SV = 4876 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode())) 4877 return SV; 4878 4879 // Constant fold FP operations. 4880 bool HasFPExceptions = TLI->hasFloatingPointExceptions(); 4881 if (N1CFP) { 4882 if (N2CFP) { 4883 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF(); 4884 APFloat::opStatus s; 4885 switch (Opcode) { 4886 case ISD::FADD: 4887 s = V1.add(V2, APFloat::rmNearestTiesToEven); 4888 if (!HasFPExceptions || s != APFloat::opInvalidOp) 4889 return getConstantFP(V1, DL, VT); 4890 break; 4891 case ISD::FSUB: 4892 s = V1.subtract(V2, APFloat::rmNearestTiesToEven); 4893 if (!HasFPExceptions || s!=APFloat::opInvalidOp) 4894 return getConstantFP(V1, DL, VT); 4895 break; 4896 case ISD::FMUL: 4897 s = V1.multiply(V2, APFloat::rmNearestTiesToEven); 4898 if (!HasFPExceptions || s!=APFloat::opInvalidOp) 4899 return getConstantFP(V1, DL, VT); 4900 break; 4901 case ISD::FDIV: 4902 s = V1.divide(V2, APFloat::rmNearestTiesToEven); 4903 if (!HasFPExceptions || (s!=APFloat::opInvalidOp && 4904 s!=APFloat::opDivByZero)) { 4905 return getConstantFP(V1, DL, VT); 4906 } 4907 break; 4908 case ISD::FREM : 4909 s = V1.mod(V2); 4910 if (!HasFPExceptions || (s!=APFloat::opInvalidOp && 4911 s!=APFloat::opDivByZero)) { 4912 return getConstantFP(V1, DL, VT); 4913 } 4914 break; 4915 case ISD::FCOPYSIGN: 4916 V1.copySign(V2); 4917 return getConstantFP(V1, DL, VT); 4918 default: break; 4919 } 4920 } 4921 4922 if (Opcode == ISD::FP_ROUND) { 4923 APFloat V = N1CFP->getValueAPF(); // make copy 4924 bool ignored; 4925 // This can return overflow, underflow, or inexact; we don't care. 4926 // FIXME need to be more flexible about rounding mode. 4927 (void)V.convert(EVTToAPFloatSemantics(VT), 4928 APFloat::rmNearestTiesToEven, &ignored); 4929 return getConstantFP(V, DL, VT); 4930 } 4931 } 4932 4933 // Any FP binop with an undef operand is folded to NaN. This matches the 4934 // behavior of the IR optimizer. 4935 switch (Opcode) { 4936 case ISD::FADD: 4937 case ISD::FSUB: 4938 case ISD::FMUL: 4939 case ISD::FDIV: 4940 case ISD::FREM: 4941 if (N1.isUndef() || N2.isUndef()) 4942 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 4943 } 4944 4945 // Canonicalize an UNDEF to the RHS, even over a constant. 4946 if (N1.isUndef()) { 4947 if (TLI->isCommutativeBinOp(Opcode)) { 4948 std::swap(N1, N2); 4949 } else { 4950 switch (Opcode) { 4951 case ISD::FP_ROUND_INREG: 4952 case ISD::SIGN_EXTEND_INREG: 4953 case ISD::SUB: 4954 return getUNDEF(VT); // fold op(undef, arg2) -> undef 4955 case ISD::UDIV: 4956 case ISD::SDIV: 4957 case ISD::UREM: 4958 case ISD::SREM: 4959 case ISD::SRA: 4960 case ISD::SRL: 4961 case ISD::SHL: 4962 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 4963 } 4964 } 4965 } 4966 4967 // Fold a bunch of operators when the RHS is undef. 4968 if (N2.isUndef()) { 4969 switch (Opcode) { 4970 case ISD::XOR: 4971 if (N1.isUndef()) 4972 // Handle undef ^ undef -> 0 special case. This is a common 4973 // idiom (misuse). 4974 return getConstant(0, DL, VT); 4975 LLVM_FALLTHROUGH; 4976 case ISD::ADD: 4977 case ISD::ADDC: 4978 case ISD::ADDE: 4979 case ISD::SUB: 4980 case ISD::UDIV: 4981 case ISD::SDIV: 4982 case ISD::UREM: 4983 case ISD::SREM: 4984 case ISD::SRA: 4985 case ISD::SRL: 4986 case ISD::SHL: 4987 return getUNDEF(VT); // fold op(arg1, undef) -> undef 4988 case ISD::MUL: 4989 case ISD::AND: 4990 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 4991 case ISD::OR: 4992 return getAllOnesConstant(DL, VT); 4993 } 4994 } 4995 4996 // Memoize this node if possible. 4997 SDNode *N; 4998 SDVTList VTs = getVTList(VT); 4999 SDValue Ops[] = {N1, N2}; 5000 if (VT != MVT::Glue) { 5001 FoldingSetNodeID ID; 5002 AddNodeIDNode(ID, Opcode, VTs, Ops); 5003 void *IP = nullptr; 5004 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5005 E->intersectFlagsWith(Flags); 5006 return SDValue(E, 0); 5007 } 5008 5009 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5010 N->setFlags(Flags); 5011 createOperands(N, Ops); 5012 CSEMap.InsertNode(N, IP); 5013 } else { 5014 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5015 createOperands(N, Ops); 5016 } 5017 5018 InsertNode(N); 5019 SDValue V = SDValue(N, 0); 5020 NewSDValueDbgMsg(V, "Creating new node: ", this); 5021 return V; 5022 } 5023 5024 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5025 SDValue N1, SDValue N2, SDValue N3, 5026 const SDNodeFlags Flags) { 5027 // Perform various simplifications. 5028 switch (Opcode) { 5029 case ISD::FMA: { 5030 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5031 assert(N1.getValueType() == VT && N2.getValueType() == VT && 5032 N3.getValueType() == VT && "FMA types must match!"); 5033 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5034 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5035 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 5036 if (N1CFP && N2CFP && N3CFP) { 5037 APFloat V1 = N1CFP->getValueAPF(); 5038 const APFloat &V2 = N2CFP->getValueAPF(); 5039 const APFloat &V3 = N3CFP->getValueAPF(); 5040 APFloat::opStatus s = 5041 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 5042 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp) 5043 return getConstantFP(V1, DL, VT); 5044 } 5045 break; 5046 } 5047 case ISD::BUILD_VECTOR: { 5048 // Attempt to simplify BUILD_VECTOR. 5049 SDValue Ops[] = {N1, N2, N3}; 5050 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5051 return V; 5052 break; 5053 } 5054 case ISD::CONCAT_VECTORS: { 5055 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 5056 SDValue Ops[] = {N1, N2, N3}; 5057 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 5058 return V; 5059 break; 5060 } 5061 case ISD::SETCC: { 5062 assert(VT.isInteger() && "SETCC result type must be an integer!"); 5063 assert(N1.getValueType() == N2.getValueType() && 5064 "SETCC operands must have the same type!"); 5065 assert(VT.isVector() == N1.getValueType().isVector() && 5066 "SETCC type should be vector iff the operand type is vector!"); 5067 assert((!VT.isVector() || 5068 VT.getVectorNumElements() == N1.getValueType().getVectorNumElements()) && 5069 "SETCC vector element counts must match!"); 5070 // Use FoldSetCC to simplify SETCC's. 5071 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 5072 return V; 5073 // Vector constant folding. 5074 SDValue Ops[] = {N1, N2, N3}; 5075 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) { 5076 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 5077 return V; 5078 } 5079 break; 5080 } 5081 case ISD::SELECT: 5082 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 5083 if (N1C->getZExtValue()) 5084 return N2; // select true, X, Y -> X 5085 return N3; // select false, X, Y -> Y 5086 } 5087 5088 if (N2 == N3) return N2; // select C, X, X -> X 5089 break; 5090 case ISD::VECTOR_SHUFFLE: 5091 llvm_unreachable("should use getVectorShuffle constructor!"); 5092 case ISD::INSERT_VECTOR_ELT: { 5093 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 5094 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF 5095 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 5096 return getUNDEF(VT); 5097 break; 5098 } 5099 case ISD::INSERT_SUBVECTOR: { 5100 SDValue Index = N3; 5101 if (VT.isSimple() && N1.getValueType().isSimple() 5102 && N2.getValueType().isSimple()) { 5103 assert(VT.isVector() && N1.getValueType().isVector() && 5104 N2.getValueType().isVector() && 5105 "Insert subvector VTs must be a vectors"); 5106 assert(VT == N1.getValueType() && 5107 "Dest and insert subvector source types must match!"); 5108 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() && 5109 "Insert subvector must be from smaller vector to larger vector!"); 5110 if (isa<ConstantSDNode>(Index)) { 5111 assert((N2.getValueType().getVectorNumElements() + 5112 cast<ConstantSDNode>(Index)->getZExtValue() 5113 <= VT.getVectorNumElements()) 5114 && "Insert subvector overflow!"); 5115 } 5116 5117 // Trivial insertion. 5118 if (VT.getSimpleVT() == N2.getSimpleValueType()) 5119 return N2; 5120 } 5121 break; 5122 } 5123 case ISD::BITCAST: 5124 // Fold bit_convert nodes from a type to themselves. 5125 if (N1.getValueType() == VT) 5126 return N1; 5127 break; 5128 } 5129 5130 // Memoize node if it doesn't produce a flag. 5131 SDNode *N; 5132 SDVTList VTs = getVTList(VT); 5133 SDValue Ops[] = {N1, N2, N3}; 5134 if (VT != MVT::Glue) { 5135 FoldingSetNodeID ID; 5136 AddNodeIDNode(ID, Opcode, VTs, Ops); 5137 void *IP = nullptr; 5138 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5139 E->intersectFlagsWith(Flags); 5140 return SDValue(E, 0); 5141 } 5142 5143 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5144 N->setFlags(Flags); 5145 createOperands(N, Ops); 5146 CSEMap.InsertNode(N, IP); 5147 } else { 5148 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5149 createOperands(N, Ops); 5150 } 5151 5152 InsertNode(N); 5153 SDValue V = SDValue(N, 0); 5154 NewSDValueDbgMsg(V, "Creating new node: ", this); 5155 return V; 5156 } 5157 5158 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5159 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 5160 SDValue Ops[] = { N1, N2, N3, N4 }; 5161 return getNode(Opcode, DL, VT, Ops); 5162 } 5163 5164 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5165 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 5166 SDValue N5) { 5167 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 5168 return getNode(Opcode, DL, VT, Ops); 5169 } 5170 5171 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 5172 /// the incoming stack arguments to be loaded from the stack. 5173 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 5174 SmallVector<SDValue, 8> ArgChains; 5175 5176 // Include the original chain at the beginning of the list. When this is 5177 // used by target LowerCall hooks, this helps legalize find the 5178 // CALLSEQ_BEGIN node. 5179 ArgChains.push_back(Chain); 5180 5181 // Add a chain value for each stack argument. 5182 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 5183 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 5184 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 5185 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 5186 if (FI->getIndex() < 0) 5187 ArgChains.push_back(SDValue(L, 1)); 5188 5189 // Build a tokenfactor for all the chains. 5190 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 5191 } 5192 5193 /// getMemsetValue - Vectorized representation of the memset value 5194 /// operand. 5195 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 5196 const SDLoc &dl) { 5197 assert(!Value.isUndef()); 5198 5199 unsigned NumBits = VT.getScalarSizeInBits(); 5200 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 5201 assert(C->getAPIntValue().getBitWidth() == 8); 5202 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 5203 if (VT.isInteger()) { 5204 bool IsOpaque = VT.getSizeInBits() > 64 || 5205 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 5206 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 5207 } 5208 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 5209 VT); 5210 } 5211 5212 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 5213 EVT IntVT = VT.getScalarType(); 5214 if (!IntVT.isInteger()) 5215 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 5216 5217 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 5218 if (NumBits > 8) { 5219 // Use a multiplication with 0x010101... to extend the input to the 5220 // required length. 5221 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 5222 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 5223 DAG.getConstant(Magic, dl, IntVT)); 5224 } 5225 5226 if (VT != Value.getValueType() && !VT.isInteger()) 5227 Value = DAG.getBitcast(VT.getScalarType(), Value); 5228 if (VT != Value.getValueType()) 5229 Value = DAG.getSplatBuildVector(VT, dl, Value); 5230 5231 return Value; 5232 } 5233 5234 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 5235 /// used when a memcpy is turned into a memset when the source is a constant 5236 /// string ptr. 5237 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 5238 const TargetLowering &TLI, 5239 const ConstantDataArraySlice &Slice) { 5240 // Handle vector with all elements zero. 5241 if (Slice.Array == nullptr) { 5242 if (VT.isInteger()) 5243 return DAG.getConstant(0, dl, VT); 5244 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 5245 return DAG.getConstantFP(0.0, dl, VT); 5246 else if (VT.isVector()) { 5247 unsigned NumElts = VT.getVectorNumElements(); 5248 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 5249 return DAG.getNode(ISD::BITCAST, dl, VT, 5250 DAG.getConstant(0, dl, 5251 EVT::getVectorVT(*DAG.getContext(), 5252 EltVT, NumElts))); 5253 } else 5254 llvm_unreachable("Expected type!"); 5255 } 5256 5257 assert(!VT.isVector() && "Can't handle vector type here!"); 5258 unsigned NumVTBits = VT.getSizeInBits(); 5259 unsigned NumVTBytes = NumVTBits / 8; 5260 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 5261 5262 APInt Val(NumVTBits, 0); 5263 if (DAG.getDataLayout().isLittleEndian()) { 5264 for (unsigned i = 0; i != NumBytes; ++i) 5265 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 5266 } else { 5267 for (unsigned i = 0; i != NumBytes; ++i) 5268 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 5269 } 5270 5271 // If the "cost" of materializing the integer immediate is less than the cost 5272 // of a load, then it is cost effective to turn the load into the immediate. 5273 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 5274 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 5275 return DAG.getConstant(Val, dl, VT); 5276 return SDValue(nullptr, 0); 5277 } 5278 5279 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset, 5280 const SDLoc &DL) { 5281 EVT VT = Base.getValueType(); 5282 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT)); 5283 } 5284 5285 /// Returns true if memcpy source is constant data. 5286 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 5287 uint64_t SrcDelta = 0; 5288 GlobalAddressSDNode *G = nullptr; 5289 if (Src.getOpcode() == ISD::GlobalAddress) 5290 G = cast<GlobalAddressSDNode>(Src); 5291 else if (Src.getOpcode() == ISD::ADD && 5292 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 5293 Src.getOperand(1).getOpcode() == ISD::Constant) { 5294 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 5295 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 5296 } 5297 if (!G) 5298 return false; 5299 5300 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 5301 SrcDelta + G->getOffset()); 5302 } 5303 5304 /// Determines the optimal series of memory ops to replace the memset / memcpy. 5305 /// Return true if the number of memory ops is below the threshold (Limit). 5306 /// It returns the types of the sequence of memory ops to perform 5307 /// memset / memcpy by reference. 5308 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps, 5309 unsigned Limit, uint64_t Size, 5310 unsigned DstAlign, unsigned SrcAlign, 5311 bool IsMemset, 5312 bool ZeroMemset, 5313 bool MemcpyStrSrc, 5314 bool AllowOverlap, 5315 unsigned DstAS, unsigned SrcAS, 5316 SelectionDAG &DAG, 5317 const TargetLowering &TLI) { 5318 assert((SrcAlign == 0 || SrcAlign >= DstAlign) && 5319 "Expecting memcpy / memset source to meet alignment requirement!"); 5320 // If 'SrcAlign' is zero, that means the memory operation does not need to 5321 // load the value, i.e. memset or memcpy from constant string. Otherwise, 5322 // it's the inferred alignment of the source. 'DstAlign', on the other hand, 5323 // is the specified alignment of the memory operation. If it is zero, that 5324 // means it's possible to change the alignment of the destination. 5325 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does 5326 // not need to be loaded. 5327 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign, 5328 IsMemset, ZeroMemset, MemcpyStrSrc, 5329 DAG.getMachineFunction()); 5330 5331 if (VT == MVT::Other) { 5332 // Use the largest integer type whose alignment constraints are satisfied. 5333 // We only need to check DstAlign here as SrcAlign is always greater or 5334 // equal to DstAlign (or zero). 5335 VT = MVT::i64; 5336 while (DstAlign && DstAlign < VT.getSizeInBits() / 8 && 5337 !TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign)) 5338 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 5339 assert(VT.isInteger()); 5340 5341 // Find the largest legal integer type. 5342 MVT LVT = MVT::i64; 5343 while (!TLI.isTypeLegal(LVT)) 5344 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 5345 assert(LVT.isInteger()); 5346 5347 // If the type we've chosen is larger than the largest legal integer type 5348 // then use that instead. 5349 if (VT.bitsGT(LVT)) 5350 VT = LVT; 5351 } 5352 5353 unsigned NumMemOps = 0; 5354 while (Size != 0) { 5355 unsigned VTSize = VT.getSizeInBits() / 8; 5356 while (VTSize > Size) { 5357 // For now, only use non-vector load / store's for the left-over pieces. 5358 EVT NewVT = VT; 5359 unsigned NewVTSize; 5360 5361 bool Found = false; 5362 if (VT.isVector() || VT.isFloatingPoint()) { 5363 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 5364 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) && 5365 TLI.isSafeMemOpType(NewVT.getSimpleVT())) 5366 Found = true; 5367 else if (NewVT == MVT::i64 && 5368 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 5369 TLI.isSafeMemOpType(MVT::f64)) { 5370 // i64 is usually not legal on 32-bit targets, but f64 may be. 5371 NewVT = MVT::f64; 5372 Found = true; 5373 } 5374 } 5375 5376 if (!Found) { 5377 do { 5378 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 5379 if (NewVT == MVT::i8) 5380 break; 5381 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT())); 5382 } 5383 NewVTSize = NewVT.getSizeInBits() / 8; 5384 5385 // If the new VT cannot cover all of the remaining bits, then consider 5386 // issuing a (or a pair of) unaligned and overlapping load / store. 5387 // FIXME: Only does this for 64-bit or more since we don't have proper 5388 // cost model for unaligned load / store. 5389 bool Fast; 5390 if (NumMemOps && AllowOverlap && 5391 VTSize >= 8 && NewVTSize < Size && 5392 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast) 5393 VTSize = Size; 5394 else { 5395 VT = NewVT; 5396 VTSize = NewVTSize; 5397 } 5398 } 5399 5400 if (++NumMemOps > Limit) 5401 return false; 5402 5403 MemOps.push_back(VT); 5404 Size -= VTSize; 5405 } 5406 5407 return true; 5408 } 5409 5410 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) { 5411 // On Darwin, -Os means optimize for size without hurting performance, so 5412 // only really optimize for size when -Oz (MinSize) is used. 5413 if (MF.getTarget().getTargetTriple().isOSDarwin()) 5414 return MF.getFunction().optForMinSize(); 5415 return MF.getFunction().optForSize(); 5416 } 5417 5418 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 5419 SmallVector<SDValue, 32> &OutChains, unsigned From, 5420 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 5421 SmallVector<SDValue, 16> &OutStoreChains) { 5422 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 5423 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 5424 SmallVector<SDValue, 16> GluedLoadChains; 5425 for (unsigned i = From; i < To; ++i) { 5426 OutChains.push_back(OutLoadChains[i]); 5427 GluedLoadChains.push_back(OutLoadChains[i]); 5428 } 5429 5430 // Chain for all loads. 5431 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 5432 GluedLoadChains); 5433 5434 for (unsigned i = From; i < To; ++i) { 5435 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 5436 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 5437 ST->getBasePtr(), ST->getMemoryVT(), 5438 ST->getMemOperand()); 5439 OutChains.push_back(NewStore); 5440 } 5441 } 5442 5443 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 5444 SDValue Chain, SDValue Dst, SDValue Src, 5445 uint64_t Size, unsigned Align, 5446 bool isVol, bool AlwaysInline, 5447 MachinePointerInfo DstPtrInfo, 5448 MachinePointerInfo SrcPtrInfo) { 5449 // Turn a memcpy of undef to nop. 5450 if (Src.isUndef()) 5451 return Chain; 5452 5453 // Expand memcpy to a series of load and store ops if the size operand falls 5454 // below a certain threshold. 5455 // TODO: In the AlwaysInline case, if the size is big then generate a loop 5456 // rather than maybe a humongous number of loads and stores. 5457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5458 const DataLayout &DL = DAG.getDataLayout(); 5459 LLVMContext &C = *DAG.getContext(); 5460 std::vector<EVT> MemOps; 5461 bool DstAlignCanChange = false; 5462 MachineFunction &MF = DAG.getMachineFunction(); 5463 MachineFrameInfo &MFI = MF.getFrameInfo(); 5464 bool OptSize = shouldLowerMemFuncForSize(MF); 5465 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 5466 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 5467 DstAlignCanChange = true; 5468 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 5469 if (Align > SrcAlign) 5470 SrcAlign = Align; 5471 ConstantDataArraySlice Slice; 5472 bool CopyFromConstant = isMemSrcFromConstant(Src, Slice); 5473 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 5474 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 5475 5476 if (!FindOptimalMemOpLowering(MemOps, Limit, Size, 5477 (DstAlignCanChange ? 0 : Align), 5478 (isZeroConstant ? 0 : SrcAlign), 5479 false, false, CopyFromConstant, true, 5480 DstPtrInfo.getAddrSpace(), 5481 SrcPtrInfo.getAddrSpace(), 5482 DAG, TLI)) 5483 return SDValue(); 5484 5485 if (DstAlignCanChange) { 5486 Type *Ty = MemOps[0].getTypeForEVT(C); 5487 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty); 5488 5489 // Don't promote to an alignment that would require dynamic stack 5490 // realignment. 5491 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 5492 if (!TRI->needsStackRealignment(MF)) 5493 while (NewAlign > Align && 5494 DL.exceedsNaturalStackAlignment(NewAlign)) 5495 NewAlign /= 2; 5496 5497 if (NewAlign > Align) { 5498 // Give the stack frame object a larger alignment if needed. 5499 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign) 5500 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 5501 Align = NewAlign; 5502 } 5503 } 5504 5505 MachineMemOperand::Flags MMOFlags = 5506 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 5507 SmallVector<SDValue, 16> OutLoadChains; 5508 SmallVector<SDValue, 16> OutStoreChains; 5509 SmallVector<SDValue, 32> OutChains; 5510 unsigned NumMemOps = MemOps.size(); 5511 uint64_t SrcOff = 0, DstOff = 0; 5512 for (unsigned i = 0; i != NumMemOps; ++i) { 5513 EVT VT = MemOps[i]; 5514 unsigned VTSize = VT.getSizeInBits() / 8; 5515 SDValue Value, Store; 5516 5517 if (VTSize > Size) { 5518 // Issuing an unaligned load / store pair that overlaps with the previous 5519 // pair. Adjust the offset accordingly. 5520 assert(i == NumMemOps-1 && i != 0); 5521 SrcOff -= VTSize - Size; 5522 DstOff -= VTSize - Size; 5523 } 5524 5525 if (CopyFromConstant && 5526 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 5527 // It's unlikely a store of a vector immediate can be done in a single 5528 // instruction. It would require a load from a constantpool first. 5529 // We only handle zero vectors here. 5530 // FIXME: Handle other cases where store of vector immediate is done in 5531 // a single instruction. 5532 ConstantDataArraySlice SubSlice; 5533 if (SrcOff < Slice.Length) { 5534 SubSlice = Slice; 5535 SubSlice.move(SrcOff); 5536 } else { 5537 // This is an out-of-bounds access and hence UB. Pretend we read zero. 5538 SubSlice.Array = nullptr; 5539 SubSlice.Offset = 0; 5540 SubSlice.Length = VTSize; 5541 } 5542 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 5543 if (Value.getNode()) { 5544 Store = DAG.getStore(Chain, dl, Value, 5545 DAG.getMemBasePlusOffset(Dst, DstOff, dl), 5546 DstPtrInfo.getWithOffset(DstOff), Align, 5547 MMOFlags); 5548 OutChains.push_back(Store); 5549 } 5550 } 5551 5552 if (!Store.getNode()) { 5553 // The type might not be legal for the target. This should only happen 5554 // if the type is smaller than a legal type, as on PPC, so the right 5555 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 5556 // to Load/Store if NVT==VT. 5557 // FIXME does the case above also need this? 5558 EVT NVT = TLI.getTypeToTransformTo(C, VT); 5559 assert(NVT.bitsGE(VT)); 5560 5561 bool isDereferenceable = 5562 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 5563 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 5564 if (isDereferenceable) 5565 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 5566 5567 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain, 5568 DAG.getMemBasePlusOffset(Src, SrcOff, dl), 5569 SrcPtrInfo.getWithOffset(SrcOff), VT, 5570 MinAlign(SrcAlign, SrcOff), SrcMMOFlags); 5571 OutLoadChains.push_back(Value.getValue(1)); 5572 5573 Store = DAG.getTruncStore( 5574 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl), 5575 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags); 5576 OutStoreChains.push_back(Store); 5577 } 5578 SrcOff += VTSize; 5579 DstOff += VTSize; 5580 Size -= VTSize; 5581 } 5582 5583 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 5584 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 5585 unsigned NumLdStInMemcpy = OutStoreChains.size(); 5586 5587 if (NumLdStInMemcpy) { 5588 // It may be that memcpy might be converted to memset if it's memcpy 5589 // of constants. In such a case, we won't have loads and stores, but 5590 // just stores. In the absence of loads, there is nothing to gang up. 5591 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 5592 // If target does not care, just leave as it. 5593 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 5594 OutChains.push_back(OutLoadChains[i]); 5595 OutChains.push_back(OutStoreChains[i]); 5596 } 5597 } else { 5598 // Ld/St less than/equal limit set by target. 5599 if (NumLdStInMemcpy <= GluedLdStLimit) { 5600 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 5601 NumLdStInMemcpy, OutLoadChains, 5602 OutStoreChains); 5603 } else { 5604 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 5605 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 5606 unsigned GlueIter = 0; 5607 5608 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 5609 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 5610 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 5611 5612 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 5613 OutLoadChains, OutStoreChains); 5614 GlueIter += GluedLdStLimit; 5615 } 5616 5617 // Residual ld/st. 5618 if (RemainingLdStInMemcpy) { 5619 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 5620 RemainingLdStInMemcpy, OutLoadChains, 5621 OutStoreChains); 5622 } 5623 } 5624 } 5625 } 5626 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 5627 } 5628 5629 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 5630 SDValue Chain, SDValue Dst, SDValue Src, 5631 uint64_t Size, unsigned Align, 5632 bool isVol, bool AlwaysInline, 5633 MachinePointerInfo DstPtrInfo, 5634 MachinePointerInfo SrcPtrInfo) { 5635 // Turn a memmove of undef to nop. 5636 if (Src.isUndef()) 5637 return Chain; 5638 5639 // Expand memmove to a series of load and store ops if the size operand falls 5640 // below a certain threshold. 5641 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5642 const DataLayout &DL = DAG.getDataLayout(); 5643 LLVMContext &C = *DAG.getContext(); 5644 std::vector<EVT> MemOps; 5645 bool DstAlignCanChange = false; 5646 MachineFunction &MF = DAG.getMachineFunction(); 5647 MachineFrameInfo &MFI = MF.getFrameInfo(); 5648 bool OptSize = shouldLowerMemFuncForSize(MF); 5649 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 5650 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 5651 DstAlignCanChange = true; 5652 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 5653 if (Align > SrcAlign) 5654 SrcAlign = Align; 5655 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 5656 5657 if (!FindOptimalMemOpLowering(MemOps, Limit, Size, 5658 (DstAlignCanChange ? 0 : Align), SrcAlign, 5659 false, false, false, false, 5660 DstPtrInfo.getAddrSpace(), 5661 SrcPtrInfo.getAddrSpace(), 5662 DAG, TLI)) 5663 return SDValue(); 5664 5665 if (DstAlignCanChange) { 5666 Type *Ty = MemOps[0].getTypeForEVT(C); 5667 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty); 5668 if (NewAlign > Align) { 5669 // Give the stack frame object a larger alignment if needed. 5670 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign) 5671 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 5672 Align = NewAlign; 5673 } 5674 } 5675 5676 MachineMemOperand::Flags MMOFlags = 5677 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 5678 uint64_t SrcOff = 0, DstOff = 0; 5679 SmallVector<SDValue, 8> LoadValues; 5680 SmallVector<SDValue, 8> LoadChains; 5681 SmallVector<SDValue, 8> OutChains; 5682 unsigned NumMemOps = MemOps.size(); 5683 for (unsigned i = 0; i < NumMemOps; i++) { 5684 EVT VT = MemOps[i]; 5685 unsigned VTSize = VT.getSizeInBits() / 8; 5686 SDValue Value; 5687 5688 bool isDereferenceable = 5689 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 5690 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 5691 if (isDereferenceable) 5692 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 5693 5694 Value = 5695 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl), 5696 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags); 5697 LoadValues.push_back(Value); 5698 LoadChains.push_back(Value.getValue(1)); 5699 SrcOff += VTSize; 5700 } 5701 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 5702 OutChains.clear(); 5703 for (unsigned i = 0; i < NumMemOps; i++) { 5704 EVT VT = MemOps[i]; 5705 unsigned VTSize = VT.getSizeInBits() / 8; 5706 SDValue Store; 5707 5708 Store = DAG.getStore(Chain, dl, LoadValues[i], 5709 DAG.getMemBasePlusOffset(Dst, DstOff, dl), 5710 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags); 5711 OutChains.push_back(Store); 5712 DstOff += VTSize; 5713 } 5714 5715 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 5716 } 5717 5718 /// Lower the call to 'memset' intrinsic function into a series of store 5719 /// operations. 5720 /// 5721 /// \param DAG Selection DAG where lowered code is placed. 5722 /// \param dl Link to corresponding IR location. 5723 /// \param Chain Control flow dependency. 5724 /// \param Dst Pointer to destination memory location. 5725 /// \param Src Value of byte to write into the memory. 5726 /// \param Size Number of bytes to write. 5727 /// \param Align Alignment of the destination in bytes. 5728 /// \param isVol True if destination is volatile. 5729 /// \param DstPtrInfo IR information on the memory pointer. 5730 /// \returns New head in the control flow, if lowering was successful, empty 5731 /// SDValue otherwise. 5732 /// 5733 /// The function tries to replace 'llvm.memset' intrinsic with several store 5734 /// operations and value calculation code. This is usually profitable for small 5735 /// memory size. 5736 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 5737 SDValue Chain, SDValue Dst, SDValue Src, 5738 uint64_t Size, unsigned Align, bool isVol, 5739 MachinePointerInfo DstPtrInfo) { 5740 // Turn a memset of undef to nop. 5741 if (Src.isUndef()) 5742 return Chain; 5743 5744 // Expand memset to a series of load/store ops if the size operand 5745 // falls below a certain threshold. 5746 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5747 std::vector<EVT> MemOps; 5748 bool DstAlignCanChange = false; 5749 MachineFunction &MF = DAG.getMachineFunction(); 5750 MachineFrameInfo &MFI = MF.getFrameInfo(); 5751 bool OptSize = shouldLowerMemFuncForSize(MF); 5752 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 5753 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 5754 DstAlignCanChange = true; 5755 bool IsZeroVal = 5756 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 5757 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize), 5758 Size, (DstAlignCanChange ? 0 : Align), 0, 5759 true, IsZeroVal, false, true, 5760 DstPtrInfo.getAddrSpace(), ~0u, 5761 DAG, TLI)) 5762 return SDValue(); 5763 5764 if (DstAlignCanChange) { 5765 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 5766 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty); 5767 if (NewAlign > Align) { 5768 // Give the stack frame object a larger alignment if needed. 5769 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign) 5770 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 5771 Align = NewAlign; 5772 } 5773 } 5774 5775 SmallVector<SDValue, 8> OutChains; 5776 uint64_t DstOff = 0; 5777 unsigned NumMemOps = MemOps.size(); 5778 5779 // Find the largest store and generate the bit pattern for it. 5780 EVT LargestVT = MemOps[0]; 5781 for (unsigned i = 1; i < NumMemOps; i++) 5782 if (MemOps[i].bitsGT(LargestVT)) 5783 LargestVT = MemOps[i]; 5784 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 5785 5786 for (unsigned i = 0; i < NumMemOps; i++) { 5787 EVT VT = MemOps[i]; 5788 unsigned VTSize = VT.getSizeInBits() / 8; 5789 if (VTSize > Size) { 5790 // Issuing an unaligned load / store pair that overlaps with the previous 5791 // pair. Adjust the offset accordingly. 5792 assert(i == NumMemOps-1 && i != 0); 5793 DstOff -= VTSize - Size; 5794 } 5795 5796 // If this store is smaller than the largest store see whether we can get 5797 // the smaller value for free with a truncate. 5798 SDValue Value = MemSetValue; 5799 if (VT.bitsLT(LargestVT)) { 5800 if (!LargestVT.isVector() && !VT.isVector() && 5801 TLI.isTruncateFree(LargestVT, VT)) 5802 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 5803 else 5804 Value = getMemsetValue(Src, VT, DAG, dl); 5805 } 5806 assert(Value.getValueType() == VT && "Value with wrong type."); 5807 SDValue Store = DAG.getStore( 5808 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl), 5809 DstPtrInfo.getWithOffset(DstOff), Align, 5810 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone); 5811 OutChains.push_back(Store); 5812 DstOff += VT.getSizeInBits() / 8; 5813 Size -= VTSize; 5814 } 5815 5816 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 5817 } 5818 5819 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 5820 unsigned AS) { 5821 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 5822 // pointer operands can be losslessly bitcasted to pointers of address space 0 5823 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) { 5824 report_fatal_error("cannot lower memory intrinsic in address space " + 5825 Twine(AS)); 5826 } 5827 } 5828 5829 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 5830 SDValue Src, SDValue Size, unsigned Align, 5831 bool isVol, bool AlwaysInline, bool isTailCall, 5832 MachinePointerInfo DstPtrInfo, 5833 MachinePointerInfo SrcPtrInfo) { 5834 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 5835 5836 // Check to see if we should lower the memcpy to loads and stores first. 5837 // For cases within the target-specified limits, this is the best choice. 5838 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 5839 if (ConstantSize) { 5840 // Memcpy with size zero? Just return the original chain. 5841 if (ConstantSize->isNullValue()) 5842 return Chain; 5843 5844 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 5845 ConstantSize->getZExtValue(),Align, 5846 isVol, false, DstPtrInfo, SrcPtrInfo); 5847 if (Result.getNode()) 5848 return Result; 5849 } 5850 5851 // Then check to see if we should lower the memcpy with target-specific 5852 // code. If the target chooses to do this, this is the next best. 5853 if (TSI) { 5854 SDValue Result = TSI->EmitTargetCodeForMemcpy( 5855 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline, 5856 DstPtrInfo, SrcPtrInfo); 5857 if (Result.getNode()) 5858 return Result; 5859 } 5860 5861 // If we really need inline code and the target declined to provide it, 5862 // use a (potentially long) sequence of loads and stores. 5863 if (AlwaysInline) { 5864 assert(ConstantSize && "AlwaysInline requires a constant size!"); 5865 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 5866 ConstantSize->getZExtValue(), Align, isVol, 5867 true, DstPtrInfo, SrcPtrInfo); 5868 } 5869 5870 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 5871 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 5872 5873 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 5874 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 5875 // respect volatile, so they may do things like read or write memory 5876 // beyond the given memory regions. But fixing this isn't easy, and most 5877 // people don't care. 5878 5879 // Emit a library call. 5880 TargetLowering::ArgListTy Args; 5881 TargetLowering::ArgListEntry Entry; 5882 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 5883 Entry.Node = Dst; Args.push_back(Entry); 5884 Entry.Node = Src; Args.push_back(Entry); 5885 Entry.Node = Size; Args.push_back(Entry); 5886 // FIXME: pass in SDLoc 5887 TargetLowering::CallLoweringInfo CLI(*this); 5888 CLI.setDebugLoc(dl) 5889 .setChain(Chain) 5890 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 5891 Dst.getValueType().getTypeForEVT(*getContext()), 5892 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 5893 TLI->getPointerTy(getDataLayout())), 5894 std::move(Args)) 5895 .setDiscardResult() 5896 .setTailCall(isTailCall); 5897 5898 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 5899 return CallResult.second; 5900 } 5901 5902 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 5903 SDValue Dst, unsigned DstAlign, 5904 SDValue Src, unsigned SrcAlign, 5905 SDValue Size, Type *SizeTy, 5906 unsigned ElemSz, bool isTailCall, 5907 MachinePointerInfo DstPtrInfo, 5908 MachinePointerInfo SrcPtrInfo) { 5909 // Emit a library call. 5910 TargetLowering::ArgListTy Args; 5911 TargetLowering::ArgListEntry Entry; 5912 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 5913 Entry.Node = Dst; 5914 Args.push_back(Entry); 5915 5916 Entry.Node = Src; 5917 Args.push_back(Entry); 5918 5919 Entry.Ty = SizeTy; 5920 Entry.Node = Size; 5921 Args.push_back(Entry); 5922 5923 RTLIB::Libcall LibraryCall = 5924 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 5925 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 5926 report_fatal_error("Unsupported element size"); 5927 5928 TargetLowering::CallLoweringInfo CLI(*this); 5929 CLI.setDebugLoc(dl) 5930 .setChain(Chain) 5931 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 5932 Type::getVoidTy(*getContext()), 5933 getExternalSymbol(TLI->getLibcallName(LibraryCall), 5934 TLI->getPointerTy(getDataLayout())), 5935 std::move(Args)) 5936 .setDiscardResult() 5937 .setTailCall(isTailCall); 5938 5939 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 5940 return CallResult.second; 5941 } 5942 5943 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 5944 SDValue Src, SDValue Size, unsigned Align, 5945 bool isVol, bool isTailCall, 5946 MachinePointerInfo DstPtrInfo, 5947 MachinePointerInfo SrcPtrInfo) { 5948 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 5949 5950 // Check to see if we should lower the memmove to loads and stores first. 5951 // For cases within the target-specified limits, this is the best choice. 5952 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 5953 if (ConstantSize) { 5954 // Memmove with size zero? Just return the original chain. 5955 if (ConstantSize->isNullValue()) 5956 return Chain; 5957 5958 SDValue Result = 5959 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src, 5960 ConstantSize->getZExtValue(), Align, isVol, 5961 false, DstPtrInfo, SrcPtrInfo); 5962 if (Result.getNode()) 5963 return Result; 5964 } 5965 5966 // Then check to see if we should lower the memmove with target-specific 5967 // code. If the target chooses to do this, this is the next best. 5968 if (TSI) { 5969 SDValue Result = TSI->EmitTargetCodeForMemmove( 5970 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo); 5971 if (Result.getNode()) 5972 return Result; 5973 } 5974 5975 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 5976 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 5977 5978 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 5979 // not be safe. See memcpy above for more details. 5980 5981 // Emit a library call. 5982 TargetLowering::ArgListTy Args; 5983 TargetLowering::ArgListEntry Entry; 5984 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 5985 Entry.Node = Dst; Args.push_back(Entry); 5986 Entry.Node = Src; Args.push_back(Entry); 5987 Entry.Node = Size; Args.push_back(Entry); 5988 // FIXME: pass in SDLoc 5989 TargetLowering::CallLoweringInfo CLI(*this); 5990 CLI.setDebugLoc(dl) 5991 .setChain(Chain) 5992 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 5993 Dst.getValueType().getTypeForEVT(*getContext()), 5994 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 5995 TLI->getPointerTy(getDataLayout())), 5996 std::move(Args)) 5997 .setDiscardResult() 5998 .setTailCall(isTailCall); 5999 6000 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6001 return CallResult.second; 6002 } 6003 6004 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 6005 SDValue Dst, unsigned DstAlign, 6006 SDValue Src, unsigned SrcAlign, 6007 SDValue Size, Type *SizeTy, 6008 unsigned ElemSz, bool isTailCall, 6009 MachinePointerInfo DstPtrInfo, 6010 MachinePointerInfo SrcPtrInfo) { 6011 // Emit a library call. 6012 TargetLowering::ArgListTy Args; 6013 TargetLowering::ArgListEntry Entry; 6014 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6015 Entry.Node = Dst; 6016 Args.push_back(Entry); 6017 6018 Entry.Node = Src; 6019 Args.push_back(Entry); 6020 6021 Entry.Ty = SizeTy; 6022 Entry.Node = Size; 6023 Args.push_back(Entry); 6024 6025 RTLIB::Libcall LibraryCall = 6026 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6027 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6028 report_fatal_error("Unsupported element size"); 6029 6030 TargetLowering::CallLoweringInfo CLI(*this); 6031 CLI.setDebugLoc(dl) 6032 .setChain(Chain) 6033 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6034 Type::getVoidTy(*getContext()), 6035 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6036 TLI->getPointerTy(getDataLayout())), 6037 std::move(Args)) 6038 .setDiscardResult() 6039 .setTailCall(isTailCall); 6040 6041 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6042 return CallResult.second; 6043 } 6044 6045 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 6046 SDValue Src, SDValue Size, unsigned Align, 6047 bool isVol, bool isTailCall, 6048 MachinePointerInfo DstPtrInfo) { 6049 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 6050 6051 // Check to see if we should lower the memset to stores first. 6052 // For cases within the target-specified limits, this is the best choice. 6053 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6054 if (ConstantSize) { 6055 // Memset with size zero? Just return the original chain. 6056 if (ConstantSize->isNullValue()) 6057 return Chain; 6058 6059 SDValue Result = 6060 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), 6061 Align, isVol, DstPtrInfo); 6062 6063 if (Result.getNode()) 6064 return Result; 6065 } 6066 6067 // Then check to see if we should lower the memset with target-specific 6068 // code. If the target chooses to do this, this is the next best. 6069 if (TSI) { 6070 SDValue Result = TSI->EmitTargetCodeForMemset( 6071 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo); 6072 if (Result.getNode()) 6073 return Result; 6074 } 6075 6076 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6077 6078 // Emit a library call. 6079 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext()); 6080 TargetLowering::ArgListTy Args; 6081 TargetLowering::ArgListEntry Entry; 6082 Entry.Node = Dst; Entry.Ty = IntPtrTy; 6083 Args.push_back(Entry); 6084 Entry.Node = Src; 6085 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 6086 Args.push_back(Entry); 6087 Entry.Node = Size; 6088 Entry.Ty = IntPtrTy; 6089 Args.push_back(Entry); 6090 6091 // FIXME: pass in SDLoc 6092 TargetLowering::CallLoweringInfo CLI(*this); 6093 CLI.setDebugLoc(dl) 6094 .setChain(Chain) 6095 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 6096 Dst.getValueType().getTypeForEVT(*getContext()), 6097 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 6098 TLI->getPointerTy(getDataLayout())), 6099 std::move(Args)) 6100 .setDiscardResult() 6101 .setTailCall(isTailCall); 6102 6103 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6104 return CallResult.second; 6105 } 6106 6107 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 6108 SDValue Dst, unsigned DstAlign, 6109 SDValue Value, SDValue Size, Type *SizeTy, 6110 unsigned ElemSz, bool isTailCall, 6111 MachinePointerInfo DstPtrInfo) { 6112 // Emit a library call. 6113 TargetLowering::ArgListTy Args; 6114 TargetLowering::ArgListEntry Entry; 6115 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6116 Entry.Node = Dst; 6117 Args.push_back(Entry); 6118 6119 Entry.Ty = Type::getInt8Ty(*getContext()); 6120 Entry.Node = Value; 6121 Args.push_back(Entry); 6122 6123 Entry.Ty = SizeTy; 6124 Entry.Node = Size; 6125 Args.push_back(Entry); 6126 6127 RTLIB::Libcall LibraryCall = 6128 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6129 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6130 report_fatal_error("Unsupported element size"); 6131 6132 TargetLowering::CallLoweringInfo CLI(*this); 6133 CLI.setDebugLoc(dl) 6134 .setChain(Chain) 6135 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6136 Type::getVoidTy(*getContext()), 6137 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6138 TLI->getPointerTy(getDataLayout())), 6139 std::move(Args)) 6140 .setDiscardResult() 6141 .setTailCall(isTailCall); 6142 6143 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6144 return CallResult.second; 6145 } 6146 6147 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6148 SDVTList VTList, ArrayRef<SDValue> Ops, 6149 MachineMemOperand *MMO) { 6150 FoldingSetNodeID ID; 6151 ID.AddInteger(MemVT.getRawBits()); 6152 AddNodeIDNode(ID, Opcode, VTList, Ops); 6153 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6154 void* IP = nullptr; 6155 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6156 cast<AtomicSDNode>(E)->refineAlignment(MMO); 6157 return SDValue(E, 0); 6158 } 6159 6160 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6161 VTList, MemVT, MMO); 6162 createOperands(N, Ops); 6163 6164 CSEMap.InsertNode(N, IP); 6165 InsertNode(N); 6166 return SDValue(N, 0); 6167 } 6168 6169 SDValue SelectionDAG::getAtomicCmpSwap( 6170 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, 6171 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo, 6172 unsigned Alignment, AtomicOrdering SuccessOrdering, 6173 AtomicOrdering FailureOrdering, SyncScope::ID SSID) { 6174 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 6175 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 6176 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 6177 6178 if (Alignment == 0) // Ensure that codegen never sees alignment 0 6179 Alignment = getEVTAlignment(MemVT); 6180 6181 MachineFunction &MF = getMachineFunction(); 6182 6183 // FIXME: Volatile isn't really correct; we should keep track of atomic 6184 // orderings in the memoperand. 6185 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad | 6186 MachineMemOperand::MOStore; 6187 MachineMemOperand *MMO = 6188 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment, 6189 AAMDNodes(), nullptr, SSID, SuccessOrdering, 6190 FailureOrdering); 6191 6192 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO); 6193 } 6194 6195 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 6196 EVT MemVT, SDVTList VTs, SDValue Chain, 6197 SDValue Ptr, SDValue Cmp, SDValue Swp, 6198 MachineMemOperand *MMO) { 6199 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 6200 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 6201 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 6202 6203 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 6204 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6205 } 6206 6207 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6208 SDValue Chain, SDValue Ptr, SDValue Val, 6209 const Value *PtrVal, unsigned Alignment, 6210 AtomicOrdering Ordering, 6211 SyncScope::ID SSID) { 6212 if (Alignment == 0) // Ensure that codegen never sees alignment 0 6213 Alignment = getEVTAlignment(MemVT); 6214 6215 MachineFunction &MF = getMachineFunction(); 6216 // An atomic store does not load. An atomic load does not store. 6217 // (An atomicrmw obviously both loads and stores.) 6218 // For now, atomics are considered to be volatile always, and they are 6219 // chained as such. 6220 // FIXME: Volatile isn't really correct; we should keep track of atomic 6221 // orderings in the memoperand. 6222 auto Flags = MachineMemOperand::MOVolatile; 6223 if (Opcode != ISD::ATOMIC_STORE) 6224 Flags |= MachineMemOperand::MOLoad; 6225 if (Opcode != ISD::ATOMIC_LOAD) 6226 Flags |= MachineMemOperand::MOStore; 6227 6228 MachineMemOperand *MMO = 6229 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags, 6230 MemVT.getStoreSize(), Alignment, AAMDNodes(), 6231 nullptr, SSID, Ordering); 6232 6233 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO); 6234 } 6235 6236 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6237 SDValue Chain, SDValue Ptr, SDValue Val, 6238 MachineMemOperand *MMO) { 6239 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 6240 Opcode == ISD::ATOMIC_LOAD_SUB || 6241 Opcode == ISD::ATOMIC_LOAD_AND || 6242 Opcode == ISD::ATOMIC_LOAD_CLR || 6243 Opcode == ISD::ATOMIC_LOAD_OR || 6244 Opcode == ISD::ATOMIC_LOAD_XOR || 6245 Opcode == ISD::ATOMIC_LOAD_NAND || 6246 Opcode == ISD::ATOMIC_LOAD_MIN || 6247 Opcode == ISD::ATOMIC_LOAD_MAX || 6248 Opcode == ISD::ATOMIC_LOAD_UMIN || 6249 Opcode == ISD::ATOMIC_LOAD_UMAX || 6250 Opcode == ISD::ATOMIC_SWAP || 6251 Opcode == ISD::ATOMIC_STORE) && 6252 "Invalid Atomic Op"); 6253 6254 EVT VT = Val.getValueType(); 6255 6256 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 6257 getVTList(VT, MVT::Other); 6258 SDValue Ops[] = {Chain, Ptr, Val}; 6259 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6260 } 6261 6262 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6263 EVT VT, SDValue Chain, SDValue Ptr, 6264 MachineMemOperand *MMO) { 6265 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 6266 6267 SDVTList VTs = getVTList(VT, MVT::Other); 6268 SDValue Ops[] = {Chain, Ptr}; 6269 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6270 } 6271 6272 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 6273 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 6274 if (Ops.size() == 1) 6275 return Ops[0]; 6276 6277 SmallVector<EVT, 4> VTs; 6278 VTs.reserve(Ops.size()); 6279 for (unsigned i = 0; i < Ops.size(); ++i) 6280 VTs.push_back(Ops[i].getValueType()); 6281 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 6282 } 6283 6284 SDValue SelectionDAG::getMemIntrinsicNode( 6285 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 6286 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, 6287 MachineMemOperand::Flags Flags, unsigned Size) { 6288 if (Align == 0) // Ensure that codegen never sees alignment 0 6289 Align = getEVTAlignment(MemVT); 6290 6291 if (!Size) 6292 Size = MemVT.getStoreSize(); 6293 6294 MachineFunction &MF = getMachineFunction(); 6295 MachineMemOperand *MMO = 6296 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align); 6297 6298 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 6299 } 6300 6301 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 6302 SDVTList VTList, 6303 ArrayRef<SDValue> Ops, EVT MemVT, 6304 MachineMemOperand *MMO) { 6305 assert((Opcode == ISD::INTRINSIC_VOID || 6306 Opcode == ISD::INTRINSIC_W_CHAIN || 6307 Opcode == ISD::PREFETCH || 6308 Opcode == ISD::LIFETIME_START || 6309 Opcode == ISD::LIFETIME_END || 6310 ((int)Opcode <= std::numeric_limits<int>::max() && 6311 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 6312 "Opcode is not a memory-accessing opcode!"); 6313 6314 // Memoize the node unless it returns a flag. 6315 MemIntrinsicSDNode *N; 6316 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 6317 FoldingSetNodeID ID; 6318 AddNodeIDNode(ID, Opcode, VTList, Ops); 6319 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 6320 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 6321 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6322 void *IP = nullptr; 6323 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6324 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 6325 return SDValue(E, 0); 6326 } 6327 6328 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6329 VTList, MemVT, MMO); 6330 createOperands(N, Ops); 6331 6332 CSEMap.InsertNode(N, IP); 6333 } else { 6334 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6335 VTList, MemVT, MMO); 6336 createOperands(N, Ops); 6337 } 6338 InsertNode(N); 6339 return SDValue(N, 0); 6340 } 6341 6342 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 6343 /// MachinePointerInfo record from it. This is particularly useful because the 6344 /// code generator has many cases where it doesn't bother passing in a 6345 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 6346 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 6347 SelectionDAG &DAG, SDValue Ptr, 6348 int64_t Offset = 0) { 6349 // If this is FI+Offset, we can model it. 6350 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 6351 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 6352 FI->getIndex(), Offset); 6353 6354 // If this is (FI+Offset1)+Offset2, we can model it. 6355 if (Ptr.getOpcode() != ISD::ADD || 6356 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 6357 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 6358 return Info; 6359 6360 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 6361 return MachinePointerInfo::getFixedStack( 6362 DAG.getMachineFunction(), FI, 6363 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 6364 } 6365 6366 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 6367 /// MachinePointerInfo record from it. This is particularly useful because the 6368 /// code generator has many cases where it doesn't bother passing in a 6369 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 6370 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 6371 SelectionDAG &DAG, SDValue Ptr, 6372 SDValue OffsetOp) { 6373 // If the 'Offset' value isn't a constant, we can't handle this. 6374 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 6375 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 6376 if (OffsetOp.isUndef()) 6377 return InferPointerInfo(Info, DAG, Ptr); 6378 return Info; 6379 } 6380 6381 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 6382 EVT VT, const SDLoc &dl, SDValue Chain, 6383 SDValue Ptr, SDValue Offset, 6384 MachinePointerInfo PtrInfo, EVT MemVT, 6385 unsigned Alignment, 6386 MachineMemOperand::Flags MMOFlags, 6387 const AAMDNodes &AAInfo, const MDNode *Ranges) { 6388 assert(Chain.getValueType() == MVT::Other && 6389 "Invalid chain type"); 6390 if (Alignment == 0) // Ensure that codegen never sees alignment 0 6391 Alignment = getEVTAlignment(MemVT); 6392 6393 MMOFlags |= MachineMemOperand::MOLoad; 6394 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 6395 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 6396 // clients. 6397 if (PtrInfo.V.isNull()) 6398 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 6399 6400 MachineFunction &MF = getMachineFunction(); 6401 MachineMemOperand *MMO = MF.getMachineMemOperand( 6402 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges); 6403 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 6404 } 6405 6406 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 6407 EVT VT, const SDLoc &dl, SDValue Chain, 6408 SDValue Ptr, SDValue Offset, EVT MemVT, 6409 MachineMemOperand *MMO) { 6410 if (VT == MemVT) { 6411 ExtType = ISD::NON_EXTLOAD; 6412 } else if (ExtType == ISD::NON_EXTLOAD) { 6413 assert(VT == MemVT && "Non-extending load from different memory type!"); 6414 } else { 6415 // Extending load. 6416 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 6417 "Should only be an extending load, not truncating!"); 6418 assert(VT.isInteger() == MemVT.isInteger() && 6419 "Cannot convert from FP to Int or Int -> FP!"); 6420 assert(VT.isVector() == MemVT.isVector() && 6421 "Cannot use an ext load to convert to or from a vector!"); 6422 assert((!VT.isVector() || 6423 VT.getVectorNumElements() == MemVT.getVectorNumElements()) && 6424 "Cannot use an ext load to change the number of vector elements!"); 6425 } 6426 6427 bool Indexed = AM != ISD::UNINDEXED; 6428 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 6429 6430 SDVTList VTs = Indexed ? 6431 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 6432 SDValue Ops[] = { Chain, Ptr, Offset }; 6433 FoldingSetNodeID ID; 6434 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 6435 ID.AddInteger(MemVT.getRawBits()); 6436 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 6437 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 6438 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6439 void *IP = nullptr; 6440 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6441 cast<LoadSDNode>(E)->refineAlignment(MMO); 6442 return SDValue(E, 0); 6443 } 6444 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 6445 ExtType, MemVT, MMO); 6446 createOperands(N, Ops); 6447 6448 CSEMap.InsertNode(N, IP); 6449 InsertNode(N); 6450 SDValue V(N, 0); 6451 NewSDValueDbgMsg(V, "Creating new node: ", this); 6452 return V; 6453 } 6454 6455 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 6456 SDValue Ptr, MachinePointerInfo PtrInfo, 6457 unsigned Alignment, 6458 MachineMemOperand::Flags MMOFlags, 6459 const AAMDNodes &AAInfo, const MDNode *Ranges) { 6460 SDValue Undef = getUNDEF(Ptr.getValueType()); 6461 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 6462 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 6463 } 6464 6465 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 6466 SDValue Ptr, MachineMemOperand *MMO) { 6467 SDValue Undef = getUNDEF(Ptr.getValueType()); 6468 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 6469 VT, MMO); 6470 } 6471 6472 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 6473 EVT VT, SDValue Chain, SDValue Ptr, 6474 MachinePointerInfo PtrInfo, EVT MemVT, 6475 unsigned Alignment, 6476 MachineMemOperand::Flags MMOFlags, 6477 const AAMDNodes &AAInfo) { 6478 SDValue Undef = getUNDEF(Ptr.getValueType()); 6479 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 6480 MemVT, Alignment, MMOFlags, AAInfo); 6481 } 6482 6483 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 6484 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 6485 MachineMemOperand *MMO) { 6486 SDValue Undef = getUNDEF(Ptr.getValueType()); 6487 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 6488 MemVT, MMO); 6489 } 6490 6491 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 6492 SDValue Base, SDValue Offset, 6493 ISD::MemIndexedMode AM) { 6494 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 6495 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 6496 // Don't propagate the invariant or dereferenceable flags. 6497 auto MMOFlags = 6498 LD->getMemOperand()->getFlags() & 6499 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 6500 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 6501 LD->getChain(), Base, Offset, LD->getPointerInfo(), 6502 LD->getMemoryVT(), LD->getAlignment(), MMOFlags, 6503 LD->getAAInfo()); 6504 } 6505 6506 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 6507 SDValue Ptr, MachinePointerInfo PtrInfo, 6508 unsigned Alignment, 6509 MachineMemOperand::Flags MMOFlags, 6510 const AAMDNodes &AAInfo) { 6511 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 6512 if (Alignment == 0) // Ensure that codegen never sees alignment 0 6513 Alignment = getEVTAlignment(Val.getValueType()); 6514 6515 MMOFlags |= MachineMemOperand::MOStore; 6516 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 6517 6518 if (PtrInfo.V.isNull()) 6519 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 6520 6521 MachineFunction &MF = getMachineFunction(); 6522 MachineMemOperand *MMO = MF.getMachineMemOperand( 6523 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo); 6524 return getStore(Chain, dl, Val, Ptr, MMO); 6525 } 6526 6527 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 6528 SDValue Ptr, MachineMemOperand *MMO) { 6529 assert(Chain.getValueType() == MVT::Other && 6530 "Invalid chain type"); 6531 EVT VT = Val.getValueType(); 6532 SDVTList VTs = getVTList(MVT::Other); 6533 SDValue Undef = getUNDEF(Ptr.getValueType()); 6534 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 6535 FoldingSetNodeID ID; 6536 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 6537 ID.AddInteger(VT.getRawBits()); 6538 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 6539 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 6540 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6541 void *IP = nullptr; 6542 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6543 cast<StoreSDNode>(E)->refineAlignment(MMO); 6544 return SDValue(E, 0); 6545 } 6546 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 6547 ISD::UNINDEXED, false, VT, MMO); 6548 createOperands(N, Ops); 6549 6550 CSEMap.InsertNode(N, IP); 6551 InsertNode(N); 6552 SDValue V(N, 0); 6553 NewSDValueDbgMsg(V, "Creating new node: ", this); 6554 return V; 6555 } 6556 6557 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 6558 SDValue Ptr, MachinePointerInfo PtrInfo, 6559 EVT SVT, unsigned Alignment, 6560 MachineMemOperand::Flags MMOFlags, 6561 const AAMDNodes &AAInfo) { 6562 assert(Chain.getValueType() == MVT::Other && 6563 "Invalid chain type"); 6564 if (Alignment == 0) // Ensure that codegen never sees alignment 0 6565 Alignment = getEVTAlignment(SVT); 6566 6567 MMOFlags |= MachineMemOperand::MOStore; 6568 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 6569 6570 if (PtrInfo.V.isNull()) 6571 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 6572 6573 MachineFunction &MF = getMachineFunction(); 6574 MachineMemOperand *MMO = MF.getMachineMemOperand( 6575 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo); 6576 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 6577 } 6578 6579 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 6580 SDValue Ptr, EVT SVT, 6581 MachineMemOperand *MMO) { 6582 EVT VT = Val.getValueType(); 6583 6584 assert(Chain.getValueType() == MVT::Other && 6585 "Invalid chain type"); 6586 if (VT == SVT) 6587 return getStore(Chain, dl, Val, Ptr, MMO); 6588 6589 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 6590 "Should only be a truncating store, not extending!"); 6591 assert(VT.isInteger() == SVT.isInteger() && 6592 "Can't do FP-INT conversion!"); 6593 assert(VT.isVector() == SVT.isVector() && 6594 "Cannot use trunc store to convert to or from a vector!"); 6595 assert((!VT.isVector() || 6596 VT.getVectorNumElements() == SVT.getVectorNumElements()) && 6597 "Cannot use trunc store to change the number of vector elements!"); 6598 6599 SDVTList VTs = getVTList(MVT::Other); 6600 SDValue Undef = getUNDEF(Ptr.getValueType()); 6601 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 6602 FoldingSetNodeID ID; 6603 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 6604 ID.AddInteger(SVT.getRawBits()); 6605 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 6606 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 6607 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6608 void *IP = nullptr; 6609 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6610 cast<StoreSDNode>(E)->refineAlignment(MMO); 6611 return SDValue(E, 0); 6612 } 6613 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 6614 ISD::UNINDEXED, true, SVT, MMO); 6615 createOperands(N, Ops); 6616 6617 CSEMap.InsertNode(N, IP); 6618 InsertNode(N); 6619 SDValue V(N, 0); 6620 NewSDValueDbgMsg(V, "Creating new node: ", this); 6621 return V; 6622 } 6623 6624 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 6625 SDValue Base, SDValue Offset, 6626 ISD::MemIndexedMode AM) { 6627 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 6628 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 6629 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 6630 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 6631 FoldingSetNodeID ID; 6632 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 6633 ID.AddInteger(ST->getMemoryVT().getRawBits()); 6634 ID.AddInteger(ST->getRawSubclassData()); 6635 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 6636 void *IP = nullptr; 6637 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 6638 return SDValue(E, 0); 6639 6640 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 6641 ST->isTruncatingStore(), ST->getMemoryVT(), 6642 ST->getMemOperand()); 6643 createOperands(N, Ops); 6644 6645 CSEMap.InsertNode(N, IP); 6646 InsertNode(N); 6647 SDValue V(N, 0); 6648 NewSDValueDbgMsg(V, "Creating new node: ", this); 6649 return V; 6650 } 6651 6652 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 6653 SDValue Ptr, SDValue Mask, SDValue PassThru, 6654 EVT MemVT, MachineMemOperand *MMO, 6655 ISD::LoadExtType ExtTy, bool isExpanding) { 6656 SDVTList VTs = getVTList(VT, MVT::Other); 6657 SDValue Ops[] = { Chain, Ptr, Mask, PassThru }; 6658 FoldingSetNodeID ID; 6659 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 6660 ID.AddInteger(VT.getRawBits()); 6661 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 6662 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO)); 6663 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6664 void *IP = nullptr; 6665 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6666 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 6667 return SDValue(E, 0); 6668 } 6669 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 6670 ExtTy, isExpanding, MemVT, MMO); 6671 createOperands(N, Ops); 6672 6673 CSEMap.InsertNode(N, IP); 6674 InsertNode(N); 6675 SDValue V(N, 0); 6676 NewSDValueDbgMsg(V, "Creating new node: ", this); 6677 return V; 6678 } 6679 6680 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 6681 SDValue Val, SDValue Ptr, SDValue Mask, 6682 EVT MemVT, MachineMemOperand *MMO, 6683 bool IsTruncating, bool IsCompressing) { 6684 assert(Chain.getValueType() == MVT::Other && 6685 "Invalid chain type"); 6686 EVT VT = Val.getValueType(); 6687 SDVTList VTs = getVTList(MVT::Other); 6688 SDValue Ops[] = { Chain, Val, Ptr, Mask }; 6689 FoldingSetNodeID ID; 6690 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 6691 ID.AddInteger(VT.getRawBits()); 6692 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 6693 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO)); 6694 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6695 void *IP = nullptr; 6696 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6697 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 6698 return SDValue(E, 0); 6699 } 6700 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 6701 IsTruncating, IsCompressing, MemVT, MMO); 6702 createOperands(N, Ops); 6703 6704 CSEMap.InsertNode(N, IP); 6705 InsertNode(N); 6706 SDValue V(N, 0); 6707 NewSDValueDbgMsg(V, "Creating new node: ", this); 6708 return V; 6709 } 6710 6711 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl, 6712 ArrayRef<SDValue> Ops, 6713 MachineMemOperand *MMO) { 6714 assert(Ops.size() == 6 && "Incompatible number of operands"); 6715 6716 FoldingSetNodeID ID; 6717 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 6718 ID.AddInteger(VT.getRawBits()); 6719 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 6720 dl.getIROrder(), VTs, VT, MMO)); 6721 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6722 void *IP = nullptr; 6723 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6724 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 6725 return SDValue(E, 0); 6726 } 6727 6728 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 6729 VTs, VT, MMO); 6730 createOperands(N, Ops); 6731 6732 assert(N->getPassThru().getValueType() == N->getValueType(0) && 6733 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 6734 assert(N->getMask().getValueType().getVectorNumElements() == 6735 N->getValueType(0).getVectorNumElements() && 6736 "Vector width mismatch between mask and data"); 6737 assert(N->getIndex().getValueType().getVectorNumElements() >= 6738 N->getValueType(0).getVectorNumElements() && 6739 "Vector width mismatch between index and data"); 6740 assert(isa<ConstantSDNode>(N->getScale()) && 6741 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 6742 "Scale should be a constant power of 2"); 6743 6744 CSEMap.InsertNode(N, IP); 6745 InsertNode(N); 6746 SDValue V(N, 0); 6747 NewSDValueDbgMsg(V, "Creating new node: ", this); 6748 return V; 6749 } 6750 6751 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl, 6752 ArrayRef<SDValue> Ops, 6753 MachineMemOperand *MMO) { 6754 assert(Ops.size() == 6 && "Incompatible number of operands"); 6755 6756 FoldingSetNodeID ID; 6757 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 6758 ID.AddInteger(VT.getRawBits()); 6759 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 6760 dl.getIROrder(), VTs, VT, MMO)); 6761 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6762 void *IP = nullptr; 6763 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6764 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 6765 return SDValue(E, 0); 6766 } 6767 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 6768 VTs, VT, MMO); 6769 createOperands(N, Ops); 6770 6771 assert(N->getMask().getValueType().getVectorNumElements() == 6772 N->getValue().getValueType().getVectorNumElements() && 6773 "Vector width mismatch between mask and data"); 6774 assert(N->getIndex().getValueType().getVectorNumElements() >= 6775 N->getValue().getValueType().getVectorNumElements() && 6776 "Vector width mismatch between index and data"); 6777 assert(isa<ConstantSDNode>(N->getScale()) && 6778 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 6779 "Scale should be a constant power of 2"); 6780 6781 CSEMap.InsertNode(N, IP); 6782 InsertNode(N); 6783 SDValue V(N, 0); 6784 NewSDValueDbgMsg(V, "Creating new node: ", this); 6785 return V; 6786 } 6787 6788 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 6789 SDValue Ptr, SDValue SV, unsigned Align) { 6790 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 6791 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 6792 } 6793 6794 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6795 ArrayRef<SDUse> Ops) { 6796 switch (Ops.size()) { 6797 case 0: return getNode(Opcode, DL, VT); 6798 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 6799 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 6800 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 6801 default: break; 6802 } 6803 6804 // Copy from an SDUse array into an SDValue array for use with 6805 // the regular getNode logic. 6806 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 6807 return getNode(Opcode, DL, VT, NewOps); 6808 } 6809 6810 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6811 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 6812 unsigned NumOps = Ops.size(); 6813 switch (NumOps) { 6814 case 0: return getNode(Opcode, DL, VT); 6815 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 6816 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 6817 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 6818 default: break; 6819 } 6820 6821 switch (Opcode) { 6822 default: break; 6823 case ISD::BUILD_VECTOR: 6824 // Attempt to simplify BUILD_VECTOR. 6825 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6826 return V; 6827 break; 6828 case ISD::CONCAT_VECTORS: 6829 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 6830 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 6831 return V; 6832 break; 6833 case ISD::SELECT_CC: 6834 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 6835 assert(Ops[0].getValueType() == Ops[1].getValueType() && 6836 "LHS and RHS of condition must have same type!"); 6837 assert(Ops[2].getValueType() == Ops[3].getValueType() && 6838 "True and False arms of SelectCC must have same type!"); 6839 assert(Ops[2].getValueType() == VT && 6840 "select_cc node must be of same type as true and false value!"); 6841 break; 6842 case ISD::BR_CC: 6843 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 6844 assert(Ops[2].getValueType() == Ops[3].getValueType() && 6845 "LHS/RHS of comparison should match types!"); 6846 break; 6847 } 6848 6849 // Memoize nodes. 6850 SDNode *N; 6851 SDVTList VTs = getVTList(VT); 6852 6853 if (VT != MVT::Glue) { 6854 FoldingSetNodeID ID; 6855 AddNodeIDNode(ID, Opcode, VTs, Ops); 6856 void *IP = nullptr; 6857 6858 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 6859 return SDValue(E, 0); 6860 6861 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6862 createOperands(N, Ops); 6863 6864 CSEMap.InsertNode(N, IP); 6865 } else { 6866 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6867 createOperands(N, Ops); 6868 } 6869 6870 InsertNode(N); 6871 SDValue V(N, 0); 6872 NewSDValueDbgMsg(V, "Creating new node: ", this); 6873 return V; 6874 } 6875 6876 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 6877 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 6878 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 6879 } 6880 6881 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 6882 ArrayRef<SDValue> Ops) { 6883 if (VTList.NumVTs == 1) 6884 return getNode(Opcode, DL, VTList.VTs[0], Ops); 6885 6886 #if 0 6887 switch (Opcode) { 6888 // FIXME: figure out how to safely handle things like 6889 // int foo(int x) { return 1 << (x & 255); } 6890 // int bar() { return foo(256); } 6891 case ISD::SRA_PARTS: 6892 case ISD::SRL_PARTS: 6893 case ISD::SHL_PARTS: 6894 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 6895 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 6896 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 6897 else if (N3.getOpcode() == ISD::AND) 6898 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 6899 // If the and is only masking out bits that cannot effect the shift, 6900 // eliminate the and. 6901 unsigned NumBits = VT.getScalarSizeInBits()*2; 6902 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 6903 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 6904 } 6905 break; 6906 } 6907 #endif 6908 6909 // Memoize the node unless it returns a flag. 6910 SDNode *N; 6911 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 6912 FoldingSetNodeID ID; 6913 AddNodeIDNode(ID, Opcode, VTList, Ops); 6914 void *IP = nullptr; 6915 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 6916 return SDValue(E, 0); 6917 6918 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 6919 createOperands(N, Ops); 6920 CSEMap.InsertNode(N, IP); 6921 } else { 6922 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 6923 createOperands(N, Ops); 6924 } 6925 InsertNode(N); 6926 SDValue V(N, 0); 6927 NewSDValueDbgMsg(V, "Creating new node: ", this); 6928 return V; 6929 } 6930 6931 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 6932 SDVTList VTList) { 6933 return getNode(Opcode, DL, VTList, None); 6934 } 6935 6936 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 6937 SDValue N1) { 6938 SDValue Ops[] = { N1 }; 6939 return getNode(Opcode, DL, VTList, Ops); 6940 } 6941 6942 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 6943 SDValue N1, SDValue N2) { 6944 SDValue Ops[] = { N1, N2 }; 6945 return getNode(Opcode, DL, VTList, Ops); 6946 } 6947 6948 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 6949 SDValue N1, SDValue N2, SDValue N3) { 6950 SDValue Ops[] = { N1, N2, N3 }; 6951 return getNode(Opcode, DL, VTList, Ops); 6952 } 6953 6954 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 6955 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6956 SDValue Ops[] = { N1, N2, N3, N4 }; 6957 return getNode(Opcode, DL, VTList, Ops); 6958 } 6959 6960 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 6961 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6962 SDValue N5) { 6963 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6964 return getNode(Opcode, DL, VTList, Ops); 6965 } 6966 6967 SDVTList SelectionDAG::getVTList(EVT VT) { 6968 return makeVTList(SDNode::getValueTypeList(VT), 1); 6969 } 6970 6971 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 6972 FoldingSetNodeID ID; 6973 ID.AddInteger(2U); 6974 ID.AddInteger(VT1.getRawBits()); 6975 ID.AddInteger(VT2.getRawBits()); 6976 6977 void *IP = nullptr; 6978 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 6979 if (!Result) { 6980 EVT *Array = Allocator.Allocate<EVT>(2); 6981 Array[0] = VT1; 6982 Array[1] = VT2; 6983 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 6984 VTListMap.InsertNode(Result, IP); 6985 } 6986 return Result->getSDVTList(); 6987 } 6988 6989 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 6990 FoldingSetNodeID ID; 6991 ID.AddInteger(3U); 6992 ID.AddInteger(VT1.getRawBits()); 6993 ID.AddInteger(VT2.getRawBits()); 6994 ID.AddInteger(VT3.getRawBits()); 6995 6996 void *IP = nullptr; 6997 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 6998 if (!Result) { 6999 EVT *Array = Allocator.Allocate<EVT>(3); 7000 Array[0] = VT1; 7001 Array[1] = VT2; 7002 Array[2] = VT3; 7003 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 7004 VTListMap.InsertNode(Result, IP); 7005 } 7006 return Result->getSDVTList(); 7007 } 7008 7009 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 7010 FoldingSetNodeID ID; 7011 ID.AddInteger(4U); 7012 ID.AddInteger(VT1.getRawBits()); 7013 ID.AddInteger(VT2.getRawBits()); 7014 ID.AddInteger(VT3.getRawBits()); 7015 ID.AddInteger(VT4.getRawBits()); 7016 7017 void *IP = nullptr; 7018 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7019 if (!Result) { 7020 EVT *Array = Allocator.Allocate<EVT>(4); 7021 Array[0] = VT1; 7022 Array[1] = VT2; 7023 Array[2] = VT3; 7024 Array[3] = VT4; 7025 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 7026 VTListMap.InsertNode(Result, IP); 7027 } 7028 return Result->getSDVTList(); 7029 } 7030 7031 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 7032 unsigned NumVTs = VTs.size(); 7033 FoldingSetNodeID ID; 7034 ID.AddInteger(NumVTs); 7035 for (unsigned index = 0; index < NumVTs; index++) { 7036 ID.AddInteger(VTs[index].getRawBits()); 7037 } 7038 7039 void *IP = nullptr; 7040 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7041 if (!Result) { 7042 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 7043 std::copy(VTs.begin(), VTs.end(), Array); 7044 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 7045 VTListMap.InsertNode(Result, IP); 7046 } 7047 return Result->getSDVTList(); 7048 } 7049 7050 7051 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 7052 /// specified operands. If the resultant node already exists in the DAG, 7053 /// this does not modify the specified node, instead it returns the node that 7054 /// already exists. If the resultant node does not exist in the DAG, the 7055 /// input node is returned. As a degenerate case, if you specify the same 7056 /// input operands as the node already has, the input node is returned. 7057 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 7058 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 7059 7060 // Check to see if there is no change. 7061 if (Op == N->getOperand(0)) return N; 7062 7063 // See if the modified node already exists. 7064 void *InsertPos = nullptr; 7065 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 7066 return Existing; 7067 7068 // Nope it doesn't. Remove the node from its current place in the maps. 7069 if (InsertPos) 7070 if (!RemoveNodeFromCSEMaps(N)) 7071 InsertPos = nullptr; 7072 7073 // Now we update the operands. 7074 N->OperandList[0].set(Op); 7075 7076 updateDivergence(N); 7077 // If this gets put into a CSE map, add it. 7078 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7079 return N; 7080 } 7081 7082 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 7083 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 7084 7085 // Check to see if there is no change. 7086 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 7087 return N; // No operands changed, just return the input node. 7088 7089 // See if the modified node already exists. 7090 void *InsertPos = nullptr; 7091 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 7092 return Existing; 7093 7094 // Nope it doesn't. Remove the node from its current place in the maps. 7095 if (InsertPos) 7096 if (!RemoveNodeFromCSEMaps(N)) 7097 InsertPos = nullptr; 7098 7099 // Now we update the operands. 7100 if (N->OperandList[0] != Op1) 7101 N->OperandList[0].set(Op1); 7102 if (N->OperandList[1] != Op2) 7103 N->OperandList[1].set(Op2); 7104 7105 updateDivergence(N); 7106 // If this gets put into a CSE map, add it. 7107 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7108 return N; 7109 } 7110 7111 SDNode *SelectionDAG:: 7112 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 7113 SDValue Ops[] = { Op1, Op2, Op3 }; 7114 return UpdateNodeOperands(N, Ops); 7115 } 7116 7117 SDNode *SelectionDAG:: 7118 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 7119 SDValue Op3, SDValue Op4) { 7120 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 7121 return UpdateNodeOperands(N, Ops); 7122 } 7123 7124 SDNode *SelectionDAG:: 7125 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 7126 SDValue Op3, SDValue Op4, SDValue Op5) { 7127 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 7128 return UpdateNodeOperands(N, Ops); 7129 } 7130 7131 SDNode *SelectionDAG:: 7132 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 7133 unsigned NumOps = Ops.size(); 7134 assert(N->getNumOperands() == NumOps && 7135 "Update with wrong number of operands"); 7136 7137 // If no operands changed just return the input node. 7138 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 7139 return N; 7140 7141 // See if the modified node already exists. 7142 void *InsertPos = nullptr; 7143 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 7144 return Existing; 7145 7146 // Nope it doesn't. Remove the node from its current place in the maps. 7147 if (InsertPos) 7148 if (!RemoveNodeFromCSEMaps(N)) 7149 InsertPos = nullptr; 7150 7151 // Now we update the operands. 7152 for (unsigned i = 0; i != NumOps; ++i) 7153 if (N->OperandList[i] != Ops[i]) 7154 N->OperandList[i].set(Ops[i]); 7155 7156 updateDivergence(N); 7157 // If this gets put into a CSE map, add it. 7158 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7159 return N; 7160 } 7161 7162 /// DropOperands - Release the operands and set this node to have 7163 /// zero operands. 7164 void SDNode::DropOperands() { 7165 // Unlike the code in MorphNodeTo that does this, we don't need to 7166 // watch for dead nodes here. 7167 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 7168 SDUse &Use = *I++; 7169 Use.set(SDValue()); 7170 } 7171 } 7172 7173 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 7174 ArrayRef<MachineMemOperand *> NewMemRefs) { 7175 if (NewMemRefs.empty()) { 7176 N->clearMemRefs(); 7177 return; 7178 } 7179 7180 // Check if we can avoid allocating by storing a single reference directly. 7181 if (NewMemRefs.size() == 1) { 7182 N->MemRefs = NewMemRefs[0]; 7183 N->NumMemRefs = 1; 7184 return; 7185 } 7186 7187 MachineMemOperand **MemRefsBuffer = 7188 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 7189 std::copy(NewMemRefs.begin(), NewMemRefs.end(), MemRefsBuffer); 7190 N->MemRefs = MemRefsBuffer; 7191 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 7192 } 7193 7194 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 7195 /// machine opcode. 7196 /// 7197 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7198 EVT VT) { 7199 SDVTList VTs = getVTList(VT); 7200 return SelectNodeTo(N, MachineOpc, VTs, None); 7201 } 7202 7203 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7204 EVT VT, SDValue Op1) { 7205 SDVTList VTs = getVTList(VT); 7206 SDValue Ops[] = { Op1 }; 7207 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7208 } 7209 7210 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7211 EVT VT, SDValue Op1, 7212 SDValue Op2) { 7213 SDVTList VTs = getVTList(VT); 7214 SDValue Ops[] = { Op1, Op2 }; 7215 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7216 } 7217 7218 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7219 EVT VT, SDValue Op1, 7220 SDValue Op2, SDValue Op3) { 7221 SDVTList VTs = getVTList(VT); 7222 SDValue Ops[] = { Op1, Op2, Op3 }; 7223 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7224 } 7225 7226 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7227 EVT VT, ArrayRef<SDValue> Ops) { 7228 SDVTList VTs = getVTList(VT); 7229 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7230 } 7231 7232 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7233 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 7234 SDVTList VTs = getVTList(VT1, VT2); 7235 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7236 } 7237 7238 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7239 EVT VT1, EVT VT2) { 7240 SDVTList VTs = getVTList(VT1, VT2); 7241 return SelectNodeTo(N, MachineOpc, VTs, None); 7242 } 7243 7244 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7245 EVT VT1, EVT VT2, EVT VT3, 7246 ArrayRef<SDValue> Ops) { 7247 SDVTList VTs = getVTList(VT1, VT2, VT3); 7248 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7249 } 7250 7251 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7252 EVT VT1, EVT VT2, 7253 SDValue Op1, SDValue Op2) { 7254 SDVTList VTs = getVTList(VT1, VT2); 7255 SDValue Ops[] = { Op1, Op2 }; 7256 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7257 } 7258 7259 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7260 SDVTList VTs,ArrayRef<SDValue> Ops) { 7261 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 7262 // Reset the NodeID to -1. 7263 New->setNodeId(-1); 7264 if (New != N) { 7265 ReplaceAllUsesWith(N, New); 7266 RemoveDeadNode(N); 7267 } 7268 return New; 7269 } 7270 7271 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 7272 /// the line number information on the merged node since it is not possible to 7273 /// preserve the information that operation is associated with multiple lines. 7274 /// This will make the debugger working better at -O0, were there is a higher 7275 /// probability having other instructions associated with that line. 7276 /// 7277 /// For IROrder, we keep the smaller of the two 7278 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 7279 DebugLoc NLoc = N->getDebugLoc(); 7280 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 7281 N->setDebugLoc(DebugLoc()); 7282 } 7283 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 7284 N->setIROrder(Order); 7285 return N; 7286 } 7287 7288 /// MorphNodeTo - This *mutates* the specified node to have the specified 7289 /// return type, opcode, and operands. 7290 /// 7291 /// Note that MorphNodeTo returns the resultant node. If there is already a 7292 /// node of the specified opcode and operands, it returns that node instead of 7293 /// the current one. Note that the SDLoc need not be the same. 7294 /// 7295 /// Using MorphNodeTo is faster than creating a new node and swapping it in 7296 /// with ReplaceAllUsesWith both because it often avoids allocating a new 7297 /// node, and because it doesn't require CSE recalculation for any of 7298 /// the node's users. 7299 /// 7300 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 7301 /// As a consequence it isn't appropriate to use from within the DAG combiner or 7302 /// the legalizer which maintain worklists that would need to be updated when 7303 /// deleting things. 7304 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 7305 SDVTList VTs, ArrayRef<SDValue> Ops) { 7306 // If an identical node already exists, use it. 7307 void *IP = nullptr; 7308 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 7309 FoldingSetNodeID ID; 7310 AddNodeIDNode(ID, Opc, VTs, Ops); 7311 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 7312 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 7313 } 7314 7315 if (!RemoveNodeFromCSEMaps(N)) 7316 IP = nullptr; 7317 7318 // Start the morphing. 7319 N->NodeType = Opc; 7320 N->ValueList = VTs.VTs; 7321 N->NumValues = VTs.NumVTs; 7322 7323 // Clear the operands list, updating used nodes to remove this from their 7324 // use list. Keep track of any operands that become dead as a result. 7325 SmallPtrSet<SDNode*, 16> DeadNodeSet; 7326 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 7327 SDUse &Use = *I++; 7328 SDNode *Used = Use.getNode(); 7329 Use.set(SDValue()); 7330 if (Used->use_empty()) 7331 DeadNodeSet.insert(Used); 7332 } 7333 7334 // For MachineNode, initialize the memory references information. 7335 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 7336 MN->clearMemRefs(); 7337 7338 // Swap for an appropriately sized array from the recycler. 7339 removeOperands(N); 7340 createOperands(N, Ops); 7341 7342 // Delete any nodes that are still dead after adding the uses for the 7343 // new operands. 7344 if (!DeadNodeSet.empty()) { 7345 SmallVector<SDNode *, 16> DeadNodes; 7346 for (SDNode *N : DeadNodeSet) 7347 if (N->use_empty()) 7348 DeadNodes.push_back(N); 7349 RemoveDeadNodes(DeadNodes); 7350 } 7351 7352 if (IP) 7353 CSEMap.InsertNode(N, IP); // Memoize the new node. 7354 return N; 7355 } 7356 7357 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 7358 unsigned OrigOpc = Node->getOpcode(); 7359 unsigned NewOpc; 7360 bool IsUnary = false; 7361 bool IsTernary = false; 7362 switch (OrigOpc) { 7363 default: 7364 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 7365 case ISD::STRICT_FADD: NewOpc = ISD::FADD; break; 7366 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break; 7367 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break; 7368 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break; 7369 case ISD::STRICT_FREM: NewOpc = ISD::FREM; break; 7370 case ISD::STRICT_FMA: NewOpc = ISD::FMA; IsTernary = true; break; 7371 case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break; 7372 case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break; 7373 case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break; 7374 case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break; 7375 case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break; 7376 case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break; 7377 case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break; 7378 case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break; 7379 case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break; 7380 case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break; 7381 case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break; 7382 case ISD::STRICT_FNEARBYINT: 7383 NewOpc = ISD::FNEARBYINT; 7384 IsUnary = true; 7385 break; 7386 case ISD::STRICT_FMAXNUM: NewOpc = ISD::FMAXNUM; break; 7387 case ISD::STRICT_FMINNUM: NewOpc = ISD::FMINNUM; break; 7388 case ISD::STRICT_FCEIL: NewOpc = ISD::FCEIL; IsUnary = true; break; 7389 case ISD::STRICT_FFLOOR: NewOpc = ISD::FFLOOR; IsUnary = true; break; 7390 case ISD::STRICT_FROUND: NewOpc = ISD::FROUND; IsUnary = true; break; 7391 case ISD::STRICT_FTRUNC: NewOpc = ISD::FTRUNC; IsUnary = true; break; 7392 } 7393 7394 // We're taking this node out of the chain, so we need to re-link things. 7395 SDValue InputChain = Node->getOperand(0); 7396 SDValue OutputChain = SDValue(Node, 1); 7397 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 7398 7399 SDVTList VTs = getVTList(Node->getOperand(1).getValueType()); 7400 SDNode *Res = nullptr; 7401 if (IsUnary) 7402 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) }); 7403 else if (IsTernary) 7404 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1), 7405 Node->getOperand(2), 7406 Node->getOperand(3)}); 7407 else 7408 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1), 7409 Node->getOperand(2) }); 7410 7411 // MorphNodeTo can operate in two ways: if an existing node with the 7412 // specified operands exists, it can just return it. Otherwise, it 7413 // updates the node in place to have the requested operands. 7414 if (Res == Node) { 7415 // If we updated the node in place, reset the node ID. To the isel, 7416 // this should be just like a newly allocated machine node. 7417 Res->setNodeId(-1); 7418 } else { 7419 ReplaceAllUsesWith(Node, Res); 7420 RemoveDeadNode(Node); 7421 } 7422 7423 return Res; 7424 } 7425 7426 /// getMachineNode - These are used for target selectors to create a new node 7427 /// with specified return type(s), MachineInstr opcode, and operands. 7428 /// 7429 /// Note that getMachineNode returns the resultant node. If there is already a 7430 /// node of the specified opcode and operands, it returns that node instead of 7431 /// the current one. 7432 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7433 EVT VT) { 7434 SDVTList VTs = getVTList(VT); 7435 return getMachineNode(Opcode, dl, VTs, None); 7436 } 7437 7438 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7439 EVT VT, SDValue Op1) { 7440 SDVTList VTs = getVTList(VT); 7441 SDValue Ops[] = { Op1 }; 7442 return getMachineNode(Opcode, dl, VTs, Ops); 7443 } 7444 7445 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7446 EVT VT, SDValue Op1, SDValue Op2) { 7447 SDVTList VTs = getVTList(VT); 7448 SDValue Ops[] = { Op1, Op2 }; 7449 return getMachineNode(Opcode, dl, VTs, Ops); 7450 } 7451 7452 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7453 EVT VT, SDValue Op1, SDValue Op2, 7454 SDValue Op3) { 7455 SDVTList VTs = getVTList(VT); 7456 SDValue Ops[] = { Op1, Op2, Op3 }; 7457 return getMachineNode(Opcode, dl, VTs, Ops); 7458 } 7459 7460 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7461 EVT VT, ArrayRef<SDValue> Ops) { 7462 SDVTList VTs = getVTList(VT); 7463 return getMachineNode(Opcode, dl, VTs, Ops); 7464 } 7465 7466 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7467 EVT VT1, EVT VT2, SDValue Op1, 7468 SDValue Op2) { 7469 SDVTList VTs = getVTList(VT1, VT2); 7470 SDValue Ops[] = { Op1, Op2 }; 7471 return getMachineNode(Opcode, dl, VTs, Ops); 7472 } 7473 7474 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7475 EVT VT1, EVT VT2, SDValue Op1, 7476 SDValue Op2, SDValue Op3) { 7477 SDVTList VTs = getVTList(VT1, VT2); 7478 SDValue Ops[] = { Op1, Op2, Op3 }; 7479 return getMachineNode(Opcode, dl, VTs, Ops); 7480 } 7481 7482 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7483 EVT VT1, EVT VT2, 7484 ArrayRef<SDValue> Ops) { 7485 SDVTList VTs = getVTList(VT1, VT2); 7486 return getMachineNode(Opcode, dl, VTs, Ops); 7487 } 7488 7489 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7490 EVT VT1, EVT VT2, EVT VT3, 7491 SDValue Op1, SDValue Op2) { 7492 SDVTList VTs = getVTList(VT1, VT2, VT3); 7493 SDValue Ops[] = { Op1, Op2 }; 7494 return getMachineNode(Opcode, dl, VTs, Ops); 7495 } 7496 7497 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7498 EVT VT1, EVT VT2, EVT VT3, 7499 SDValue Op1, SDValue Op2, 7500 SDValue Op3) { 7501 SDVTList VTs = getVTList(VT1, VT2, VT3); 7502 SDValue Ops[] = { Op1, Op2, Op3 }; 7503 return getMachineNode(Opcode, dl, VTs, Ops); 7504 } 7505 7506 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7507 EVT VT1, EVT VT2, EVT VT3, 7508 ArrayRef<SDValue> Ops) { 7509 SDVTList VTs = getVTList(VT1, VT2, VT3); 7510 return getMachineNode(Opcode, dl, VTs, Ops); 7511 } 7512 7513 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7514 ArrayRef<EVT> ResultTys, 7515 ArrayRef<SDValue> Ops) { 7516 SDVTList VTs = getVTList(ResultTys); 7517 return getMachineNode(Opcode, dl, VTs, Ops); 7518 } 7519 7520 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 7521 SDVTList VTs, 7522 ArrayRef<SDValue> Ops) { 7523 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 7524 MachineSDNode *N; 7525 void *IP = nullptr; 7526 7527 if (DoCSE) { 7528 FoldingSetNodeID ID; 7529 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 7530 IP = nullptr; 7531 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 7532 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 7533 } 7534 } 7535 7536 // Allocate a new MachineSDNode. 7537 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7538 createOperands(N, Ops); 7539 7540 if (DoCSE) 7541 CSEMap.InsertNode(N, IP); 7542 7543 InsertNode(N); 7544 return N; 7545 } 7546 7547 /// getTargetExtractSubreg - A convenience function for creating 7548 /// TargetOpcode::EXTRACT_SUBREG nodes. 7549 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 7550 SDValue Operand) { 7551 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 7552 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 7553 VT, Operand, SRIdxVal); 7554 return SDValue(Subreg, 0); 7555 } 7556 7557 /// getTargetInsertSubreg - A convenience function for creating 7558 /// TargetOpcode::INSERT_SUBREG nodes. 7559 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 7560 SDValue Operand, SDValue Subreg) { 7561 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 7562 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 7563 VT, Operand, Subreg, SRIdxVal); 7564 return SDValue(Result, 0); 7565 } 7566 7567 /// getNodeIfExists - Get the specified node if it's already available, or 7568 /// else return NULL. 7569 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 7570 ArrayRef<SDValue> Ops, 7571 const SDNodeFlags Flags) { 7572 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 7573 FoldingSetNodeID ID; 7574 AddNodeIDNode(ID, Opcode, VTList, Ops); 7575 void *IP = nullptr; 7576 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 7577 E->intersectFlagsWith(Flags); 7578 return E; 7579 } 7580 } 7581 return nullptr; 7582 } 7583 7584 /// getDbgValue - Creates a SDDbgValue node. 7585 /// 7586 /// SDNode 7587 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 7588 SDNode *N, unsigned R, bool IsIndirect, 7589 const DebugLoc &DL, unsigned O) { 7590 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 7591 "Expected inlined-at fields to agree"); 7592 return new (DbgInfo->getAlloc()) 7593 SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O); 7594 } 7595 7596 /// Constant 7597 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 7598 DIExpression *Expr, 7599 const Value *C, 7600 const DebugLoc &DL, unsigned O) { 7601 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 7602 "Expected inlined-at fields to agree"); 7603 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O); 7604 } 7605 7606 /// FrameIndex 7607 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 7608 DIExpression *Expr, unsigned FI, 7609 bool IsIndirect, 7610 const DebugLoc &DL, 7611 unsigned O) { 7612 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 7613 "Expected inlined-at fields to agree"); 7614 return new (DbgInfo->getAlloc()) 7615 SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX); 7616 } 7617 7618 /// VReg 7619 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, 7620 DIExpression *Expr, 7621 unsigned VReg, bool IsIndirect, 7622 const DebugLoc &DL, unsigned O) { 7623 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 7624 "Expected inlined-at fields to agree"); 7625 return new (DbgInfo->getAlloc()) 7626 SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG); 7627 } 7628 7629 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 7630 unsigned OffsetInBits, unsigned SizeInBits, 7631 bool InvalidateDbg) { 7632 SDNode *FromNode = From.getNode(); 7633 SDNode *ToNode = To.getNode(); 7634 assert(FromNode && ToNode && "Can't modify dbg values"); 7635 7636 // PR35338 7637 // TODO: assert(From != To && "Redundant dbg value transfer"); 7638 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 7639 if (From == To || FromNode == ToNode) 7640 return; 7641 7642 if (!FromNode->getHasDebugValue()) 7643 return; 7644 7645 SmallVector<SDDbgValue *, 2> ClonedDVs; 7646 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 7647 if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated()) 7648 continue; 7649 7650 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 7651 7652 // Just transfer the dbg value attached to From. 7653 if (Dbg->getResNo() != From.getResNo()) 7654 continue; 7655 7656 DIVariable *Var = Dbg->getVariable(); 7657 auto *Expr = Dbg->getExpression(); 7658 // If a fragment is requested, update the expression. 7659 if (SizeInBits) { 7660 // When splitting a larger (e.g., sign-extended) value whose 7661 // lower bits are described with an SDDbgValue, do not attempt 7662 // to transfer the SDDbgValue to the upper bits. 7663 if (auto FI = Expr->getFragmentInfo()) 7664 if (OffsetInBits + SizeInBits > FI->SizeInBits) 7665 continue; 7666 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 7667 SizeInBits); 7668 if (!Fragment) 7669 continue; 7670 Expr = *Fragment; 7671 } 7672 // Clone the SDDbgValue and move it to To. 7673 SDDbgValue *Clone = 7674 getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(), 7675 Dbg->getDebugLoc(), Dbg->getOrder()); 7676 ClonedDVs.push_back(Clone); 7677 7678 if (InvalidateDbg) 7679 Dbg->setIsInvalidated(); 7680 } 7681 7682 for (SDDbgValue *Dbg : ClonedDVs) 7683 AddDbgValue(Dbg, ToNode, false); 7684 } 7685 7686 void SelectionDAG::salvageDebugInfo(SDNode &N) { 7687 if (!N.getHasDebugValue()) 7688 return; 7689 7690 SmallVector<SDDbgValue *, 2> ClonedDVs; 7691 for (auto DV : GetDbgValues(&N)) { 7692 if (DV->isInvalidated()) 7693 continue; 7694 switch (N.getOpcode()) { 7695 default: 7696 break; 7697 case ISD::ADD: 7698 SDValue N0 = N.getOperand(0); 7699 SDValue N1 = N.getOperand(1); 7700 if (!isConstantIntBuildVectorOrConstantInt(N0) && 7701 isConstantIntBuildVectorOrConstantInt(N1)) { 7702 uint64_t Offset = N.getConstantOperandVal(1); 7703 // Rewrite an ADD constant node into a DIExpression. Since we are 7704 // performing arithmetic to compute the variable's *value* in the 7705 // DIExpression, we need to mark the expression with a 7706 // DW_OP_stack_value. 7707 auto *DIExpr = DV->getExpression(); 7708 DIExpr = DIExpression::prepend(DIExpr, DIExpression::NoDeref, Offset, 7709 DIExpression::NoDeref, 7710 DIExpression::WithStackValue); 7711 SDDbgValue *Clone = 7712 getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(), 7713 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder()); 7714 ClonedDVs.push_back(Clone); 7715 DV->setIsInvalidated(); 7716 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 7717 N0.getNode()->dumprFull(this); 7718 dbgs() << " into " << *DIExpr << '\n'); 7719 } 7720 } 7721 } 7722 7723 for (SDDbgValue *Dbg : ClonedDVs) 7724 AddDbgValue(Dbg, Dbg->getSDNode(), false); 7725 } 7726 7727 /// Creates a SDDbgLabel node. 7728 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 7729 const DebugLoc &DL, unsigned O) { 7730 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 7731 "Expected inlined-at fields to agree"); 7732 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 7733 } 7734 7735 namespace { 7736 7737 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 7738 /// pointed to by a use iterator is deleted, increment the use iterator 7739 /// so that it doesn't dangle. 7740 /// 7741 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 7742 SDNode::use_iterator &UI; 7743 SDNode::use_iterator &UE; 7744 7745 void NodeDeleted(SDNode *N, SDNode *E) override { 7746 // Increment the iterator as needed. 7747 while (UI != UE && N == *UI) 7748 ++UI; 7749 } 7750 7751 public: 7752 RAUWUpdateListener(SelectionDAG &d, 7753 SDNode::use_iterator &ui, 7754 SDNode::use_iterator &ue) 7755 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 7756 }; 7757 7758 } // end anonymous namespace 7759 7760 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 7761 /// This can cause recursive merging of nodes in the DAG. 7762 /// 7763 /// This version assumes From has a single result value. 7764 /// 7765 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 7766 SDNode *From = FromN.getNode(); 7767 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 7768 "Cannot replace with this method!"); 7769 assert(From != To.getNode() && "Cannot replace uses of with self"); 7770 7771 // Preserve Debug Values 7772 transferDbgValues(FromN, To); 7773 7774 // Iterate over all the existing uses of From. New uses will be added 7775 // to the beginning of the use list, which we avoid visiting. 7776 // This specifically avoids visiting uses of From that arise while the 7777 // replacement is happening, because any such uses would be the result 7778 // of CSE: If an existing node looks like From after one of its operands 7779 // is replaced by To, we don't want to replace of all its users with To 7780 // too. See PR3018 for more info. 7781 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 7782 RAUWUpdateListener Listener(*this, UI, UE); 7783 while (UI != UE) { 7784 SDNode *User = *UI; 7785 7786 // This node is about to morph, remove its old self from the CSE maps. 7787 RemoveNodeFromCSEMaps(User); 7788 7789 // A user can appear in a use list multiple times, and when this 7790 // happens the uses are usually next to each other in the list. 7791 // To help reduce the number of CSE recomputations, process all 7792 // the uses of this user that we can find this way. 7793 do { 7794 SDUse &Use = UI.getUse(); 7795 ++UI; 7796 Use.set(To); 7797 if (To->isDivergent() != From->isDivergent()) 7798 updateDivergence(User); 7799 } while (UI != UE && *UI == User); 7800 // Now that we have modified User, add it back to the CSE maps. If it 7801 // already exists there, recursively merge the results together. 7802 AddModifiedNodeToCSEMaps(User); 7803 } 7804 7805 // If we just RAUW'd the root, take note. 7806 if (FromN == getRoot()) 7807 setRoot(To); 7808 } 7809 7810 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 7811 /// This can cause recursive merging of nodes in the DAG. 7812 /// 7813 /// This version assumes that for each value of From, there is a 7814 /// corresponding value in To in the same position with the same type. 7815 /// 7816 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 7817 #ifndef NDEBUG 7818 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 7819 assert((!From->hasAnyUseOfValue(i) || 7820 From->getValueType(i) == To->getValueType(i)) && 7821 "Cannot use this version of ReplaceAllUsesWith!"); 7822 #endif 7823 7824 // Handle the trivial case. 7825 if (From == To) 7826 return; 7827 7828 // Preserve Debug Info. Only do this if there's a use. 7829 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 7830 if (From->hasAnyUseOfValue(i)) { 7831 assert((i < To->getNumValues()) && "Invalid To location"); 7832 transferDbgValues(SDValue(From, i), SDValue(To, i)); 7833 } 7834 7835 // Iterate over just the existing users of From. See the comments in 7836 // the ReplaceAllUsesWith above. 7837 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 7838 RAUWUpdateListener Listener(*this, UI, UE); 7839 while (UI != UE) { 7840 SDNode *User = *UI; 7841 7842 // This node is about to morph, remove its old self from the CSE maps. 7843 RemoveNodeFromCSEMaps(User); 7844 7845 // A user can appear in a use list multiple times, and when this 7846 // happens the uses are usually next to each other in the list. 7847 // To help reduce the number of CSE recomputations, process all 7848 // the uses of this user that we can find this way. 7849 do { 7850 SDUse &Use = UI.getUse(); 7851 ++UI; 7852 Use.setNode(To); 7853 if (To->isDivergent() != From->isDivergent()) 7854 updateDivergence(User); 7855 } while (UI != UE && *UI == User); 7856 7857 // Now that we have modified User, add it back to the CSE maps. If it 7858 // already exists there, recursively merge the results together. 7859 AddModifiedNodeToCSEMaps(User); 7860 } 7861 7862 // If we just RAUW'd the root, take note. 7863 if (From == getRoot().getNode()) 7864 setRoot(SDValue(To, getRoot().getResNo())); 7865 } 7866 7867 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 7868 /// This can cause recursive merging of nodes in the DAG. 7869 /// 7870 /// This version can replace From with any result values. To must match the 7871 /// number and types of values returned by From. 7872 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 7873 if (From->getNumValues() == 1) // Handle the simple case efficiently. 7874 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 7875 7876 // Preserve Debug Info. 7877 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 7878 transferDbgValues(SDValue(From, i), To[i]); 7879 7880 // Iterate over just the existing users of From. See the comments in 7881 // the ReplaceAllUsesWith above. 7882 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 7883 RAUWUpdateListener Listener(*this, UI, UE); 7884 while (UI != UE) { 7885 SDNode *User = *UI; 7886 7887 // This node is about to morph, remove its old self from the CSE maps. 7888 RemoveNodeFromCSEMaps(User); 7889 7890 // A user can appear in a use list multiple times, and when this happens the 7891 // uses are usually next to each other in the list. To help reduce the 7892 // number of CSE and divergence recomputations, process all the uses of this 7893 // user that we can find this way. 7894 bool To_IsDivergent = false; 7895 do { 7896 SDUse &Use = UI.getUse(); 7897 const SDValue &ToOp = To[Use.getResNo()]; 7898 ++UI; 7899 Use.set(ToOp); 7900 To_IsDivergent |= ToOp->isDivergent(); 7901 } while (UI != UE && *UI == User); 7902 7903 if (To_IsDivergent != From->isDivergent()) 7904 updateDivergence(User); 7905 7906 // Now that we have modified User, add it back to the CSE maps. If it 7907 // already exists there, recursively merge the results together. 7908 AddModifiedNodeToCSEMaps(User); 7909 } 7910 7911 // If we just RAUW'd the root, take note. 7912 if (From == getRoot().getNode()) 7913 setRoot(SDValue(To[getRoot().getResNo()])); 7914 } 7915 7916 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 7917 /// uses of other values produced by From.getNode() alone. The Deleted 7918 /// vector is handled the same way as for ReplaceAllUsesWith. 7919 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 7920 // Handle the really simple, really trivial case efficiently. 7921 if (From == To) return; 7922 7923 // Handle the simple, trivial, case efficiently. 7924 if (From.getNode()->getNumValues() == 1) { 7925 ReplaceAllUsesWith(From, To); 7926 return; 7927 } 7928 7929 // Preserve Debug Info. 7930 transferDbgValues(From, To); 7931 7932 // Iterate over just the existing users of From. See the comments in 7933 // the ReplaceAllUsesWith above. 7934 SDNode::use_iterator UI = From.getNode()->use_begin(), 7935 UE = From.getNode()->use_end(); 7936 RAUWUpdateListener Listener(*this, UI, UE); 7937 while (UI != UE) { 7938 SDNode *User = *UI; 7939 bool UserRemovedFromCSEMaps = false; 7940 7941 // A user can appear in a use list multiple times, and when this 7942 // happens the uses are usually next to each other in the list. 7943 // To help reduce the number of CSE recomputations, process all 7944 // the uses of this user that we can find this way. 7945 do { 7946 SDUse &Use = UI.getUse(); 7947 7948 // Skip uses of different values from the same node. 7949 if (Use.getResNo() != From.getResNo()) { 7950 ++UI; 7951 continue; 7952 } 7953 7954 // If this node hasn't been modified yet, it's still in the CSE maps, 7955 // so remove its old self from the CSE maps. 7956 if (!UserRemovedFromCSEMaps) { 7957 RemoveNodeFromCSEMaps(User); 7958 UserRemovedFromCSEMaps = true; 7959 } 7960 7961 ++UI; 7962 Use.set(To); 7963 if (To->isDivergent() != From->isDivergent()) 7964 updateDivergence(User); 7965 } while (UI != UE && *UI == User); 7966 // We are iterating over all uses of the From node, so if a use 7967 // doesn't use the specific value, no changes are made. 7968 if (!UserRemovedFromCSEMaps) 7969 continue; 7970 7971 // Now that we have modified User, add it back to the CSE maps. If it 7972 // already exists there, recursively merge the results together. 7973 AddModifiedNodeToCSEMaps(User); 7974 } 7975 7976 // If we just RAUW'd the root, take note. 7977 if (From == getRoot()) 7978 setRoot(To); 7979 } 7980 7981 namespace { 7982 7983 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 7984 /// to record information about a use. 7985 struct UseMemo { 7986 SDNode *User; 7987 unsigned Index; 7988 SDUse *Use; 7989 }; 7990 7991 /// operator< - Sort Memos by User. 7992 bool operator<(const UseMemo &L, const UseMemo &R) { 7993 return (intptr_t)L.User < (intptr_t)R.User; 7994 } 7995 7996 } // end anonymous namespace 7997 7998 void SelectionDAG::updateDivergence(SDNode * N) 7999 { 8000 if (TLI->isSDNodeAlwaysUniform(N)) 8001 return; 8002 bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 8003 for (auto &Op : N->ops()) { 8004 if (Op.Val.getValueType() != MVT::Other) 8005 IsDivergent |= Op.getNode()->isDivergent(); 8006 } 8007 if (N->SDNodeBits.IsDivergent != IsDivergent) { 8008 N->SDNodeBits.IsDivergent = IsDivergent; 8009 for (auto U : N->uses()) { 8010 updateDivergence(U); 8011 } 8012 } 8013 } 8014 8015 8016 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode*>& Order) { 8017 DenseMap<SDNode *, unsigned> Degree; 8018 Order.reserve(AllNodes.size()); 8019 for (auto & N : allnodes()) { 8020 unsigned NOps = N.getNumOperands(); 8021 Degree[&N] = NOps; 8022 if (0 == NOps) 8023 Order.push_back(&N); 8024 } 8025 for (std::vector<SDNode *>::iterator I = Order.begin(); 8026 I!=Order.end();++I) { 8027 SDNode * N = *I; 8028 for (auto U : N->uses()) { 8029 unsigned &UnsortedOps = Degree[U]; 8030 if (0 == --UnsortedOps) 8031 Order.push_back(U); 8032 } 8033 } 8034 } 8035 8036 #ifndef NDEBUG 8037 void SelectionDAG::VerifyDAGDiverence() 8038 { 8039 std::vector<SDNode*> TopoOrder; 8040 CreateTopologicalOrder(TopoOrder); 8041 const TargetLowering &TLI = getTargetLoweringInfo(); 8042 DenseMap<const SDNode *, bool> DivergenceMap; 8043 for (auto &N : allnodes()) { 8044 DivergenceMap[&N] = false; 8045 } 8046 for (auto N : TopoOrder) { 8047 bool IsDivergent = DivergenceMap[N]; 8048 bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA); 8049 for (auto &Op : N->ops()) { 8050 if (Op.Val.getValueType() != MVT::Other) 8051 IsSDNodeDivergent |= DivergenceMap[Op.getNode()]; 8052 } 8053 if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) { 8054 DivergenceMap[N] = true; 8055 } 8056 } 8057 for (auto &N : allnodes()) { 8058 (void)N; 8059 assert(DivergenceMap[&N] == N.isDivergent() && 8060 "Divergence bit inconsistency detected\n"); 8061 } 8062 } 8063 #endif 8064 8065 8066 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 8067 /// uses of other values produced by From.getNode() alone. The same value 8068 /// may appear in both the From and To list. The Deleted vector is 8069 /// handled the same way as for ReplaceAllUsesWith. 8070 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 8071 const SDValue *To, 8072 unsigned Num){ 8073 // Handle the simple, trivial case efficiently. 8074 if (Num == 1) 8075 return ReplaceAllUsesOfValueWith(*From, *To); 8076 8077 transferDbgValues(*From, *To); 8078 8079 // Read up all the uses and make records of them. This helps 8080 // processing new uses that are introduced during the 8081 // replacement process. 8082 SmallVector<UseMemo, 4> Uses; 8083 for (unsigned i = 0; i != Num; ++i) { 8084 unsigned FromResNo = From[i].getResNo(); 8085 SDNode *FromNode = From[i].getNode(); 8086 for (SDNode::use_iterator UI = FromNode->use_begin(), 8087 E = FromNode->use_end(); UI != E; ++UI) { 8088 SDUse &Use = UI.getUse(); 8089 if (Use.getResNo() == FromResNo) { 8090 UseMemo Memo = { *UI, i, &Use }; 8091 Uses.push_back(Memo); 8092 } 8093 } 8094 } 8095 8096 // Sort the uses, so that all the uses from a given User are together. 8097 llvm::sort(Uses); 8098 8099 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 8100 UseIndex != UseIndexEnd; ) { 8101 // We know that this user uses some value of From. If it is the right 8102 // value, update it. 8103 SDNode *User = Uses[UseIndex].User; 8104 8105 // This node is about to morph, remove its old self from the CSE maps. 8106 RemoveNodeFromCSEMaps(User); 8107 8108 // The Uses array is sorted, so all the uses for a given User 8109 // are next to each other in the list. 8110 // To help reduce the number of CSE recomputations, process all 8111 // the uses of this user that we can find this way. 8112 do { 8113 unsigned i = Uses[UseIndex].Index; 8114 SDUse &Use = *Uses[UseIndex].Use; 8115 ++UseIndex; 8116 8117 Use.set(To[i]); 8118 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 8119 8120 // Now that we have modified User, add it back to the CSE maps. If it 8121 // already exists there, recursively merge the results together. 8122 AddModifiedNodeToCSEMaps(User); 8123 } 8124 } 8125 8126 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 8127 /// based on their topological order. It returns the maximum id and a vector 8128 /// of the SDNodes* in assigned order by reference. 8129 unsigned SelectionDAG::AssignTopologicalOrder() { 8130 unsigned DAGSize = 0; 8131 8132 // SortedPos tracks the progress of the algorithm. Nodes before it are 8133 // sorted, nodes after it are unsorted. When the algorithm completes 8134 // it is at the end of the list. 8135 allnodes_iterator SortedPos = allnodes_begin(); 8136 8137 // Visit all the nodes. Move nodes with no operands to the front of 8138 // the list immediately. Annotate nodes that do have operands with their 8139 // operand count. Before we do this, the Node Id fields of the nodes 8140 // may contain arbitrary values. After, the Node Id fields for nodes 8141 // before SortedPos will contain the topological sort index, and the 8142 // Node Id fields for nodes At SortedPos and after will contain the 8143 // count of outstanding operands. 8144 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 8145 SDNode *N = &*I++; 8146 checkForCycles(N, this); 8147 unsigned Degree = N->getNumOperands(); 8148 if (Degree == 0) { 8149 // A node with no uses, add it to the result array immediately. 8150 N->setNodeId(DAGSize++); 8151 allnodes_iterator Q(N); 8152 if (Q != SortedPos) 8153 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 8154 assert(SortedPos != AllNodes.end() && "Overran node list"); 8155 ++SortedPos; 8156 } else { 8157 // Temporarily use the Node Id as scratch space for the degree count. 8158 N->setNodeId(Degree); 8159 } 8160 } 8161 8162 // Visit all the nodes. As we iterate, move nodes into sorted order, 8163 // such that by the time the end is reached all nodes will be sorted. 8164 for (SDNode &Node : allnodes()) { 8165 SDNode *N = &Node; 8166 checkForCycles(N, this); 8167 // N is in sorted position, so all its uses have one less operand 8168 // that needs to be sorted. 8169 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 8170 UI != UE; ++UI) { 8171 SDNode *P = *UI; 8172 unsigned Degree = P->getNodeId(); 8173 assert(Degree != 0 && "Invalid node degree"); 8174 --Degree; 8175 if (Degree == 0) { 8176 // All of P's operands are sorted, so P may sorted now. 8177 P->setNodeId(DAGSize++); 8178 if (P->getIterator() != SortedPos) 8179 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 8180 assert(SortedPos != AllNodes.end() && "Overran node list"); 8181 ++SortedPos; 8182 } else { 8183 // Update P's outstanding operand count. 8184 P->setNodeId(Degree); 8185 } 8186 } 8187 if (Node.getIterator() == SortedPos) { 8188 #ifndef NDEBUG 8189 allnodes_iterator I(N); 8190 SDNode *S = &*++I; 8191 dbgs() << "Overran sorted position:\n"; 8192 S->dumprFull(this); dbgs() << "\n"; 8193 dbgs() << "Checking if this is due to cycles\n"; 8194 checkForCycles(this, true); 8195 #endif 8196 llvm_unreachable(nullptr); 8197 } 8198 } 8199 8200 assert(SortedPos == AllNodes.end() && 8201 "Topological sort incomplete!"); 8202 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 8203 "First node in topological sort is not the entry token!"); 8204 assert(AllNodes.front().getNodeId() == 0 && 8205 "First node in topological sort has non-zero id!"); 8206 assert(AllNodes.front().getNumOperands() == 0 && 8207 "First node in topological sort has operands!"); 8208 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 8209 "Last node in topologic sort has unexpected id!"); 8210 assert(AllNodes.back().use_empty() && 8211 "Last node in topologic sort has users!"); 8212 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 8213 return DAGSize; 8214 } 8215 8216 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 8217 /// value is produced by SD. 8218 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) { 8219 if (SD) { 8220 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 8221 SD->setHasDebugValue(true); 8222 } 8223 DbgInfo->add(DB, SD, isParameter); 8224 } 8225 8226 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { 8227 DbgInfo->add(DB); 8228 } 8229 8230 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 8231 SDValue NewMemOp) { 8232 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 8233 // The new memory operation must have the same position as the old load in 8234 // terms of memory dependency. Create a TokenFactor for the old load and new 8235 // memory operation and update uses of the old load's output chain to use that 8236 // TokenFactor. 8237 SDValue OldChain = SDValue(OldLoad, 1); 8238 SDValue NewChain = SDValue(NewMemOp.getNode(), 1); 8239 if (!OldLoad->hasAnyUseOfValue(1)) 8240 return NewChain; 8241 8242 SDValue TokenFactor = 8243 getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain); 8244 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 8245 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain); 8246 return TokenFactor; 8247 } 8248 8249 //===----------------------------------------------------------------------===// 8250 // SDNode Class 8251 //===----------------------------------------------------------------------===// 8252 8253 bool llvm::isNullConstant(SDValue V) { 8254 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 8255 return Const != nullptr && Const->isNullValue(); 8256 } 8257 8258 bool llvm::isNullFPConstant(SDValue V) { 8259 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 8260 return Const != nullptr && Const->isZero() && !Const->isNegative(); 8261 } 8262 8263 bool llvm::isAllOnesConstant(SDValue V) { 8264 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 8265 return Const != nullptr && Const->isAllOnesValue(); 8266 } 8267 8268 bool llvm::isOneConstant(SDValue V) { 8269 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 8270 return Const != nullptr && Const->isOne(); 8271 } 8272 8273 SDValue llvm::peekThroughBitcasts(SDValue V) { 8274 while (V.getOpcode() == ISD::BITCAST) 8275 V = V.getOperand(0); 8276 return V; 8277 } 8278 8279 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 8280 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 8281 V = V.getOperand(0); 8282 return V; 8283 } 8284 8285 bool llvm::isBitwiseNot(SDValue V) { 8286 if (V.getOpcode() != ISD::XOR) 8287 return false; 8288 ConstantSDNode *C = isConstOrConstSplat(peekThroughBitcasts(V.getOperand(1))); 8289 return C && C->isAllOnesValue(); 8290 } 8291 8292 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs) { 8293 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 8294 return CN; 8295 8296 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 8297 BitVector UndefElements; 8298 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 8299 8300 // BuildVectors can truncate their operands. Ignore that case here. 8301 if (CN && (UndefElements.none() || AllowUndefs) && 8302 CN->getValueType(0) == N.getValueType().getScalarType()) 8303 return CN; 8304 } 8305 8306 return nullptr; 8307 } 8308 8309 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 8310 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 8311 return CN; 8312 8313 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 8314 BitVector UndefElements; 8315 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 8316 if (CN && (UndefElements.none() || AllowUndefs)) 8317 return CN; 8318 } 8319 8320 return nullptr; 8321 } 8322 8323 HandleSDNode::~HandleSDNode() { 8324 DropOperands(); 8325 } 8326 8327 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 8328 const DebugLoc &DL, 8329 const GlobalValue *GA, EVT VT, 8330 int64_t o, unsigned char TF) 8331 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 8332 TheGlobal = GA; 8333 } 8334 8335 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 8336 EVT VT, unsigned SrcAS, 8337 unsigned DestAS) 8338 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 8339 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 8340 8341 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 8342 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 8343 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 8344 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 8345 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 8346 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 8347 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 8348 8349 // We check here that the size of the memory operand fits within the size of 8350 // the MMO. This is because the MMO might indicate only a possible address 8351 // range instead of specifying the affected memory addresses precisely. 8352 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!"); 8353 } 8354 8355 /// Profile - Gather unique data for the node. 8356 /// 8357 void SDNode::Profile(FoldingSetNodeID &ID) const { 8358 AddNodeIDNode(ID, this); 8359 } 8360 8361 namespace { 8362 8363 struct EVTArray { 8364 std::vector<EVT> VTs; 8365 8366 EVTArray() { 8367 VTs.reserve(MVT::LAST_VALUETYPE); 8368 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 8369 VTs.push_back(MVT((MVT::SimpleValueType)i)); 8370 } 8371 }; 8372 8373 } // end anonymous namespace 8374 8375 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 8376 static ManagedStatic<EVTArray> SimpleVTArray; 8377 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 8378 8379 /// getValueTypeList - Return a pointer to the specified value type. 8380 /// 8381 const EVT *SDNode::getValueTypeList(EVT VT) { 8382 if (VT.isExtended()) { 8383 sys::SmartScopedLock<true> Lock(*VTMutex); 8384 return &(*EVTs->insert(VT).first); 8385 } else { 8386 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 8387 "Value type out of range!"); 8388 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 8389 } 8390 } 8391 8392 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 8393 /// indicated value. This method ignores uses of other values defined by this 8394 /// operation. 8395 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 8396 assert(Value < getNumValues() && "Bad value!"); 8397 8398 // TODO: Only iterate over uses of a given value of the node 8399 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 8400 if (UI.getUse().getResNo() == Value) { 8401 if (NUses == 0) 8402 return false; 8403 --NUses; 8404 } 8405 } 8406 8407 // Found exactly the right number of uses? 8408 return NUses == 0; 8409 } 8410 8411 /// hasAnyUseOfValue - Return true if there are any use of the indicated 8412 /// value. This method ignores uses of other values defined by this operation. 8413 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 8414 assert(Value < getNumValues() && "Bad value!"); 8415 8416 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 8417 if (UI.getUse().getResNo() == Value) 8418 return true; 8419 8420 return false; 8421 } 8422 8423 /// isOnlyUserOf - Return true if this node is the only use of N. 8424 bool SDNode::isOnlyUserOf(const SDNode *N) const { 8425 bool Seen = false; 8426 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 8427 SDNode *User = *I; 8428 if (User == this) 8429 Seen = true; 8430 else 8431 return false; 8432 } 8433 8434 return Seen; 8435 } 8436 8437 /// Return true if the only users of N are contained in Nodes. 8438 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 8439 bool Seen = false; 8440 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 8441 SDNode *User = *I; 8442 if (llvm::any_of(Nodes, 8443 [&User](const SDNode *Node) { return User == Node; })) 8444 Seen = true; 8445 else 8446 return false; 8447 } 8448 8449 return Seen; 8450 } 8451 8452 /// isOperand - Return true if this node is an operand of N. 8453 bool SDValue::isOperandOf(const SDNode *N) const { 8454 for (const SDValue &Op : N->op_values()) 8455 if (*this == Op) 8456 return true; 8457 return false; 8458 } 8459 8460 bool SDNode::isOperandOf(const SDNode *N) const { 8461 for (const SDValue &Op : N->op_values()) 8462 if (this == Op.getNode()) 8463 return true; 8464 return false; 8465 } 8466 8467 /// reachesChainWithoutSideEffects - Return true if this operand (which must 8468 /// be a chain) reaches the specified operand without crossing any 8469 /// side-effecting instructions on any chain path. In practice, this looks 8470 /// through token factors and non-volatile loads. In order to remain efficient, 8471 /// this only looks a couple of nodes in, it does not do an exhaustive search. 8472 /// 8473 /// Note that we only need to examine chains when we're searching for 8474 /// side-effects; SelectionDAG requires that all side-effects are represented 8475 /// by chains, even if another operand would force a specific ordering. This 8476 /// constraint is necessary to allow transformations like splitting loads. 8477 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 8478 unsigned Depth) const { 8479 if (*this == Dest) return true; 8480 8481 // Don't search too deeply, we just want to be able to see through 8482 // TokenFactor's etc. 8483 if (Depth == 0) return false; 8484 8485 // If this is a token factor, all inputs to the TF happen in parallel. 8486 if (getOpcode() == ISD::TokenFactor) { 8487 // First, try a shallow search. 8488 if (is_contained((*this)->ops(), Dest)) { 8489 // We found the chain we want as an operand of this TokenFactor. 8490 // Essentially, we reach the chain without side-effects if we could 8491 // serialize the TokenFactor into a simple chain of operations with 8492 // Dest as the last operation. This is automatically true if the 8493 // chain has one use: there are no other ordering constraints. 8494 // If the chain has more than one use, we give up: some other 8495 // use of Dest might force a side-effect between Dest and the current 8496 // node. 8497 if (Dest.hasOneUse()) 8498 return true; 8499 } 8500 // Next, try a deep search: check whether every operand of the TokenFactor 8501 // reaches Dest. 8502 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 8503 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 8504 }); 8505 } 8506 8507 // Loads don't have side effects, look through them. 8508 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 8509 if (!Ld->isVolatile()) 8510 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 8511 } 8512 return false; 8513 } 8514 8515 bool SDNode::hasPredecessor(const SDNode *N) const { 8516 SmallPtrSet<const SDNode *, 32> Visited; 8517 SmallVector<const SDNode *, 16> Worklist; 8518 Worklist.push_back(this); 8519 return hasPredecessorHelper(N, Visited, Worklist); 8520 } 8521 8522 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 8523 this->Flags.intersectWith(Flags); 8524 } 8525 8526 SDValue 8527 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 8528 ArrayRef<ISD::NodeType> CandidateBinOps) { 8529 // The pattern must end in an extract from index 0. 8530 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8531 !isNullConstant(Extract->getOperand(1))) 8532 return SDValue(); 8533 8534 SDValue Op = Extract->getOperand(0); 8535 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 8536 8537 // Match against one of the candidate binary ops. 8538 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 8539 return Op.getOpcode() == unsigned(BinOp); 8540 })) 8541 return SDValue(); 8542 8543 // At each stage, we're looking for something that looks like: 8544 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 8545 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 8546 // i32 undef, i32 undef, i32 undef, i32 undef> 8547 // %a = binop <8 x i32> %op, %s 8548 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 8549 // we expect something like: 8550 // <4,5,6,7,u,u,u,u> 8551 // <2,3,u,u,u,u,u,u> 8552 // <1,u,u,u,u,u,u,u> 8553 unsigned CandidateBinOp = Op.getOpcode(); 8554 for (unsigned i = 0; i < Stages; ++i) { 8555 if (Op.getOpcode() != CandidateBinOp) 8556 return SDValue(); 8557 8558 SDValue Op0 = Op.getOperand(0); 8559 SDValue Op1 = Op.getOperand(1); 8560 8561 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 8562 if (Shuffle) { 8563 Op = Op1; 8564 } else { 8565 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 8566 Op = Op0; 8567 } 8568 8569 // The first operand of the shuffle should be the same as the other operand 8570 // of the binop. 8571 if (!Shuffle || Shuffle->getOperand(0) != Op) 8572 return SDValue(); 8573 8574 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 8575 for (int Index = 0, MaskEnd = 1 << i; Index < MaskEnd; ++Index) 8576 if (Shuffle->getMaskElt(Index) != MaskEnd + Index) 8577 return SDValue(); 8578 } 8579 8580 BinOp = (ISD::NodeType)CandidateBinOp; 8581 return Op; 8582 } 8583 8584 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 8585 assert(N->getNumValues() == 1 && 8586 "Can't unroll a vector with multiple results!"); 8587 8588 EVT VT = N->getValueType(0); 8589 unsigned NE = VT.getVectorNumElements(); 8590 EVT EltVT = VT.getVectorElementType(); 8591 SDLoc dl(N); 8592 8593 SmallVector<SDValue, 8> Scalars; 8594 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 8595 8596 // If ResNE is 0, fully unroll the vector op. 8597 if (ResNE == 0) 8598 ResNE = NE; 8599 else if (NE > ResNE) 8600 NE = ResNE; 8601 8602 unsigned i; 8603 for (i= 0; i != NE; ++i) { 8604 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 8605 SDValue Operand = N->getOperand(j); 8606 EVT OperandVT = Operand.getValueType(); 8607 if (OperandVT.isVector()) { 8608 // A vector operand; extract a single element. 8609 EVT OperandEltVT = OperandVT.getVectorElementType(); 8610 Operands[j] = 8611 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand, 8612 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout()))); 8613 } else { 8614 // A scalar operand; just use it as is. 8615 Operands[j] = Operand; 8616 } 8617 } 8618 8619 switch (N->getOpcode()) { 8620 default: { 8621 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 8622 N->getFlags())); 8623 break; 8624 } 8625 case ISD::VSELECT: 8626 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 8627 break; 8628 case ISD::SHL: 8629 case ISD::SRA: 8630 case ISD::SRL: 8631 case ISD::ROTL: 8632 case ISD::ROTR: 8633 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 8634 getShiftAmountOperand(Operands[0].getValueType(), 8635 Operands[1]))); 8636 break; 8637 case ISD::SIGN_EXTEND_INREG: 8638 case ISD::FP_ROUND_INREG: { 8639 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 8640 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 8641 Operands[0], 8642 getValueType(ExtVT))); 8643 } 8644 } 8645 } 8646 8647 for (; i < ResNE; ++i) 8648 Scalars.push_back(getUNDEF(EltVT)); 8649 8650 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 8651 return getBuildVector(VecVT, dl, Scalars); 8652 } 8653 8654 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 8655 LoadSDNode *Base, 8656 unsigned Bytes, 8657 int Dist) const { 8658 if (LD->isVolatile() || Base->isVolatile()) 8659 return false; 8660 if (LD->isIndexed() || Base->isIndexed()) 8661 return false; 8662 if (LD->getChain() != Base->getChain()) 8663 return false; 8664 EVT VT = LD->getValueType(0); 8665 if (VT.getSizeInBits() / 8 != Bytes) 8666 return false; 8667 8668 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 8669 auto LocDecomp = BaseIndexOffset::match(LD, *this); 8670 8671 int64_t Offset = 0; 8672 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 8673 return (Dist * Bytes == Offset); 8674 return false; 8675 } 8676 8677 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if 8678 /// it cannot be inferred. 8679 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const { 8680 // If this is a GlobalAddress + cst, return the alignment. 8681 const GlobalValue *GV; 8682 int64_t GVOffset = 0; 8683 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 8684 unsigned IdxWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType()); 8685 KnownBits Known(IdxWidth); 8686 llvm::computeKnownBits(GV, Known, getDataLayout()); 8687 unsigned AlignBits = Known.countMinTrailingZeros(); 8688 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0; 8689 if (Align) 8690 return MinAlign(Align, GVOffset); 8691 } 8692 8693 // If this is a direct reference to a stack slot, use information about the 8694 // stack slot's alignment. 8695 int FrameIdx = 1 << 31; 8696 int64_t FrameOffset = 0; 8697 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 8698 FrameIdx = FI->getIndex(); 8699 } else if (isBaseWithConstantOffset(Ptr) && 8700 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 8701 // Handle FI+Cst 8702 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 8703 FrameOffset = Ptr.getConstantOperandVal(1); 8704 } 8705 8706 if (FrameIdx != (1 << 31)) { 8707 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 8708 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx), 8709 FrameOffset); 8710 return FIInfoAlign; 8711 } 8712 8713 return 0; 8714 } 8715 8716 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 8717 /// which is split (or expanded) into two not necessarily identical pieces. 8718 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 8719 // Currently all types are split in half. 8720 EVT LoVT, HiVT; 8721 if (!VT.isVector()) 8722 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 8723 else 8724 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 8725 8726 return std::make_pair(LoVT, HiVT); 8727 } 8728 8729 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 8730 /// low/high part. 8731 std::pair<SDValue, SDValue> 8732 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 8733 const EVT &HiVT) { 8734 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <= 8735 N.getValueType().getVectorNumElements() && 8736 "More vector elements requested than available!"); 8737 SDValue Lo, Hi; 8738 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, 8739 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout()))); 8740 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 8741 getConstant(LoVT.getVectorNumElements(), DL, 8742 TLI->getVectorIdxTy(getDataLayout()))); 8743 return std::make_pair(Lo, Hi); 8744 } 8745 8746 void SelectionDAG::ExtractVectorElements(SDValue Op, 8747 SmallVectorImpl<SDValue> &Args, 8748 unsigned Start, unsigned Count) { 8749 EVT VT = Op.getValueType(); 8750 if (Count == 0) 8751 Count = VT.getVectorNumElements(); 8752 8753 EVT EltVT = VT.getVectorElementType(); 8754 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout()); 8755 SDLoc SL(Op); 8756 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 8757 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 8758 Op, getConstant(i, SL, IdxTy))); 8759 } 8760 } 8761 8762 // getAddressSpace - Return the address space this GlobalAddress belongs to. 8763 unsigned GlobalAddressSDNode::getAddressSpace() const { 8764 return getGlobal()->getType()->getAddressSpace(); 8765 } 8766 8767 Type *ConstantPoolSDNode::getType() const { 8768 if (isMachineConstantPoolEntry()) 8769 return Val.MachineCPVal->getType(); 8770 return Val.ConstVal->getType(); 8771 } 8772 8773 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 8774 unsigned &SplatBitSize, 8775 bool &HasAnyUndefs, 8776 unsigned MinSplatBits, 8777 bool IsBigEndian) const { 8778 EVT VT = getValueType(0); 8779 assert(VT.isVector() && "Expected a vector type"); 8780 unsigned VecWidth = VT.getSizeInBits(); 8781 if (MinSplatBits > VecWidth) 8782 return false; 8783 8784 // FIXME: The widths are based on this node's type, but build vectors can 8785 // truncate their operands. 8786 SplatValue = APInt(VecWidth, 0); 8787 SplatUndef = APInt(VecWidth, 0); 8788 8789 // Get the bits. Bits with undefined values (when the corresponding element 8790 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 8791 // in SplatValue. If any of the values are not constant, give up and return 8792 // false. 8793 unsigned int NumOps = getNumOperands(); 8794 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 8795 unsigned EltWidth = VT.getScalarSizeInBits(); 8796 8797 for (unsigned j = 0; j < NumOps; ++j) { 8798 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 8799 SDValue OpVal = getOperand(i); 8800 unsigned BitPos = j * EltWidth; 8801 8802 if (OpVal.isUndef()) 8803 SplatUndef.setBits(BitPos, BitPos + EltWidth); 8804 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 8805 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 8806 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 8807 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 8808 else 8809 return false; 8810 } 8811 8812 // The build_vector is all constants or undefs. Find the smallest element 8813 // size that splats the vector. 8814 HasAnyUndefs = (SplatUndef != 0); 8815 8816 // FIXME: This does not work for vectors with elements less than 8 bits. 8817 while (VecWidth > 8) { 8818 unsigned HalfSize = VecWidth / 2; 8819 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 8820 APInt LowValue = SplatValue.trunc(HalfSize); 8821 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 8822 APInt LowUndef = SplatUndef.trunc(HalfSize); 8823 8824 // If the two halves do not match (ignoring undef bits), stop here. 8825 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 8826 MinSplatBits > HalfSize) 8827 break; 8828 8829 SplatValue = HighValue | LowValue; 8830 SplatUndef = HighUndef & LowUndef; 8831 8832 VecWidth = HalfSize; 8833 } 8834 8835 SplatBitSize = VecWidth; 8836 return true; 8837 } 8838 8839 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 8840 if (UndefElements) { 8841 UndefElements->clear(); 8842 UndefElements->resize(getNumOperands()); 8843 } 8844 SDValue Splatted; 8845 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 8846 SDValue Op = getOperand(i); 8847 if (Op.isUndef()) { 8848 if (UndefElements) 8849 (*UndefElements)[i] = true; 8850 } else if (!Splatted) { 8851 Splatted = Op; 8852 } else if (Splatted != Op) { 8853 return SDValue(); 8854 } 8855 } 8856 8857 if (!Splatted) { 8858 assert(getOperand(0).isUndef() && 8859 "Can only have a splat without a constant for all undefs."); 8860 return getOperand(0); 8861 } 8862 8863 return Splatted; 8864 } 8865 8866 ConstantSDNode * 8867 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 8868 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 8869 } 8870 8871 ConstantFPSDNode * 8872 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 8873 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 8874 } 8875 8876 int32_t 8877 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 8878 uint32_t BitWidth) const { 8879 if (ConstantFPSDNode *CN = 8880 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 8881 bool IsExact; 8882 APSInt IntVal(BitWidth); 8883 const APFloat &APF = CN->getValueAPF(); 8884 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 8885 APFloat::opOK || 8886 !IsExact) 8887 return -1; 8888 8889 return IntVal.exactLogBase2(); 8890 } 8891 return -1; 8892 } 8893 8894 bool BuildVectorSDNode::isConstant() const { 8895 for (const SDValue &Op : op_values()) { 8896 unsigned Opc = Op.getOpcode(); 8897 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 8898 return false; 8899 } 8900 return true; 8901 } 8902 8903 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 8904 // Find the first non-undef value in the shuffle mask. 8905 unsigned i, e; 8906 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 8907 /* search */; 8908 8909 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!"); 8910 8911 // Make sure all remaining elements are either undef or the same as the first 8912 // non-undef value. 8913 for (int Idx = Mask[i]; i != e; ++i) 8914 if (Mask[i] >= 0 && Mask[i] != Idx) 8915 return false; 8916 return true; 8917 } 8918 8919 // Returns the SDNode if it is a constant integer BuildVector 8920 // or constant integer. 8921 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) { 8922 if (isa<ConstantSDNode>(N)) 8923 return N.getNode(); 8924 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 8925 return N.getNode(); 8926 // Treat a GlobalAddress supporting constant offset folding as a 8927 // constant integer. 8928 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 8929 if (GA->getOpcode() == ISD::GlobalAddress && 8930 TLI->isOffsetFoldingLegal(GA)) 8931 return GA; 8932 return nullptr; 8933 } 8934 8935 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) { 8936 if (isa<ConstantFPSDNode>(N)) 8937 return N.getNode(); 8938 8939 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 8940 return N.getNode(); 8941 8942 return nullptr; 8943 } 8944 8945 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 8946 assert(!Node->OperandList && "Node already has operands"); 8947 SDUse *Ops = OperandRecycler.allocate( 8948 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 8949 8950 bool IsDivergent = false; 8951 for (unsigned I = 0; I != Vals.size(); ++I) { 8952 Ops[I].setUser(Node); 8953 Ops[I].setInitial(Vals[I]); 8954 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 8955 IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent(); 8956 } 8957 Node->NumOperands = Vals.size(); 8958 Node->OperandList = Ops; 8959 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 8960 if (!TLI->isSDNodeAlwaysUniform(Node)) 8961 Node->SDNodeBits.IsDivergent = IsDivergent; 8962 checkForCycles(Node); 8963 } 8964 8965 #ifndef NDEBUG 8966 static void checkForCyclesHelper(const SDNode *N, 8967 SmallPtrSetImpl<const SDNode*> &Visited, 8968 SmallPtrSetImpl<const SDNode*> &Checked, 8969 const llvm::SelectionDAG *DAG) { 8970 // If this node has already been checked, don't check it again. 8971 if (Checked.count(N)) 8972 return; 8973 8974 // If a node has already been visited on this depth-first walk, reject it as 8975 // a cycle. 8976 if (!Visited.insert(N).second) { 8977 errs() << "Detected cycle in SelectionDAG\n"; 8978 dbgs() << "Offending node:\n"; 8979 N->dumprFull(DAG); dbgs() << "\n"; 8980 abort(); 8981 } 8982 8983 for (const SDValue &Op : N->op_values()) 8984 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 8985 8986 Checked.insert(N); 8987 Visited.erase(N); 8988 } 8989 #endif 8990 8991 void llvm::checkForCycles(const llvm::SDNode *N, 8992 const llvm::SelectionDAG *DAG, 8993 bool force) { 8994 #ifndef NDEBUG 8995 bool check = force; 8996 #ifdef EXPENSIVE_CHECKS 8997 check = true; 8998 #endif // EXPENSIVE_CHECKS 8999 if (check) { 9000 assert(N && "Checking nonexistent SDNode"); 9001 SmallPtrSet<const SDNode*, 32> visited; 9002 SmallPtrSet<const SDNode*, 32> checked; 9003 checkForCyclesHelper(N, visited, checked, DAG); 9004 } 9005 #endif // !NDEBUG 9006 } 9007 9008 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 9009 checkForCycles(DAG->getRoot().getNode(), DAG, force); 9010 } 9011