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