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