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