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