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