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