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