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