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