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(llvm::Align(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 SDValue V(N, 0); 6608 NewSDValueDbgMsg(V, "Creating new node: ", this); 6609 return V; 6610 } 6611 6612 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 6613 SDValue Chain, int FrameIndex, 6614 int64_t Size, int64_t Offset) { 6615 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 6616 const auto VTs = getVTList(MVT::Other); 6617 SDValue Ops[2] = { 6618 Chain, 6619 getFrameIndex(FrameIndex, 6620 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 6621 true)}; 6622 6623 FoldingSetNodeID ID; 6624 AddNodeIDNode(ID, Opcode, VTs, Ops); 6625 ID.AddInteger(FrameIndex); 6626 ID.AddInteger(Size); 6627 ID.AddInteger(Offset); 6628 void *IP = nullptr; 6629 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 6630 return SDValue(E, 0); 6631 6632 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 6633 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 6634 createOperands(N, Ops); 6635 CSEMap.InsertNode(N, IP); 6636 InsertNode(N); 6637 SDValue V(N, 0); 6638 NewSDValueDbgMsg(V, "Creating new node: ", this); 6639 return V; 6640 } 6641 6642 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 6643 /// MachinePointerInfo record from it. This is particularly useful because the 6644 /// code generator has many cases where it doesn't bother passing in a 6645 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 6646 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 6647 SelectionDAG &DAG, SDValue Ptr, 6648 int64_t Offset = 0) { 6649 // If this is FI+Offset, we can model it. 6650 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 6651 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 6652 FI->getIndex(), Offset); 6653 6654 // If this is (FI+Offset1)+Offset2, we can model it. 6655 if (Ptr.getOpcode() != ISD::ADD || 6656 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 6657 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 6658 return Info; 6659 6660 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 6661 return MachinePointerInfo::getFixedStack( 6662 DAG.getMachineFunction(), FI, 6663 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 6664 } 6665 6666 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 6667 /// MachinePointerInfo record from it. This is particularly useful because the 6668 /// code generator has many cases where it doesn't bother passing in a 6669 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 6670 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 6671 SelectionDAG &DAG, SDValue Ptr, 6672 SDValue OffsetOp) { 6673 // If the 'Offset' value isn't a constant, we can't handle this. 6674 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 6675 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 6676 if (OffsetOp.isUndef()) 6677 return InferPointerInfo(Info, DAG, Ptr); 6678 return Info; 6679 } 6680 6681 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 6682 EVT VT, const SDLoc &dl, SDValue Chain, 6683 SDValue Ptr, SDValue Offset, 6684 MachinePointerInfo PtrInfo, EVT MemVT, 6685 unsigned Alignment, 6686 MachineMemOperand::Flags MMOFlags, 6687 const AAMDNodes &AAInfo, const MDNode *Ranges) { 6688 assert(Chain.getValueType() == MVT::Other && 6689 "Invalid chain type"); 6690 if (Alignment == 0) // Ensure that codegen never sees alignment 0 6691 Alignment = getEVTAlignment(MemVT); 6692 6693 MMOFlags |= MachineMemOperand::MOLoad; 6694 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 6695 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 6696 // clients. 6697 if (PtrInfo.V.isNull()) 6698 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 6699 6700 MachineFunction &MF = getMachineFunction(); 6701 MachineMemOperand *MMO = MF.getMachineMemOperand( 6702 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges); 6703 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 6704 } 6705 6706 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 6707 EVT VT, const SDLoc &dl, SDValue Chain, 6708 SDValue Ptr, SDValue Offset, EVT MemVT, 6709 MachineMemOperand *MMO) { 6710 if (VT == MemVT) { 6711 ExtType = ISD::NON_EXTLOAD; 6712 } else if (ExtType == ISD::NON_EXTLOAD) { 6713 assert(VT == MemVT && "Non-extending load from different memory type!"); 6714 } else { 6715 // Extending load. 6716 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 6717 "Should only be an extending load, not truncating!"); 6718 assert(VT.isInteger() == MemVT.isInteger() && 6719 "Cannot convert from FP to Int or Int -> FP!"); 6720 assert(VT.isVector() == MemVT.isVector() && 6721 "Cannot use an ext load to convert to or from a vector!"); 6722 assert((!VT.isVector() || 6723 VT.getVectorNumElements() == MemVT.getVectorNumElements()) && 6724 "Cannot use an ext load to change the number of vector elements!"); 6725 } 6726 6727 bool Indexed = AM != ISD::UNINDEXED; 6728 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 6729 6730 SDVTList VTs = Indexed ? 6731 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 6732 SDValue Ops[] = { Chain, Ptr, Offset }; 6733 FoldingSetNodeID ID; 6734 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 6735 ID.AddInteger(MemVT.getRawBits()); 6736 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 6737 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 6738 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6739 void *IP = nullptr; 6740 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6741 cast<LoadSDNode>(E)->refineAlignment(MMO); 6742 return SDValue(E, 0); 6743 } 6744 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 6745 ExtType, MemVT, MMO); 6746 createOperands(N, Ops); 6747 6748 CSEMap.InsertNode(N, IP); 6749 InsertNode(N); 6750 SDValue V(N, 0); 6751 NewSDValueDbgMsg(V, "Creating new node: ", this); 6752 return V; 6753 } 6754 6755 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 6756 SDValue Ptr, MachinePointerInfo PtrInfo, 6757 unsigned Alignment, 6758 MachineMemOperand::Flags MMOFlags, 6759 const AAMDNodes &AAInfo, const MDNode *Ranges) { 6760 SDValue Undef = getUNDEF(Ptr.getValueType()); 6761 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 6762 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 6763 } 6764 6765 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 6766 SDValue Ptr, MachineMemOperand *MMO) { 6767 SDValue Undef = getUNDEF(Ptr.getValueType()); 6768 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 6769 VT, MMO); 6770 } 6771 6772 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 6773 EVT VT, SDValue Chain, SDValue Ptr, 6774 MachinePointerInfo PtrInfo, EVT MemVT, 6775 unsigned Alignment, 6776 MachineMemOperand::Flags MMOFlags, 6777 const AAMDNodes &AAInfo) { 6778 SDValue Undef = getUNDEF(Ptr.getValueType()); 6779 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 6780 MemVT, Alignment, MMOFlags, AAInfo); 6781 } 6782 6783 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 6784 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 6785 MachineMemOperand *MMO) { 6786 SDValue Undef = getUNDEF(Ptr.getValueType()); 6787 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 6788 MemVT, MMO); 6789 } 6790 6791 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 6792 SDValue Base, SDValue Offset, 6793 ISD::MemIndexedMode AM) { 6794 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 6795 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 6796 // Don't propagate the invariant or dereferenceable flags. 6797 auto MMOFlags = 6798 LD->getMemOperand()->getFlags() & 6799 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 6800 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 6801 LD->getChain(), Base, Offset, LD->getPointerInfo(), 6802 LD->getMemoryVT(), LD->getAlignment(), MMOFlags, 6803 LD->getAAInfo()); 6804 } 6805 6806 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 6807 SDValue Ptr, MachinePointerInfo PtrInfo, 6808 unsigned Alignment, 6809 MachineMemOperand::Flags MMOFlags, 6810 const AAMDNodes &AAInfo) { 6811 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 6812 if (Alignment == 0) // Ensure that codegen never sees alignment 0 6813 Alignment = getEVTAlignment(Val.getValueType()); 6814 6815 MMOFlags |= MachineMemOperand::MOStore; 6816 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 6817 6818 if (PtrInfo.V.isNull()) 6819 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 6820 6821 MachineFunction &MF = getMachineFunction(); 6822 MachineMemOperand *MMO = MF.getMachineMemOperand( 6823 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo); 6824 return getStore(Chain, dl, Val, Ptr, MMO); 6825 } 6826 6827 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 6828 SDValue Ptr, MachineMemOperand *MMO) { 6829 assert(Chain.getValueType() == MVT::Other && 6830 "Invalid chain type"); 6831 EVT VT = Val.getValueType(); 6832 SDVTList VTs = getVTList(MVT::Other); 6833 SDValue Undef = getUNDEF(Ptr.getValueType()); 6834 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 6835 FoldingSetNodeID ID; 6836 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 6837 ID.AddInteger(VT.getRawBits()); 6838 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 6839 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 6840 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6841 void *IP = nullptr; 6842 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6843 cast<StoreSDNode>(E)->refineAlignment(MMO); 6844 return SDValue(E, 0); 6845 } 6846 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 6847 ISD::UNINDEXED, false, VT, MMO); 6848 createOperands(N, Ops); 6849 6850 CSEMap.InsertNode(N, IP); 6851 InsertNode(N); 6852 SDValue V(N, 0); 6853 NewSDValueDbgMsg(V, "Creating new node: ", this); 6854 return V; 6855 } 6856 6857 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 6858 SDValue Ptr, MachinePointerInfo PtrInfo, 6859 EVT SVT, unsigned Alignment, 6860 MachineMemOperand::Flags MMOFlags, 6861 const AAMDNodes &AAInfo) { 6862 assert(Chain.getValueType() == MVT::Other && 6863 "Invalid chain type"); 6864 if (Alignment == 0) // Ensure that codegen never sees alignment 0 6865 Alignment = getEVTAlignment(SVT); 6866 6867 MMOFlags |= MachineMemOperand::MOStore; 6868 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 6869 6870 if (PtrInfo.V.isNull()) 6871 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 6872 6873 MachineFunction &MF = getMachineFunction(); 6874 MachineMemOperand *MMO = MF.getMachineMemOperand( 6875 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo); 6876 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 6877 } 6878 6879 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 6880 SDValue Ptr, EVT SVT, 6881 MachineMemOperand *MMO) { 6882 EVT VT = Val.getValueType(); 6883 6884 assert(Chain.getValueType() == MVT::Other && 6885 "Invalid chain type"); 6886 if (VT == SVT) 6887 return getStore(Chain, dl, Val, Ptr, MMO); 6888 6889 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 6890 "Should only be a truncating store, not extending!"); 6891 assert(VT.isInteger() == SVT.isInteger() && 6892 "Can't do FP-INT conversion!"); 6893 assert(VT.isVector() == SVT.isVector() && 6894 "Cannot use trunc store to convert to or from a vector!"); 6895 assert((!VT.isVector() || 6896 VT.getVectorNumElements() == SVT.getVectorNumElements()) && 6897 "Cannot use trunc store to change the number of vector elements!"); 6898 6899 SDVTList VTs = getVTList(MVT::Other); 6900 SDValue Undef = getUNDEF(Ptr.getValueType()); 6901 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 6902 FoldingSetNodeID ID; 6903 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 6904 ID.AddInteger(SVT.getRawBits()); 6905 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 6906 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 6907 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6908 void *IP = nullptr; 6909 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6910 cast<StoreSDNode>(E)->refineAlignment(MMO); 6911 return SDValue(E, 0); 6912 } 6913 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 6914 ISD::UNINDEXED, true, SVT, MMO); 6915 createOperands(N, Ops); 6916 6917 CSEMap.InsertNode(N, IP); 6918 InsertNode(N); 6919 SDValue V(N, 0); 6920 NewSDValueDbgMsg(V, "Creating new node: ", this); 6921 return V; 6922 } 6923 6924 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 6925 SDValue Base, SDValue Offset, 6926 ISD::MemIndexedMode AM) { 6927 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 6928 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 6929 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 6930 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 6931 FoldingSetNodeID ID; 6932 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 6933 ID.AddInteger(ST->getMemoryVT().getRawBits()); 6934 ID.AddInteger(ST->getRawSubclassData()); 6935 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 6936 void *IP = nullptr; 6937 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 6938 return SDValue(E, 0); 6939 6940 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 6941 ST->isTruncatingStore(), ST->getMemoryVT(), 6942 ST->getMemOperand()); 6943 createOperands(N, Ops); 6944 6945 CSEMap.InsertNode(N, IP); 6946 InsertNode(N); 6947 SDValue V(N, 0); 6948 NewSDValueDbgMsg(V, "Creating new node: ", this); 6949 return V; 6950 } 6951 6952 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 6953 SDValue Ptr, SDValue Mask, SDValue PassThru, 6954 EVT MemVT, MachineMemOperand *MMO, 6955 ISD::LoadExtType ExtTy, bool isExpanding) { 6956 SDVTList VTs = getVTList(VT, MVT::Other); 6957 SDValue Ops[] = { Chain, Ptr, Mask, PassThru }; 6958 FoldingSetNodeID ID; 6959 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 6960 ID.AddInteger(MemVT.getRawBits()); 6961 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 6962 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO)); 6963 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6964 void *IP = nullptr; 6965 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6966 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 6967 return SDValue(E, 0); 6968 } 6969 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 6970 ExtTy, isExpanding, MemVT, MMO); 6971 createOperands(N, Ops); 6972 6973 CSEMap.InsertNode(N, IP); 6974 InsertNode(N); 6975 SDValue V(N, 0); 6976 NewSDValueDbgMsg(V, "Creating new node: ", this); 6977 return V; 6978 } 6979 6980 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 6981 SDValue Val, SDValue Ptr, SDValue Mask, 6982 EVT MemVT, MachineMemOperand *MMO, 6983 bool IsTruncating, bool IsCompressing) { 6984 assert(Chain.getValueType() == MVT::Other && 6985 "Invalid chain type"); 6986 SDVTList VTs = getVTList(MVT::Other); 6987 SDValue Ops[] = { Chain, Val, Ptr, Mask }; 6988 FoldingSetNodeID ID; 6989 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 6990 ID.AddInteger(MemVT.getRawBits()); 6991 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 6992 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO)); 6993 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6994 void *IP = nullptr; 6995 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6996 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 6997 return SDValue(E, 0); 6998 } 6999 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7000 IsTruncating, IsCompressing, MemVT, MMO); 7001 createOperands(N, Ops); 7002 7003 CSEMap.InsertNode(N, IP); 7004 InsertNode(N); 7005 SDValue V(N, 0); 7006 NewSDValueDbgMsg(V, "Creating new node: ", this); 7007 return V; 7008 } 7009 7010 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl, 7011 ArrayRef<SDValue> Ops, 7012 MachineMemOperand *MMO) { 7013 assert(Ops.size() == 6 && "Incompatible number of operands"); 7014 7015 FoldingSetNodeID ID; 7016 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 7017 ID.AddInteger(VT.getRawBits()); 7018 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 7019 dl.getIROrder(), VTs, VT, MMO)); 7020 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7021 void *IP = nullptr; 7022 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7023 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 7024 return SDValue(E, 0); 7025 } 7026 7027 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7028 VTs, VT, MMO); 7029 createOperands(N, Ops); 7030 7031 assert(N->getPassThru().getValueType() == N->getValueType(0) && 7032 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 7033 assert(N->getMask().getValueType().getVectorNumElements() == 7034 N->getValueType(0).getVectorNumElements() && 7035 "Vector width mismatch between mask and data"); 7036 assert(N->getIndex().getValueType().getVectorNumElements() >= 7037 N->getValueType(0).getVectorNumElements() && 7038 "Vector width mismatch between index and data"); 7039 assert(isa<ConstantSDNode>(N->getScale()) && 7040 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7041 "Scale should be a constant power of 2"); 7042 7043 CSEMap.InsertNode(N, IP); 7044 InsertNode(N); 7045 SDValue V(N, 0); 7046 NewSDValueDbgMsg(V, "Creating new node: ", this); 7047 return V; 7048 } 7049 7050 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl, 7051 ArrayRef<SDValue> Ops, 7052 MachineMemOperand *MMO) { 7053 assert(Ops.size() == 6 && "Incompatible number of operands"); 7054 7055 FoldingSetNodeID ID; 7056 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 7057 ID.AddInteger(VT.getRawBits()); 7058 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 7059 dl.getIROrder(), VTs, VT, MMO)); 7060 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7061 void *IP = nullptr; 7062 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7063 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 7064 return SDValue(E, 0); 7065 } 7066 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7067 VTs, VT, MMO); 7068 createOperands(N, Ops); 7069 7070 assert(N->getMask().getValueType().getVectorNumElements() == 7071 N->getValue().getValueType().getVectorNumElements() && 7072 "Vector width mismatch between mask and data"); 7073 assert(N->getIndex().getValueType().getVectorNumElements() >= 7074 N->getValue().getValueType().getVectorNumElements() && 7075 "Vector width mismatch between index and data"); 7076 assert(isa<ConstantSDNode>(N->getScale()) && 7077 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7078 "Scale should be a constant power of 2"); 7079 7080 CSEMap.InsertNode(N, IP); 7081 InsertNode(N); 7082 SDValue V(N, 0); 7083 NewSDValueDbgMsg(V, "Creating new node: ", this); 7084 return V; 7085 } 7086 7087 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 7088 // select undef, T, F --> T (if T is a constant), otherwise F 7089 // select, ?, undef, F --> F 7090 // select, ?, T, undef --> T 7091 if (Cond.isUndef()) 7092 return isConstantValueOfAnyType(T) ? T : F; 7093 if (T.isUndef()) 7094 return F; 7095 if (F.isUndef()) 7096 return T; 7097 7098 // select true, T, F --> T 7099 // select false, T, F --> F 7100 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 7101 return CondC->isNullValue() ? F : T; 7102 7103 // TODO: This should simplify VSELECT with constant condition using something 7104 // like this (but check boolean contents to be complete?): 7105 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 7106 // return T; 7107 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 7108 // return F; 7109 7110 // select ?, T, T --> T 7111 if (T == F) 7112 return T; 7113 7114 return SDValue(); 7115 } 7116 7117 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 7118 // shift undef, Y --> 0 (can always assume that the undef value is 0) 7119 if (X.isUndef()) 7120 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 7121 // shift X, undef --> undef (because it may shift by the bitwidth) 7122 if (Y.isUndef()) 7123 return getUNDEF(X.getValueType()); 7124 7125 // shift 0, Y --> 0 7126 // shift X, 0 --> X 7127 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 7128 return X; 7129 7130 // shift X, C >= bitwidth(X) --> undef 7131 // All vector elements must be too big (or undef) to avoid partial undefs. 7132 auto isShiftTooBig = [X](ConstantSDNode *Val) { 7133 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 7134 }; 7135 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 7136 return getUNDEF(X.getValueType()); 7137 7138 return SDValue(); 7139 } 7140 7141 // TODO: Use fast-math-flags to enable more simplifications. 7142 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y) { 7143 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 7144 if (!YC) 7145 return SDValue(); 7146 7147 // X + -0.0 --> X 7148 if (Opcode == ISD::FADD) 7149 if (YC->getValueAPF().isNegZero()) 7150 return X; 7151 7152 // X - +0.0 --> X 7153 if (Opcode == ISD::FSUB) 7154 if (YC->getValueAPF().isPosZero()) 7155 return X; 7156 7157 // X * 1.0 --> X 7158 // X / 1.0 --> X 7159 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 7160 if (YC->getValueAPF().isExactlyValue(1.0)) 7161 return X; 7162 7163 return SDValue(); 7164 } 7165 7166 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 7167 SDValue Ptr, SDValue SV, unsigned Align) { 7168 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 7169 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 7170 } 7171 7172 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7173 ArrayRef<SDUse> Ops) { 7174 switch (Ops.size()) { 7175 case 0: return getNode(Opcode, DL, VT); 7176 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 7177 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 7178 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 7179 default: break; 7180 } 7181 7182 // Copy from an SDUse array into an SDValue array for use with 7183 // the regular getNode logic. 7184 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 7185 return getNode(Opcode, DL, VT, NewOps); 7186 } 7187 7188 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7189 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7190 unsigned NumOps = Ops.size(); 7191 switch (NumOps) { 7192 case 0: return getNode(Opcode, DL, VT); 7193 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 7194 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 7195 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 7196 default: break; 7197 } 7198 7199 switch (Opcode) { 7200 default: break; 7201 case ISD::BUILD_VECTOR: 7202 // Attempt to simplify BUILD_VECTOR. 7203 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 7204 return V; 7205 break; 7206 case ISD::CONCAT_VECTORS: 7207 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 7208 return V; 7209 break; 7210 case ISD::SELECT_CC: 7211 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 7212 assert(Ops[0].getValueType() == Ops[1].getValueType() && 7213 "LHS and RHS of condition must have same type!"); 7214 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7215 "True and False arms of SelectCC must have same type!"); 7216 assert(Ops[2].getValueType() == VT && 7217 "select_cc node must be of same type as true and false value!"); 7218 break; 7219 case ISD::BR_CC: 7220 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 7221 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7222 "LHS/RHS of comparison should match types!"); 7223 break; 7224 } 7225 7226 // Memoize nodes. 7227 SDNode *N; 7228 SDVTList VTs = getVTList(VT); 7229 7230 if (VT != MVT::Glue) { 7231 FoldingSetNodeID ID; 7232 AddNodeIDNode(ID, Opcode, VTs, Ops); 7233 void *IP = nullptr; 7234 7235 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7236 return SDValue(E, 0); 7237 7238 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7239 createOperands(N, Ops); 7240 7241 CSEMap.InsertNode(N, IP); 7242 } else { 7243 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7244 createOperands(N, Ops); 7245 } 7246 7247 InsertNode(N); 7248 SDValue V(N, 0); 7249 NewSDValueDbgMsg(V, "Creating new node: ", this); 7250 return V; 7251 } 7252 7253 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7254 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 7255 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 7256 } 7257 7258 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7259 ArrayRef<SDValue> Ops) { 7260 if (VTList.NumVTs == 1) 7261 return getNode(Opcode, DL, VTList.VTs[0], Ops); 7262 7263 #if 0 7264 switch (Opcode) { 7265 // FIXME: figure out how to safely handle things like 7266 // int foo(int x) { return 1 << (x & 255); } 7267 // int bar() { return foo(256); } 7268 case ISD::SRA_PARTS: 7269 case ISD::SRL_PARTS: 7270 case ISD::SHL_PARTS: 7271 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 7272 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 7273 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7274 else if (N3.getOpcode() == ISD::AND) 7275 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 7276 // If the and is only masking out bits that cannot effect the shift, 7277 // eliminate the and. 7278 unsigned NumBits = VT.getScalarSizeInBits()*2; 7279 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 7280 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7281 } 7282 break; 7283 } 7284 #endif 7285 7286 // Memoize the node unless it returns a flag. 7287 SDNode *N; 7288 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7289 FoldingSetNodeID ID; 7290 AddNodeIDNode(ID, Opcode, VTList, Ops); 7291 void *IP = nullptr; 7292 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7293 return SDValue(E, 0); 7294 7295 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7296 createOperands(N, Ops); 7297 CSEMap.InsertNode(N, IP); 7298 } else { 7299 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7300 createOperands(N, Ops); 7301 } 7302 InsertNode(N); 7303 SDValue V(N, 0); 7304 NewSDValueDbgMsg(V, "Creating new node: ", this); 7305 return V; 7306 } 7307 7308 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7309 SDVTList VTList) { 7310 return getNode(Opcode, DL, VTList, None); 7311 } 7312 7313 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7314 SDValue N1) { 7315 SDValue Ops[] = { N1 }; 7316 return getNode(Opcode, DL, VTList, Ops); 7317 } 7318 7319 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7320 SDValue N1, SDValue N2) { 7321 SDValue Ops[] = { N1, N2 }; 7322 return getNode(Opcode, DL, VTList, Ops); 7323 } 7324 7325 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7326 SDValue N1, SDValue N2, SDValue N3) { 7327 SDValue Ops[] = { N1, N2, N3 }; 7328 return getNode(Opcode, DL, VTList, Ops); 7329 } 7330 7331 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7332 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 7333 SDValue Ops[] = { N1, N2, N3, N4 }; 7334 return getNode(Opcode, DL, VTList, Ops); 7335 } 7336 7337 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7338 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 7339 SDValue N5) { 7340 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 7341 return getNode(Opcode, DL, VTList, Ops); 7342 } 7343 7344 SDVTList SelectionDAG::getVTList(EVT VT) { 7345 return makeVTList(SDNode::getValueTypeList(VT), 1); 7346 } 7347 7348 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 7349 FoldingSetNodeID ID; 7350 ID.AddInteger(2U); 7351 ID.AddInteger(VT1.getRawBits()); 7352 ID.AddInteger(VT2.getRawBits()); 7353 7354 void *IP = nullptr; 7355 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7356 if (!Result) { 7357 EVT *Array = Allocator.Allocate<EVT>(2); 7358 Array[0] = VT1; 7359 Array[1] = VT2; 7360 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 7361 VTListMap.InsertNode(Result, IP); 7362 } 7363 return Result->getSDVTList(); 7364 } 7365 7366 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 7367 FoldingSetNodeID ID; 7368 ID.AddInteger(3U); 7369 ID.AddInteger(VT1.getRawBits()); 7370 ID.AddInteger(VT2.getRawBits()); 7371 ID.AddInteger(VT3.getRawBits()); 7372 7373 void *IP = nullptr; 7374 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7375 if (!Result) { 7376 EVT *Array = Allocator.Allocate<EVT>(3); 7377 Array[0] = VT1; 7378 Array[1] = VT2; 7379 Array[2] = VT3; 7380 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 7381 VTListMap.InsertNode(Result, IP); 7382 } 7383 return Result->getSDVTList(); 7384 } 7385 7386 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 7387 FoldingSetNodeID ID; 7388 ID.AddInteger(4U); 7389 ID.AddInteger(VT1.getRawBits()); 7390 ID.AddInteger(VT2.getRawBits()); 7391 ID.AddInteger(VT3.getRawBits()); 7392 ID.AddInteger(VT4.getRawBits()); 7393 7394 void *IP = nullptr; 7395 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7396 if (!Result) { 7397 EVT *Array = Allocator.Allocate<EVT>(4); 7398 Array[0] = VT1; 7399 Array[1] = VT2; 7400 Array[2] = VT3; 7401 Array[3] = VT4; 7402 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 7403 VTListMap.InsertNode(Result, IP); 7404 } 7405 return Result->getSDVTList(); 7406 } 7407 7408 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 7409 unsigned NumVTs = VTs.size(); 7410 FoldingSetNodeID ID; 7411 ID.AddInteger(NumVTs); 7412 for (unsigned index = 0; index < NumVTs; index++) { 7413 ID.AddInteger(VTs[index].getRawBits()); 7414 } 7415 7416 void *IP = nullptr; 7417 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7418 if (!Result) { 7419 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 7420 llvm::copy(VTs, Array); 7421 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 7422 VTListMap.InsertNode(Result, IP); 7423 } 7424 return Result->getSDVTList(); 7425 } 7426 7427 7428 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 7429 /// specified operands. If the resultant node already exists in the DAG, 7430 /// this does not modify the specified node, instead it returns the node that 7431 /// already exists. If the resultant node does not exist in the DAG, the 7432 /// input node is returned. As a degenerate case, if you specify the same 7433 /// input operands as the node already has, the input node is returned. 7434 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 7435 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 7436 7437 // Check to see if there is no change. 7438 if (Op == N->getOperand(0)) return N; 7439 7440 // See if the modified node already exists. 7441 void *InsertPos = nullptr; 7442 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 7443 return Existing; 7444 7445 // Nope it doesn't. Remove the node from its current place in the maps. 7446 if (InsertPos) 7447 if (!RemoveNodeFromCSEMaps(N)) 7448 InsertPos = nullptr; 7449 7450 // Now we update the operands. 7451 N->OperandList[0].set(Op); 7452 7453 updateDivergence(N); 7454 // If this gets put into a CSE map, add it. 7455 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7456 return N; 7457 } 7458 7459 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 7460 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 7461 7462 // Check to see if there is no change. 7463 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 7464 return N; // No operands changed, just return the input node. 7465 7466 // See if the modified node already exists. 7467 void *InsertPos = nullptr; 7468 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 7469 return Existing; 7470 7471 // Nope it doesn't. Remove the node from its current place in the maps. 7472 if (InsertPos) 7473 if (!RemoveNodeFromCSEMaps(N)) 7474 InsertPos = nullptr; 7475 7476 // Now we update the operands. 7477 if (N->OperandList[0] != Op1) 7478 N->OperandList[0].set(Op1); 7479 if (N->OperandList[1] != Op2) 7480 N->OperandList[1].set(Op2); 7481 7482 updateDivergence(N); 7483 // If this gets put into a CSE map, add it. 7484 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7485 return N; 7486 } 7487 7488 SDNode *SelectionDAG:: 7489 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 7490 SDValue Ops[] = { Op1, Op2, Op3 }; 7491 return UpdateNodeOperands(N, Ops); 7492 } 7493 7494 SDNode *SelectionDAG:: 7495 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 7496 SDValue Op3, SDValue Op4) { 7497 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 7498 return UpdateNodeOperands(N, Ops); 7499 } 7500 7501 SDNode *SelectionDAG:: 7502 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 7503 SDValue Op3, SDValue Op4, SDValue Op5) { 7504 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 7505 return UpdateNodeOperands(N, Ops); 7506 } 7507 7508 SDNode *SelectionDAG:: 7509 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 7510 unsigned NumOps = Ops.size(); 7511 assert(N->getNumOperands() == NumOps && 7512 "Update with wrong number of operands"); 7513 7514 // If no operands changed just return the input node. 7515 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 7516 return N; 7517 7518 // See if the modified node already exists. 7519 void *InsertPos = nullptr; 7520 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 7521 return Existing; 7522 7523 // Nope it doesn't. Remove the node from its current place in the maps. 7524 if (InsertPos) 7525 if (!RemoveNodeFromCSEMaps(N)) 7526 InsertPos = nullptr; 7527 7528 // Now we update the operands. 7529 for (unsigned i = 0; i != NumOps; ++i) 7530 if (N->OperandList[i] != Ops[i]) 7531 N->OperandList[i].set(Ops[i]); 7532 7533 updateDivergence(N); 7534 // If this gets put into a CSE map, add it. 7535 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7536 return N; 7537 } 7538 7539 /// DropOperands - Release the operands and set this node to have 7540 /// zero operands. 7541 void SDNode::DropOperands() { 7542 // Unlike the code in MorphNodeTo that does this, we don't need to 7543 // watch for dead nodes here. 7544 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 7545 SDUse &Use = *I++; 7546 Use.set(SDValue()); 7547 } 7548 } 7549 7550 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 7551 ArrayRef<MachineMemOperand *> NewMemRefs) { 7552 if (NewMemRefs.empty()) { 7553 N->clearMemRefs(); 7554 return; 7555 } 7556 7557 // Check if we can avoid allocating by storing a single reference directly. 7558 if (NewMemRefs.size() == 1) { 7559 N->MemRefs = NewMemRefs[0]; 7560 N->NumMemRefs = 1; 7561 return; 7562 } 7563 7564 MachineMemOperand **MemRefsBuffer = 7565 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 7566 llvm::copy(NewMemRefs, MemRefsBuffer); 7567 N->MemRefs = MemRefsBuffer; 7568 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 7569 } 7570 7571 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 7572 /// machine opcode. 7573 /// 7574 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7575 EVT VT) { 7576 SDVTList VTs = getVTList(VT); 7577 return SelectNodeTo(N, MachineOpc, VTs, None); 7578 } 7579 7580 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7581 EVT VT, SDValue Op1) { 7582 SDVTList VTs = getVTList(VT); 7583 SDValue Ops[] = { Op1 }; 7584 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7585 } 7586 7587 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7588 EVT VT, SDValue Op1, 7589 SDValue Op2) { 7590 SDVTList VTs = getVTList(VT); 7591 SDValue Ops[] = { Op1, Op2 }; 7592 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7593 } 7594 7595 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7596 EVT VT, SDValue Op1, 7597 SDValue Op2, SDValue Op3) { 7598 SDVTList VTs = getVTList(VT); 7599 SDValue Ops[] = { Op1, Op2, Op3 }; 7600 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7601 } 7602 7603 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7604 EVT VT, ArrayRef<SDValue> Ops) { 7605 SDVTList VTs = getVTList(VT); 7606 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7607 } 7608 7609 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7610 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 7611 SDVTList VTs = getVTList(VT1, VT2); 7612 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7613 } 7614 7615 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7616 EVT VT1, EVT VT2) { 7617 SDVTList VTs = getVTList(VT1, VT2); 7618 return SelectNodeTo(N, MachineOpc, VTs, None); 7619 } 7620 7621 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7622 EVT VT1, EVT VT2, EVT VT3, 7623 ArrayRef<SDValue> Ops) { 7624 SDVTList VTs = getVTList(VT1, VT2, VT3); 7625 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7626 } 7627 7628 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7629 EVT VT1, EVT VT2, 7630 SDValue Op1, SDValue Op2) { 7631 SDVTList VTs = getVTList(VT1, VT2); 7632 SDValue Ops[] = { Op1, Op2 }; 7633 return SelectNodeTo(N, MachineOpc, VTs, Ops); 7634 } 7635 7636 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 7637 SDVTList VTs,ArrayRef<SDValue> Ops) { 7638 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 7639 // Reset the NodeID to -1. 7640 New->setNodeId(-1); 7641 if (New != N) { 7642 ReplaceAllUsesWith(N, New); 7643 RemoveDeadNode(N); 7644 } 7645 return New; 7646 } 7647 7648 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 7649 /// the line number information on the merged node since it is not possible to 7650 /// preserve the information that operation is associated with multiple lines. 7651 /// This will make the debugger working better at -O0, were there is a higher 7652 /// probability having other instructions associated with that line. 7653 /// 7654 /// For IROrder, we keep the smaller of the two 7655 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 7656 DebugLoc NLoc = N->getDebugLoc(); 7657 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 7658 N->setDebugLoc(DebugLoc()); 7659 } 7660 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 7661 N->setIROrder(Order); 7662 return N; 7663 } 7664 7665 /// MorphNodeTo - This *mutates* the specified node to have the specified 7666 /// return type, opcode, and operands. 7667 /// 7668 /// Note that MorphNodeTo returns the resultant node. If there is already a 7669 /// node of the specified opcode and operands, it returns that node instead of 7670 /// the current one. Note that the SDLoc need not be the same. 7671 /// 7672 /// Using MorphNodeTo is faster than creating a new node and swapping it in 7673 /// with ReplaceAllUsesWith both because it often avoids allocating a new 7674 /// node, and because it doesn't require CSE recalculation for any of 7675 /// the node's users. 7676 /// 7677 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 7678 /// As a consequence it isn't appropriate to use from within the DAG combiner or 7679 /// the legalizer which maintain worklists that would need to be updated when 7680 /// deleting things. 7681 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 7682 SDVTList VTs, ArrayRef<SDValue> Ops) { 7683 // If an identical node already exists, use it. 7684 void *IP = nullptr; 7685 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 7686 FoldingSetNodeID ID; 7687 AddNodeIDNode(ID, Opc, VTs, Ops); 7688 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 7689 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 7690 } 7691 7692 if (!RemoveNodeFromCSEMaps(N)) 7693 IP = nullptr; 7694 7695 // Start the morphing. 7696 N->NodeType = Opc; 7697 N->ValueList = VTs.VTs; 7698 N->NumValues = VTs.NumVTs; 7699 7700 // Clear the operands list, updating used nodes to remove this from their 7701 // use list. Keep track of any operands that become dead as a result. 7702 SmallPtrSet<SDNode*, 16> DeadNodeSet; 7703 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 7704 SDUse &Use = *I++; 7705 SDNode *Used = Use.getNode(); 7706 Use.set(SDValue()); 7707 if (Used->use_empty()) 7708 DeadNodeSet.insert(Used); 7709 } 7710 7711 // For MachineNode, initialize the memory references information. 7712 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 7713 MN->clearMemRefs(); 7714 7715 // Swap for an appropriately sized array from the recycler. 7716 removeOperands(N); 7717 createOperands(N, Ops); 7718 7719 // Delete any nodes that are still dead after adding the uses for the 7720 // new operands. 7721 if (!DeadNodeSet.empty()) { 7722 SmallVector<SDNode *, 16> DeadNodes; 7723 for (SDNode *N : DeadNodeSet) 7724 if (N->use_empty()) 7725 DeadNodes.push_back(N); 7726 RemoveDeadNodes(DeadNodes); 7727 } 7728 7729 if (IP) 7730 CSEMap.InsertNode(N, IP); // Memoize the new node. 7731 return N; 7732 } 7733 7734 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 7735 unsigned OrigOpc = Node->getOpcode(); 7736 unsigned NewOpc; 7737 switch (OrigOpc) { 7738 default: 7739 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 7740 case ISD::STRICT_FADD: NewOpc = ISD::FADD; break; 7741 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break; 7742 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break; 7743 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break; 7744 case ISD::STRICT_FREM: NewOpc = ISD::FREM; break; 7745 case ISD::STRICT_FMA: NewOpc = ISD::FMA; break; 7746 case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; break; 7747 case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break; 7748 case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break; 7749 case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; break; 7750 case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; break; 7751 case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; break; 7752 case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; break; 7753 case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; break; 7754 case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; break; 7755 case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; break; 7756 case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; break; 7757 case ISD::STRICT_FNEARBYINT: NewOpc = ISD::FNEARBYINT; break; 7758 case ISD::STRICT_FMAXNUM: NewOpc = ISD::FMAXNUM; break; 7759 case ISD::STRICT_FMINNUM: NewOpc = ISD::FMINNUM; break; 7760 case ISD::STRICT_FCEIL: NewOpc = ISD::FCEIL; break; 7761 case ISD::STRICT_FFLOOR: NewOpc = ISD::FFLOOR; break; 7762 case ISD::STRICT_FROUND: NewOpc = ISD::FROUND; break; 7763 case ISD::STRICT_FTRUNC: NewOpc = ISD::FTRUNC; break; 7764 case ISD::STRICT_FP_ROUND: NewOpc = ISD::FP_ROUND; break; 7765 case ISD::STRICT_FP_EXTEND: NewOpc = ISD::FP_EXTEND; break; 7766 } 7767 7768 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 7769 7770 // We're taking this node out of the chain, so we need to re-link things. 7771 SDValue InputChain = Node->getOperand(0); 7772 SDValue OutputChain = SDValue(Node, 1); 7773 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 7774 7775 SmallVector<SDValue, 3> Ops; 7776 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 7777 Ops.push_back(Node->getOperand(i)); 7778 7779 SDVTList VTs = getVTList(Node->getValueType(0)); 7780 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 7781 7782 // MorphNodeTo can operate in two ways: if an existing node with the 7783 // specified operands exists, it can just return it. Otherwise, it 7784 // updates the node in place to have the requested operands. 7785 if (Res == Node) { 7786 // If we updated the node in place, reset the node ID. To the isel, 7787 // this should be just like a newly allocated machine node. 7788 Res->setNodeId(-1); 7789 } else { 7790 ReplaceAllUsesWith(Node, Res); 7791 RemoveDeadNode(Node); 7792 } 7793 7794 return Res; 7795 } 7796 7797 /// getMachineNode - These are used for target selectors to create a new node 7798 /// with specified return type(s), MachineInstr opcode, and operands. 7799 /// 7800 /// Note that getMachineNode returns the resultant node. If there is already a 7801 /// node of the specified opcode and operands, it returns that node instead of 7802 /// the current one. 7803 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7804 EVT VT) { 7805 SDVTList VTs = getVTList(VT); 7806 return getMachineNode(Opcode, dl, VTs, None); 7807 } 7808 7809 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7810 EVT VT, SDValue Op1) { 7811 SDVTList VTs = getVTList(VT); 7812 SDValue Ops[] = { Op1 }; 7813 return getMachineNode(Opcode, dl, VTs, Ops); 7814 } 7815 7816 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7817 EVT VT, SDValue Op1, SDValue Op2) { 7818 SDVTList VTs = getVTList(VT); 7819 SDValue Ops[] = { Op1, Op2 }; 7820 return getMachineNode(Opcode, dl, VTs, Ops); 7821 } 7822 7823 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7824 EVT VT, SDValue Op1, SDValue Op2, 7825 SDValue Op3) { 7826 SDVTList VTs = getVTList(VT); 7827 SDValue Ops[] = { Op1, Op2, Op3 }; 7828 return getMachineNode(Opcode, dl, VTs, Ops); 7829 } 7830 7831 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7832 EVT VT, ArrayRef<SDValue> Ops) { 7833 SDVTList VTs = getVTList(VT); 7834 return getMachineNode(Opcode, dl, VTs, Ops); 7835 } 7836 7837 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7838 EVT VT1, EVT VT2, SDValue Op1, 7839 SDValue Op2) { 7840 SDVTList VTs = getVTList(VT1, VT2); 7841 SDValue Ops[] = { Op1, Op2 }; 7842 return getMachineNode(Opcode, dl, VTs, Ops); 7843 } 7844 7845 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7846 EVT VT1, EVT VT2, SDValue Op1, 7847 SDValue Op2, SDValue Op3) { 7848 SDVTList VTs = getVTList(VT1, VT2); 7849 SDValue Ops[] = { Op1, Op2, Op3 }; 7850 return getMachineNode(Opcode, dl, VTs, Ops); 7851 } 7852 7853 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7854 EVT VT1, EVT VT2, 7855 ArrayRef<SDValue> Ops) { 7856 SDVTList VTs = getVTList(VT1, VT2); 7857 return getMachineNode(Opcode, dl, VTs, Ops); 7858 } 7859 7860 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7861 EVT VT1, EVT VT2, EVT VT3, 7862 SDValue Op1, SDValue Op2) { 7863 SDVTList VTs = getVTList(VT1, VT2, VT3); 7864 SDValue Ops[] = { Op1, Op2 }; 7865 return getMachineNode(Opcode, dl, VTs, Ops); 7866 } 7867 7868 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7869 EVT VT1, EVT VT2, EVT VT3, 7870 SDValue Op1, SDValue Op2, 7871 SDValue Op3) { 7872 SDVTList VTs = getVTList(VT1, VT2, VT3); 7873 SDValue Ops[] = { Op1, Op2, Op3 }; 7874 return getMachineNode(Opcode, dl, VTs, Ops); 7875 } 7876 7877 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7878 EVT VT1, EVT VT2, EVT VT3, 7879 ArrayRef<SDValue> Ops) { 7880 SDVTList VTs = getVTList(VT1, VT2, VT3); 7881 return getMachineNode(Opcode, dl, VTs, Ops); 7882 } 7883 7884 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 7885 ArrayRef<EVT> ResultTys, 7886 ArrayRef<SDValue> Ops) { 7887 SDVTList VTs = getVTList(ResultTys); 7888 return getMachineNode(Opcode, dl, VTs, Ops); 7889 } 7890 7891 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 7892 SDVTList VTs, 7893 ArrayRef<SDValue> Ops) { 7894 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 7895 MachineSDNode *N; 7896 void *IP = nullptr; 7897 7898 if (DoCSE) { 7899 FoldingSetNodeID ID; 7900 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 7901 IP = nullptr; 7902 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 7903 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 7904 } 7905 } 7906 7907 // Allocate a new MachineSDNode. 7908 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7909 createOperands(N, Ops); 7910 7911 if (DoCSE) 7912 CSEMap.InsertNode(N, IP); 7913 7914 InsertNode(N); 7915 return N; 7916 } 7917 7918 /// getTargetExtractSubreg - A convenience function for creating 7919 /// TargetOpcode::EXTRACT_SUBREG nodes. 7920 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 7921 SDValue Operand) { 7922 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 7923 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 7924 VT, Operand, SRIdxVal); 7925 return SDValue(Subreg, 0); 7926 } 7927 7928 /// getTargetInsertSubreg - A convenience function for creating 7929 /// TargetOpcode::INSERT_SUBREG nodes. 7930 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 7931 SDValue Operand, SDValue Subreg) { 7932 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 7933 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 7934 VT, Operand, Subreg, SRIdxVal); 7935 return SDValue(Result, 0); 7936 } 7937 7938 /// getNodeIfExists - Get the specified node if it's already available, or 7939 /// else return NULL. 7940 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 7941 ArrayRef<SDValue> Ops, 7942 const SDNodeFlags Flags) { 7943 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 7944 FoldingSetNodeID ID; 7945 AddNodeIDNode(ID, Opcode, VTList, Ops); 7946 void *IP = nullptr; 7947 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 7948 E->intersectFlagsWith(Flags); 7949 return E; 7950 } 7951 } 7952 return nullptr; 7953 } 7954 7955 /// getDbgValue - Creates a SDDbgValue node. 7956 /// 7957 /// SDNode 7958 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 7959 SDNode *N, unsigned R, bool IsIndirect, 7960 const DebugLoc &DL, unsigned O) { 7961 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 7962 "Expected inlined-at fields to agree"); 7963 return new (DbgInfo->getAlloc()) 7964 SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O); 7965 } 7966 7967 /// Constant 7968 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 7969 DIExpression *Expr, 7970 const Value *C, 7971 const DebugLoc &DL, unsigned O) { 7972 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 7973 "Expected inlined-at fields to agree"); 7974 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O); 7975 } 7976 7977 /// FrameIndex 7978 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 7979 DIExpression *Expr, unsigned FI, 7980 bool IsIndirect, 7981 const DebugLoc &DL, 7982 unsigned O) { 7983 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 7984 "Expected inlined-at fields to agree"); 7985 return new (DbgInfo->getAlloc()) 7986 SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX); 7987 } 7988 7989 /// VReg 7990 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, 7991 DIExpression *Expr, 7992 unsigned VReg, bool IsIndirect, 7993 const DebugLoc &DL, unsigned O) { 7994 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 7995 "Expected inlined-at fields to agree"); 7996 return new (DbgInfo->getAlloc()) 7997 SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG); 7998 } 7999 8000 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 8001 unsigned OffsetInBits, unsigned SizeInBits, 8002 bool InvalidateDbg) { 8003 SDNode *FromNode = From.getNode(); 8004 SDNode *ToNode = To.getNode(); 8005 assert(FromNode && ToNode && "Can't modify dbg values"); 8006 8007 // PR35338 8008 // TODO: assert(From != To && "Redundant dbg value transfer"); 8009 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 8010 if (From == To || FromNode == ToNode) 8011 return; 8012 8013 if (!FromNode->getHasDebugValue()) 8014 return; 8015 8016 SmallVector<SDDbgValue *, 2> ClonedDVs; 8017 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 8018 if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated()) 8019 continue; 8020 8021 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 8022 8023 // Just transfer the dbg value attached to From. 8024 if (Dbg->getResNo() != From.getResNo()) 8025 continue; 8026 8027 DIVariable *Var = Dbg->getVariable(); 8028 auto *Expr = Dbg->getExpression(); 8029 // If a fragment is requested, update the expression. 8030 if (SizeInBits) { 8031 // When splitting a larger (e.g., sign-extended) value whose 8032 // lower bits are described with an SDDbgValue, do not attempt 8033 // to transfer the SDDbgValue to the upper bits. 8034 if (auto FI = Expr->getFragmentInfo()) 8035 if (OffsetInBits + SizeInBits > FI->SizeInBits) 8036 continue; 8037 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 8038 SizeInBits); 8039 if (!Fragment) 8040 continue; 8041 Expr = *Fragment; 8042 } 8043 // Clone the SDDbgValue and move it to To. 8044 SDDbgValue *Clone = 8045 getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(), 8046 Dbg->getDebugLoc(), Dbg->getOrder()); 8047 ClonedDVs.push_back(Clone); 8048 8049 if (InvalidateDbg) { 8050 // Invalidate value and indicate the SDDbgValue should not be emitted. 8051 Dbg->setIsInvalidated(); 8052 Dbg->setIsEmitted(); 8053 } 8054 } 8055 8056 for (SDDbgValue *Dbg : ClonedDVs) 8057 AddDbgValue(Dbg, ToNode, false); 8058 } 8059 8060 void SelectionDAG::salvageDebugInfo(SDNode &N) { 8061 if (!N.getHasDebugValue()) 8062 return; 8063 8064 SmallVector<SDDbgValue *, 2> ClonedDVs; 8065 for (auto DV : GetDbgValues(&N)) { 8066 if (DV->isInvalidated()) 8067 continue; 8068 switch (N.getOpcode()) { 8069 default: 8070 break; 8071 case ISD::ADD: 8072 SDValue N0 = N.getOperand(0); 8073 SDValue N1 = N.getOperand(1); 8074 if (!isConstantIntBuildVectorOrConstantInt(N0) && 8075 isConstantIntBuildVectorOrConstantInt(N1)) { 8076 uint64_t Offset = N.getConstantOperandVal(1); 8077 // Rewrite an ADD constant node into a DIExpression. Since we are 8078 // performing arithmetic to compute the variable's *value* in the 8079 // DIExpression, we need to mark the expression with a 8080 // DW_OP_stack_value. 8081 auto *DIExpr = DV->getExpression(); 8082 DIExpr = 8083 DIExpression::prepend(DIExpr, DIExpression::StackValue, Offset); 8084 SDDbgValue *Clone = 8085 getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(), 8086 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder()); 8087 ClonedDVs.push_back(Clone); 8088 DV->setIsInvalidated(); 8089 DV->setIsEmitted(); 8090 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 8091 N0.getNode()->dumprFull(this); 8092 dbgs() << " into " << *DIExpr << '\n'); 8093 } 8094 } 8095 } 8096 8097 for (SDDbgValue *Dbg : ClonedDVs) 8098 AddDbgValue(Dbg, Dbg->getSDNode(), false); 8099 } 8100 8101 /// Creates a SDDbgLabel node. 8102 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 8103 const DebugLoc &DL, unsigned O) { 8104 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 8105 "Expected inlined-at fields to agree"); 8106 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 8107 } 8108 8109 namespace { 8110 8111 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 8112 /// pointed to by a use iterator is deleted, increment the use iterator 8113 /// so that it doesn't dangle. 8114 /// 8115 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 8116 SDNode::use_iterator &UI; 8117 SDNode::use_iterator &UE; 8118 8119 void NodeDeleted(SDNode *N, SDNode *E) override { 8120 // Increment the iterator as needed. 8121 while (UI != UE && N == *UI) 8122 ++UI; 8123 } 8124 8125 public: 8126 RAUWUpdateListener(SelectionDAG &d, 8127 SDNode::use_iterator &ui, 8128 SDNode::use_iterator &ue) 8129 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 8130 }; 8131 8132 } // end anonymous namespace 8133 8134 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8135 /// This can cause recursive merging of nodes in the DAG. 8136 /// 8137 /// This version assumes From has a single result value. 8138 /// 8139 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 8140 SDNode *From = FromN.getNode(); 8141 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 8142 "Cannot replace with this method!"); 8143 assert(From != To.getNode() && "Cannot replace uses of with self"); 8144 8145 // Preserve Debug Values 8146 transferDbgValues(FromN, To); 8147 8148 // Iterate over all the existing uses of From. New uses will be added 8149 // to the beginning of the use list, which we avoid visiting. 8150 // This specifically avoids visiting uses of From that arise while the 8151 // replacement is happening, because any such uses would be the result 8152 // of CSE: If an existing node looks like From after one of its operands 8153 // is replaced by To, we don't want to replace of all its users with To 8154 // too. See PR3018 for more info. 8155 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8156 RAUWUpdateListener Listener(*this, UI, UE); 8157 while (UI != UE) { 8158 SDNode *User = *UI; 8159 8160 // This node is about to morph, remove its old self from the CSE maps. 8161 RemoveNodeFromCSEMaps(User); 8162 8163 // A user can appear in a use list multiple times, and when this 8164 // happens the uses are usually next to each other in the list. 8165 // To help reduce the number of CSE recomputations, process all 8166 // the uses of this user that we can find this way. 8167 do { 8168 SDUse &Use = UI.getUse(); 8169 ++UI; 8170 Use.set(To); 8171 if (To->isDivergent() != From->isDivergent()) 8172 updateDivergence(User); 8173 } while (UI != UE && *UI == User); 8174 // Now that we have modified User, add it back to the CSE maps. If it 8175 // already exists there, recursively merge the results together. 8176 AddModifiedNodeToCSEMaps(User); 8177 } 8178 8179 // If we just RAUW'd the root, take note. 8180 if (FromN == getRoot()) 8181 setRoot(To); 8182 } 8183 8184 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8185 /// This can cause recursive merging of nodes in the DAG. 8186 /// 8187 /// This version assumes that for each value of From, there is a 8188 /// corresponding value in To in the same position with the same type. 8189 /// 8190 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 8191 #ifndef NDEBUG 8192 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8193 assert((!From->hasAnyUseOfValue(i) || 8194 From->getValueType(i) == To->getValueType(i)) && 8195 "Cannot use this version of ReplaceAllUsesWith!"); 8196 #endif 8197 8198 // Handle the trivial case. 8199 if (From == To) 8200 return; 8201 8202 // Preserve Debug Info. Only do this if there's a use. 8203 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8204 if (From->hasAnyUseOfValue(i)) { 8205 assert((i < To->getNumValues()) && "Invalid To location"); 8206 transferDbgValues(SDValue(From, i), SDValue(To, i)); 8207 } 8208 8209 // Iterate over just the existing users of From. See the comments in 8210 // the ReplaceAllUsesWith above. 8211 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8212 RAUWUpdateListener Listener(*this, UI, UE); 8213 while (UI != UE) { 8214 SDNode *User = *UI; 8215 8216 // This node is about to morph, remove its old self from the CSE maps. 8217 RemoveNodeFromCSEMaps(User); 8218 8219 // A user can appear in a use list multiple times, and when this 8220 // happens the uses are usually next to each other in the list. 8221 // To help reduce the number of CSE recomputations, process all 8222 // the uses of this user that we can find this way. 8223 do { 8224 SDUse &Use = UI.getUse(); 8225 ++UI; 8226 Use.setNode(To); 8227 if (To->isDivergent() != From->isDivergent()) 8228 updateDivergence(User); 8229 } while (UI != UE && *UI == User); 8230 8231 // Now that we have modified User, add it back to the CSE maps. If it 8232 // already exists there, recursively merge the results together. 8233 AddModifiedNodeToCSEMaps(User); 8234 } 8235 8236 // If we just RAUW'd the root, take note. 8237 if (From == getRoot().getNode()) 8238 setRoot(SDValue(To, getRoot().getResNo())); 8239 } 8240 8241 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8242 /// This can cause recursive merging of nodes in the DAG. 8243 /// 8244 /// This version can replace From with any result values. To must match the 8245 /// number and types of values returned by From. 8246 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 8247 if (From->getNumValues() == 1) // Handle the simple case efficiently. 8248 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 8249 8250 // Preserve Debug Info. 8251 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8252 transferDbgValues(SDValue(From, i), To[i]); 8253 8254 // Iterate over just the existing users of From. See the comments in 8255 // the ReplaceAllUsesWith above. 8256 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8257 RAUWUpdateListener Listener(*this, UI, UE); 8258 while (UI != UE) { 8259 SDNode *User = *UI; 8260 8261 // This node is about to morph, remove its old self from the CSE maps. 8262 RemoveNodeFromCSEMaps(User); 8263 8264 // A user can appear in a use list multiple times, and when this happens the 8265 // uses are usually next to each other in the list. To help reduce the 8266 // number of CSE and divergence recomputations, process all the uses of this 8267 // user that we can find this way. 8268 bool To_IsDivergent = false; 8269 do { 8270 SDUse &Use = UI.getUse(); 8271 const SDValue &ToOp = To[Use.getResNo()]; 8272 ++UI; 8273 Use.set(ToOp); 8274 To_IsDivergent |= ToOp->isDivergent(); 8275 } while (UI != UE && *UI == User); 8276 8277 if (To_IsDivergent != From->isDivergent()) 8278 updateDivergence(User); 8279 8280 // Now that we have modified User, add it back to the CSE maps. If it 8281 // already exists there, recursively merge the results together. 8282 AddModifiedNodeToCSEMaps(User); 8283 } 8284 8285 // If we just RAUW'd the root, take note. 8286 if (From == getRoot().getNode()) 8287 setRoot(SDValue(To[getRoot().getResNo()])); 8288 } 8289 8290 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 8291 /// uses of other values produced by From.getNode() alone. The Deleted 8292 /// vector is handled the same way as for ReplaceAllUsesWith. 8293 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 8294 // Handle the really simple, really trivial case efficiently. 8295 if (From == To) return; 8296 8297 // Handle the simple, trivial, case efficiently. 8298 if (From.getNode()->getNumValues() == 1) { 8299 ReplaceAllUsesWith(From, To); 8300 return; 8301 } 8302 8303 // Preserve Debug Info. 8304 transferDbgValues(From, To); 8305 8306 // Iterate over just the existing users of From. See the comments in 8307 // the ReplaceAllUsesWith above. 8308 SDNode::use_iterator UI = From.getNode()->use_begin(), 8309 UE = From.getNode()->use_end(); 8310 RAUWUpdateListener Listener(*this, UI, UE); 8311 while (UI != UE) { 8312 SDNode *User = *UI; 8313 bool UserRemovedFromCSEMaps = false; 8314 8315 // A user can appear in a use list multiple times, and when this 8316 // happens the uses are usually next to each other in the list. 8317 // To help reduce the number of CSE recomputations, process all 8318 // the uses of this user that we can find this way. 8319 do { 8320 SDUse &Use = UI.getUse(); 8321 8322 // Skip uses of different values from the same node. 8323 if (Use.getResNo() != From.getResNo()) { 8324 ++UI; 8325 continue; 8326 } 8327 8328 // If this node hasn't been modified yet, it's still in the CSE maps, 8329 // so remove its old self from the CSE maps. 8330 if (!UserRemovedFromCSEMaps) { 8331 RemoveNodeFromCSEMaps(User); 8332 UserRemovedFromCSEMaps = true; 8333 } 8334 8335 ++UI; 8336 Use.set(To); 8337 if (To->isDivergent() != From->isDivergent()) 8338 updateDivergence(User); 8339 } while (UI != UE && *UI == User); 8340 // We are iterating over all uses of the From node, so if a use 8341 // doesn't use the specific value, no changes are made. 8342 if (!UserRemovedFromCSEMaps) 8343 continue; 8344 8345 // Now that we have modified User, add it back to the CSE maps. If it 8346 // already exists there, recursively merge the results together. 8347 AddModifiedNodeToCSEMaps(User); 8348 } 8349 8350 // If we just RAUW'd the root, take note. 8351 if (From == getRoot()) 8352 setRoot(To); 8353 } 8354 8355 namespace { 8356 8357 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 8358 /// to record information about a use. 8359 struct UseMemo { 8360 SDNode *User; 8361 unsigned Index; 8362 SDUse *Use; 8363 }; 8364 8365 /// operator< - Sort Memos by User. 8366 bool operator<(const UseMemo &L, const UseMemo &R) { 8367 return (intptr_t)L.User < (intptr_t)R.User; 8368 } 8369 8370 } // end anonymous namespace 8371 8372 void SelectionDAG::updateDivergence(SDNode * N) 8373 { 8374 if (TLI->isSDNodeAlwaysUniform(N)) 8375 return; 8376 bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 8377 for (auto &Op : N->ops()) { 8378 if (Op.Val.getValueType() != MVT::Other) 8379 IsDivergent |= Op.getNode()->isDivergent(); 8380 } 8381 if (N->SDNodeBits.IsDivergent != IsDivergent) { 8382 N->SDNodeBits.IsDivergent = IsDivergent; 8383 for (auto U : N->uses()) { 8384 updateDivergence(U); 8385 } 8386 } 8387 } 8388 8389 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 8390 DenseMap<SDNode *, unsigned> Degree; 8391 Order.reserve(AllNodes.size()); 8392 for (auto &N : allnodes()) { 8393 unsigned NOps = N.getNumOperands(); 8394 Degree[&N] = NOps; 8395 if (0 == NOps) 8396 Order.push_back(&N); 8397 } 8398 for (size_t I = 0; I != Order.size(); ++I) { 8399 SDNode *N = Order[I]; 8400 for (auto U : N->uses()) { 8401 unsigned &UnsortedOps = Degree[U]; 8402 if (0 == --UnsortedOps) 8403 Order.push_back(U); 8404 } 8405 } 8406 } 8407 8408 #ifndef NDEBUG 8409 void SelectionDAG::VerifyDAGDiverence() { 8410 std::vector<SDNode *> TopoOrder; 8411 CreateTopologicalOrder(TopoOrder); 8412 const TargetLowering &TLI = getTargetLoweringInfo(); 8413 DenseMap<const SDNode *, bool> DivergenceMap; 8414 for (auto &N : allnodes()) { 8415 DivergenceMap[&N] = false; 8416 } 8417 for (auto N : TopoOrder) { 8418 bool IsDivergent = DivergenceMap[N]; 8419 bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA); 8420 for (auto &Op : N->ops()) { 8421 if (Op.Val.getValueType() != MVT::Other) 8422 IsSDNodeDivergent |= DivergenceMap[Op.getNode()]; 8423 } 8424 if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) { 8425 DivergenceMap[N] = true; 8426 } 8427 } 8428 for (auto &N : allnodes()) { 8429 (void)N; 8430 assert(DivergenceMap[&N] == N.isDivergent() && 8431 "Divergence bit inconsistency detected\n"); 8432 } 8433 } 8434 #endif 8435 8436 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 8437 /// uses of other values produced by From.getNode() alone. The same value 8438 /// may appear in both the From and To list. The Deleted vector is 8439 /// handled the same way as for ReplaceAllUsesWith. 8440 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 8441 const SDValue *To, 8442 unsigned Num){ 8443 // Handle the simple, trivial case efficiently. 8444 if (Num == 1) 8445 return ReplaceAllUsesOfValueWith(*From, *To); 8446 8447 transferDbgValues(*From, *To); 8448 8449 // Read up all the uses and make records of them. This helps 8450 // processing new uses that are introduced during the 8451 // replacement process. 8452 SmallVector<UseMemo, 4> Uses; 8453 for (unsigned i = 0; i != Num; ++i) { 8454 unsigned FromResNo = From[i].getResNo(); 8455 SDNode *FromNode = From[i].getNode(); 8456 for (SDNode::use_iterator UI = FromNode->use_begin(), 8457 E = FromNode->use_end(); UI != E; ++UI) { 8458 SDUse &Use = UI.getUse(); 8459 if (Use.getResNo() == FromResNo) { 8460 UseMemo Memo = { *UI, i, &Use }; 8461 Uses.push_back(Memo); 8462 } 8463 } 8464 } 8465 8466 // Sort the uses, so that all the uses from a given User are together. 8467 llvm::sort(Uses); 8468 8469 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 8470 UseIndex != UseIndexEnd; ) { 8471 // We know that this user uses some value of From. If it is the right 8472 // value, update it. 8473 SDNode *User = Uses[UseIndex].User; 8474 8475 // This node is about to morph, remove its old self from the CSE maps. 8476 RemoveNodeFromCSEMaps(User); 8477 8478 // The Uses array is sorted, so all the uses for a given User 8479 // are next to each other in the list. 8480 // To help reduce the number of CSE recomputations, process all 8481 // the uses of this user that we can find this way. 8482 do { 8483 unsigned i = Uses[UseIndex].Index; 8484 SDUse &Use = *Uses[UseIndex].Use; 8485 ++UseIndex; 8486 8487 Use.set(To[i]); 8488 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 8489 8490 // Now that we have modified User, add it back to the CSE maps. If it 8491 // already exists there, recursively merge the results together. 8492 AddModifiedNodeToCSEMaps(User); 8493 } 8494 } 8495 8496 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 8497 /// based on their topological order. It returns the maximum id and a vector 8498 /// of the SDNodes* in assigned order by reference. 8499 unsigned SelectionDAG::AssignTopologicalOrder() { 8500 unsigned DAGSize = 0; 8501 8502 // SortedPos tracks the progress of the algorithm. Nodes before it are 8503 // sorted, nodes after it are unsorted. When the algorithm completes 8504 // it is at the end of the list. 8505 allnodes_iterator SortedPos = allnodes_begin(); 8506 8507 // Visit all the nodes. Move nodes with no operands to the front of 8508 // the list immediately. Annotate nodes that do have operands with their 8509 // operand count. Before we do this, the Node Id fields of the nodes 8510 // may contain arbitrary values. After, the Node Id fields for nodes 8511 // before SortedPos will contain the topological sort index, and the 8512 // Node Id fields for nodes At SortedPos and after will contain the 8513 // count of outstanding operands. 8514 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 8515 SDNode *N = &*I++; 8516 checkForCycles(N, this); 8517 unsigned Degree = N->getNumOperands(); 8518 if (Degree == 0) { 8519 // A node with no uses, add it to the result array immediately. 8520 N->setNodeId(DAGSize++); 8521 allnodes_iterator Q(N); 8522 if (Q != SortedPos) 8523 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 8524 assert(SortedPos != AllNodes.end() && "Overran node list"); 8525 ++SortedPos; 8526 } else { 8527 // Temporarily use the Node Id as scratch space for the degree count. 8528 N->setNodeId(Degree); 8529 } 8530 } 8531 8532 // Visit all the nodes. As we iterate, move nodes into sorted order, 8533 // such that by the time the end is reached all nodes will be sorted. 8534 for (SDNode &Node : allnodes()) { 8535 SDNode *N = &Node; 8536 checkForCycles(N, this); 8537 // N is in sorted position, so all its uses have one less operand 8538 // that needs to be sorted. 8539 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 8540 UI != UE; ++UI) { 8541 SDNode *P = *UI; 8542 unsigned Degree = P->getNodeId(); 8543 assert(Degree != 0 && "Invalid node degree"); 8544 --Degree; 8545 if (Degree == 0) { 8546 // All of P's operands are sorted, so P may sorted now. 8547 P->setNodeId(DAGSize++); 8548 if (P->getIterator() != SortedPos) 8549 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 8550 assert(SortedPos != AllNodes.end() && "Overran node list"); 8551 ++SortedPos; 8552 } else { 8553 // Update P's outstanding operand count. 8554 P->setNodeId(Degree); 8555 } 8556 } 8557 if (Node.getIterator() == SortedPos) { 8558 #ifndef NDEBUG 8559 allnodes_iterator I(N); 8560 SDNode *S = &*++I; 8561 dbgs() << "Overran sorted position:\n"; 8562 S->dumprFull(this); dbgs() << "\n"; 8563 dbgs() << "Checking if this is due to cycles\n"; 8564 checkForCycles(this, true); 8565 #endif 8566 llvm_unreachable(nullptr); 8567 } 8568 } 8569 8570 assert(SortedPos == AllNodes.end() && 8571 "Topological sort incomplete!"); 8572 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 8573 "First node in topological sort is not the entry token!"); 8574 assert(AllNodes.front().getNodeId() == 0 && 8575 "First node in topological sort has non-zero id!"); 8576 assert(AllNodes.front().getNumOperands() == 0 && 8577 "First node in topological sort has operands!"); 8578 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 8579 "Last node in topologic sort has unexpected id!"); 8580 assert(AllNodes.back().use_empty() && 8581 "Last node in topologic sort has users!"); 8582 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 8583 return DAGSize; 8584 } 8585 8586 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 8587 /// value is produced by SD. 8588 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) { 8589 if (SD) { 8590 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 8591 SD->setHasDebugValue(true); 8592 } 8593 DbgInfo->add(DB, SD, isParameter); 8594 } 8595 8596 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { 8597 DbgInfo->add(DB); 8598 } 8599 8600 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 8601 SDValue NewMemOp) { 8602 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 8603 // The new memory operation must have the same position as the old load in 8604 // terms of memory dependency. Create a TokenFactor for the old load and new 8605 // memory operation and update uses of the old load's output chain to use that 8606 // TokenFactor. 8607 SDValue OldChain = SDValue(OldLoad, 1); 8608 SDValue NewChain = SDValue(NewMemOp.getNode(), 1); 8609 if (OldChain == NewChain || !OldLoad->hasAnyUseOfValue(1)) 8610 return NewChain; 8611 8612 SDValue TokenFactor = 8613 getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain); 8614 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 8615 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain); 8616 return TokenFactor; 8617 } 8618 8619 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 8620 Function **OutFunction) { 8621 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 8622 8623 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 8624 auto *Module = MF->getFunction().getParent(); 8625 auto *Function = Module->getFunction(Symbol); 8626 8627 if (OutFunction != nullptr) 8628 *OutFunction = Function; 8629 8630 if (Function != nullptr) { 8631 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 8632 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 8633 } 8634 8635 std::string ErrorStr; 8636 raw_string_ostream ErrorFormatter(ErrorStr); 8637 8638 ErrorFormatter << "Undefined external symbol "; 8639 ErrorFormatter << '"' << Symbol << '"'; 8640 ErrorFormatter.flush(); 8641 8642 report_fatal_error(ErrorStr); 8643 } 8644 8645 //===----------------------------------------------------------------------===// 8646 // SDNode Class 8647 //===----------------------------------------------------------------------===// 8648 8649 bool llvm::isNullConstant(SDValue V) { 8650 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 8651 return Const != nullptr && Const->isNullValue(); 8652 } 8653 8654 bool llvm::isNullFPConstant(SDValue V) { 8655 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 8656 return Const != nullptr && Const->isZero() && !Const->isNegative(); 8657 } 8658 8659 bool llvm::isAllOnesConstant(SDValue V) { 8660 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 8661 return Const != nullptr && Const->isAllOnesValue(); 8662 } 8663 8664 bool llvm::isOneConstant(SDValue V) { 8665 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 8666 return Const != nullptr && Const->isOne(); 8667 } 8668 8669 SDValue llvm::peekThroughBitcasts(SDValue V) { 8670 while (V.getOpcode() == ISD::BITCAST) 8671 V = V.getOperand(0); 8672 return V; 8673 } 8674 8675 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 8676 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 8677 V = V.getOperand(0); 8678 return V; 8679 } 8680 8681 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 8682 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 8683 V = V.getOperand(0); 8684 return V; 8685 } 8686 8687 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 8688 if (V.getOpcode() != ISD::XOR) 8689 return false; 8690 V = peekThroughBitcasts(V.getOperand(1)); 8691 unsigned NumBits = V.getScalarValueSizeInBits(); 8692 ConstantSDNode *C = 8693 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 8694 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 8695 } 8696 8697 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 8698 bool AllowTruncation) { 8699 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 8700 return CN; 8701 8702 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 8703 BitVector UndefElements; 8704 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 8705 8706 // BuildVectors can truncate their operands. Ignore that case here unless 8707 // AllowTruncation is set. 8708 if (CN && (UndefElements.none() || AllowUndefs)) { 8709 EVT CVT = CN->getValueType(0); 8710 EVT NSVT = N.getValueType().getScalarType(); 8711 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 8712 if (AllowTruncation || (CVT == NSVT)) 8713 return CN; 8714 } 8715 } 8716 8717 return nullptr; 8718 } 8719 8720 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 8721 bool AllowUndefs, 8722 bool AllowTruncation) { 8723 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 8724 return CN; 8725 8726 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 8727 BitVector UndefElements; 8728 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 8729 8730 // BuildVectors can truncate their operands. Ignore that case here unless 8731 // AllowTruncation is set. 8732 if (CN && (UndefElements.none() || AllowUndefs)) { 8733 EVT CVT = CN->getValueType(0); 8734 EVT NSVT = N.getValueType().getScalarType(); 8735 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 8736 if (AllowTruncation || (CVT == NSVT)) 8737 return CN; 8738 } 8739 } 8740 8741 return nullptr; 8742 } 8743 8744 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 8745 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 8746 return CN; 8747 8748 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 8749 BitVector UndefElements; 8750 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 8751 if (CN && (UndefElements.none() || AllowUndefs)) 8752 return CN; 8753 } 8754 8755 return nullptr; 8756 } 8757 8758 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 8759 const APInt &DemandedElts, 8760 bool AllowUndefs) { 8761 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 8762 return CN; 8763 8764 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 8765 BitVector UndefElements; 8766 ConstantFPSDNode *CN = 8767 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 8768 if (CN && (UndefElements.none() || AllowUndefs)) 8769 return CN; 8770 } 8771 8772 return nullptr; 8773 } 8774 8775 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 8776 // TODO: may want to use peekThroughBitcast() here. 8777 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 8778 return C && C->isNullValue(); 8779 } 8780 8781 bool llvm::isOneOrOneSplat(SDValue N) { 8782 // TODO: may want to use peekThroughBitcast() here. 8783 unsigned BitWidth = N.getScalarValueSizeInBits(); 8784 ConstantSDNode *C = isConstOrConstSplat(N); 8785 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 8786 } 8787 8788 bool llvm::isAllOnesOrAllOnesSplat(SDValue N) { 8789 N = peekThroughBitcasts(N); 8790 unsigned BitWidth = N.getScalarValueSizeInBits(); 8791 ConstantSDNode *C = isConstOrConstSplat(N); 8792 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth; 8793 } 8794 8795 HandleSDNode::~HandleSDNode() { 8796 DropOperands(); 8797 } 8798 8799 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 8800 const DebugLoc &DL, 8801 const GlobalValue *GA, EVT VT, 8802 int64_t o, unsigned TF) 8803 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 8804 TheGlobal = GA; 8805 } 8806 8807 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 8808 EVT VT, unsigned SrcAS, 8809 unsigned DestAS) 8810 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 8811 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 8812 8813 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 8814 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 8815 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 8816 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 8817 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 8818 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 8819 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 8820 8821 // We check here that the size of the memory operand fits within the size of 8822 // the MMO. This is because the MMO might indicate only a possible address 8823 // range instead of specifying the affected memory addresses precisely. 8824 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!"); 8825 } 8826 8827 /// Profile - Gather unique data for the node. 8828 /// 8829 void SDNode::Profile(FoldingSetNodeID &ID) const { 8830 AddNodeIDNode(ID, this); 8831 } 8832 8833 namespace { 8834 8835 struct EVTArray { 8836 std::vector<EVT> VTs; 8837 8838 EVTArray() { 8839 VTs.reserve(MVT::LAST_VALUETYPE); 8840 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 8841 VTs.push_back(MVT((MVT::SimpleValueType)i)); 8842 } 8843 }; 8844 8845 } // end anonymous namespace 8846 8847 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 8848 static ManagedStatic<EVTArray> SimpleVTArray; 8849 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 8850 8851 /// getValueTypeList - Return a pointer to the specified value type. 8852 /// 8853 const EVT *SDNode::getValueTypeList(EVT VT) { 8854 if (VT.isExtended()) { 8855 sys::SmartScopedLock<true> Lock(*VTMutex); 8856 return &(*EVTs->insert(VT).first); 8857 } else { 8858 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 8859 "Value type out of range!"); 8860 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 8861 } 8862 } 8863 8864 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 8865 /// indicated value. This method ignores uses of other values defined by this 8866 /// operation. 8867 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 8868 assert(Value < getNumValues() && "Bad value!"); 8869 8870 // TODO: Only iterate over uses of a given value of the node 8871 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 8872 if (UI.getUse().getResNo() == Value) { 8873 if (NUses == 0) 8874 return false; 8875 --NUses; 8876 } 8877 } 8878 8879 // Found exactly the right number of uses? 8880 return NUses == 0; 8881 } 8882 8883 /// hasAnyUseOfValue - Return true if there are any use of the indicated 8884 /// value. This method ignores uses of other values defined by this operation. 8885 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 8886 assert(Value < getNumValues() && "Bad value!"); 8887 8888 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 8889 if (UI.getUse().getResNo() == Value) 8890 return true; 8891 8892 return false; 8893 } 8894 8895 /// isOnlyUserOf - Return true if this node is the only use of N. 8896 bool SDNode::isOnlyUserOf(const SDNode *N) const { 8897 bool Seen = false; 8898 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 8899 SDNode *User = *I; 8900 if (User == this) 8901 Seen = true; 8902 else 8903 return false; 8904 } 8905 8906 return Seen; 8907 } 8908 8909 /// Return true if the only users of N are contained in Nodes. 8910 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 8911 bool Seen = false; 8912 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 8913 SDNode *User = *I; 8914 if (llvm::any_of(Nodes, 8915 [&User](const SDNode *Node) { return User == Node; })) 8916 Seen = true; 8917 else 8918 return false; 8919 } 8920 8921 return Seen; 8922 } 8923 8924 /// isOperand - Return true if this node is an operand of N. 8925 bool SDValue::isOperandOf(const SDNode *N) const { 8926 return any_of(N->op_values(), [this](SDValue Op) { return *this == Op; }); 8927 } 8928 8929 bool SDNode::isOperandOf(const SDNode *N) const { 8930 return any_of(N->op_values(), 8931 [this](SDValue Op) { return this == Op.getNode(); }); 8932 } 8933 8934 /// reachesChainWithoutSideEffects - Return true if this operand (which must 8935 /// be a chain) reaches the specified operand without crossing any 8936 /// side-effecting instructions on any chain path. In practice, this looks 8937 /// through token factors and non-volatile loads. In order to remain efficient, 8938 /// this only looks a couple of nodes in, it does not do an exhaustive search. 8939 /// 8940 /// Note that we only need to examine chains when we're searching for 8941 /// side-effects; SelectionDAG requires that all side-effects are represented 8942 /// by chains, even if another operand would force a specific ordering. This 8943 /// constraint is necessary to allow transformations like splitting loads. 8944 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 8945 unsigned Depth) const { 8946 if (*this == Dest) return true; 8947 8948 // Don't search too deeply, we just want to be able to see through 8949 // TokenFactor's etc. 8950 if (Depth == 0) return false; 8951 8952 // If this is a token factor, all inputs to the TF happen in parallel. 8953 if (getOpcode() == ISD::TokenFactor) { 8954 // First, try a shallow search. 8955 if (is_contained((*this)->ops(), Dest)) { 8956 // We found the chain we want as an operand of this TokenFactor. 8957 // Essentially, we reach the chain without side-effects if we could 8958 // serialize the TokenFactor into a simple chain of operations with 8959 // Dest as the last operation. This is automatically true if the 8960 // chain has one use: there are no other ordering constraints. 8961 // If the chain has more than one use, we give up: some other 8962 // use of Dest might force a side-effect between Dest and the current 8963 // node. 8964 if (Dest.hasOneUse()) 8965 return true; 8966 } 8967 // Next, try a deep search: check whether every operand of the TokenFactor 8968 // reaches Dest. 8969 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 8970 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 8971 }); 8972 } 8973 8974 // Loads don't have side effects, look through them. 8975 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 8976 if (!Ld->isVolatile()) 8977 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 8978 } 8979 return false; 8980 } 8981 8982 bool SDNode::hasPredecessor(const SDNode *N) const { 8983 SmallPtrSet<const SDNode *, 32> Visited; 8984 SmallVector<const SDNode *, 16> Worklist; 8985 Worklist.push_back(this); 8986 return hasPredecessorHelper(N, Visited, Worklist); 8987 } 8988 8989 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 8990 this->Flags.intersectWith(Flags); 8991 } 8992 8993 SDValue 8994 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 8995 ArrayRef<ISD::NodeType> CandidateBinOps, 8996 bool AllowPartials) { 8997 // The pattern must end in an extract from index 0. 8998 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8999 !isNullConstant(Extract->getOperand(1))) 9000 return SDValue(); 9001 9002 SDValue Op = Extract->getOperand(0); 9003 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 9004 9005 // Match against one of the candidate binary ops. 9006 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 9007 return Op.getOpcode() == unsigned(BinOp); 9008 })) 9009 return SDValue(); 9010 unsigned CandidateBinOp = Op.getOpcode(); 9011 9012 // Matching failed - attempt to see if we did enough stages that a partial 9013 // reduction from a subvector is possible. 9014 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 9015 if (!AllowPartials || !Op) 9016 return SDValue(); 9017 EVT OpVT = Op.getValueType(); 9018 EVT OpSVT = OpVT.getScalarType(); 9019 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 9020 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 9021 return SDValue(); 9022 BinOp = (ISD::NodeType)CandidateBinOp; 9023 return getNode( 9024 ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 9025 getConstant(0, SDLoc(Op), TLI->getVectorIdxTy(getDataLayout()))); 9026 }; 9027 9028 // At each stage, we're looking for something that looks like: 9029 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 9030 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 9031 // i32 undef, i32 undef, i32 undef, i32 undef> 9032 // %a = binop <8 x i32> %op, %s 9033 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 9034 // we expect something like: 9035 // <4,5,6,7,u,u,u,u> 9036 // <2,3,u,u,u,u,u,u> 9037 // <1,u,u,u,u,u,u,u> 9038 // While a partial reduction match would be: 9039 // <2,3,u,u,u,u,u,u> 9040 // <1,u,u,u,u,u,u,u> 9041 SDValue PrevOp; 9042 for (unsigned i = 0; i < Stages; ++i) { 9043 unsigned MaskEnd = (1 << i); 9044 9045 if (Op.getOpcode() != CandidateBinOp) 9046 return PartialReduction(PrevOp, MaskEnd); 9047 9048 SDValue Op0 = Op.getOperand(0); 9049 SDValue Op1 = Op.getOperand(1); 9050 9051 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 9052 if (Shuffle) { 9053 Op = Op1; 9054 } else { 9055 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 9056 Op = Op0; 9057 } 9058 9059 // The first operand of the shuffle should be the same as the other operand 9060 // of the binop. 9061 if (!Shuffle || Shuffle->getOperand(0) != Op) 9062 return PartialReduction(PrevOp, MaskEnd); 9063 9064 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 9065 for (int Index = 0; Index < (int)MaskEnd; ++Index) 9066 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 9067 return PartialReduction(PrevOp, MaskEnd); 9068 9069 PrevOp = Op; 9070 } 9071 9072 BinOp = (ISD::NodeType)CandidateBinOp; 9073 return Op; 9074 } 9075 9076 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 9077 assert(N->getNumValues() == 1 && 9078 "Can't unroll a vector with multiple results!"); 9079 9080 EVT VT = N->getValueType(0); 9081 unsigned NE = VT.getVectorNumElements(); 9082 EVT EltVT = VT.getVectorElementType(); 9083 SDLoc dl(N); 9084 9085 SmallVector<SDValue, 8> Scalars; 9086 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 9087 9088 // If ResNE is 0, fully unroll the vector op. 9089 if (ResNE == 0) 9090 ResNE = NE; 9091 else if (NE > ResNE) 9092 NE = ResNE; 9093 9094 unsigned i; 9095 for (i= 0; i != NE; ++i) { 9096 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 9097 SDValue Operand = N->getOperand(j); 9098 EVT OperandVT = Operand.getValueType(); 9099 if (OperandVT.isVector()) { 9100 // A vector operand; extract a single element. 9101 EVT OperandEltVT = OperandVT.getVectorElementType(); 9102 Operands[j] = 9103 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand, 9104 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout()))); 9105 } else { 9106 // A scalar operand; just use it as is. 9107 Operands[j] = Operand; 9108 } 9109 } 9110 9111 switch (N->getOpcode()) { 9112 default: { 9113 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 9114 N->getFlags())); 9115 break; 9116 } 9117 case ISD::VSELECT: 9118 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 9119 break; 9120 case ISD::SHL: 9121 case ISD::SRA: 9122 case ISD::SRL: 9123 case ISD::ROTL: 9124 case ISD::ROTR: 9125 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 9126 getShiftAmountOperand(Operands[0].getValueType(), 9127 Operands[1]))); 9128 break; 9129 case ISD::SIGN_EXTEND_INREG: 9130 case ISD::FP_ROUND_INREG: { 9131 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 9132 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 9133 Operands[0], 9134 getValueType(ExtVT))); 9135 } 9136 } 9137 } 9138 9139 for (; i < ResNE; ++i) 9140 Scalars.push_back(getUNDEF(EltVT)); 9141 9142 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 9143 return getBuildVector(VecVT, dl, Scalars); 9144 } 9145 9146 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 9147 SDNode *N, unsigned ResNE) { 9148 unsigned Opcode = N->getOpcode(); 9149 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 9150 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 9151 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 9152 "Expected an overflow opcode"); 9153 9154 EVT ResVT = N->getValueType(0); 9155 EVT OvVT = N->getValueType(1); 9156 EVT ResEltVT = ResVT.getVectorElementType(); 9157 EVT OvEltVT = OvVT.getVectorElementType(); 9158 SDLoc dl(N); 9159 9160 // If ResNE is 0, fully unroll the vector op. 9161 unsigned NE = ResVT.getVectorNumElements(); 9162 if (ResNE == 0) 9163 ResNE = NE; 9164 else if (NE > ResNE) 9165 NE = ResNE; 9166 9167 SmallVector<SDValue, 8> LHSScalars; 9168 SmallVector<SDValue, 8> RHSScalars; 9169 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 9170 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 9171 9172 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 9173 SDVTList VTs = getVTList(ResEltVT, SVT); 9174 SmallVector<SDValue, 8> ResScalars; 9175 SmallVector<SDValue, 8> OvScalars; 9176 for (unsigned i = 0; i < NE; ++i) { 9177 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 9178 SDValue Ov = 9179 getSelect(dl, OvEltVT, Res.getValue(1), 9180 getBoolConstant(true, dl, OvEltVT, ResVT), 9181 getConstant(0, dl, OvEltVT)); 9182 9183 ResScalars.push_back(Res); 9184 OvScalars.push_back(Ov); 9185 } 9186 9187 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 9188 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 9189 9190 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 9191 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 9192 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 9193 getBuildVector(NewOvVT, dl, OvScalars)); 9194 } 9195 9196 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 9197 LoadSDNode *Base, 9198 unsigned Bytes, 9199 int Dist) const { 9200 if (LD->isVolatile() || Base->isVolatile()) 9201 return false; 9202 if (LD->isIndexed() || Base->isIndexed()) 9203 return false; 9204 if (LD->getChain() != Base->getChain()) 9205 return false; 9206 EVT VT = LD->getValueType(0); 9207 if (VT.getSizeInBits() / 8 != Bytes) 9208 return false; 9209 9210 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 9211 auto LocDecomp = BaseIndexOffset::match(LD, *this); 9212 9213 int64_t Offset = 0; 9214 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 9215 return (Dist * Bytes == Offset); 9216 return false; 9217 } 9218 9219 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if 9220 /// it cannot be inferred. 9221 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const { 9222 // If this is a GlobalAddress + cst, return the alignment. 9223 const GlobalValue *GV; 9224 int64_t GVOffset = 0; 9225 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 9226 unsigned IdxWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType()); 9227 KnownBits Known(IdxWidth); 9228 llvm::computeKnownBits(GV, Known, getDataLayout()); 9229 unsigned AlignBits = Known.countMinTrailingZeros(); 9230 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0; 9231 if (Align) 9232 return MinAlign(Align, GVOffset); 9233 } 9234 9235 // If this is a direct reference to a stack slot, use information about the 9236 // stack slot's alignment. 9237 int FrameIdx = INT_MIN; 9238 int64_t FrameOffset = 0; 9239 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 9240 FrameIdx = FI->getIndex(); 9241 } else if (isBaseWithConstantOffset(Ptr) && 9242 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 9243 // Handle FI+Cst 9244 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 9245 FrameOffset = Ptr.getConstantOperandVal(1); 9246 } 9247 9248 if (FrameIdx != INT_MIN) { 9249 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 9250 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx), 9251 FrameOffset); 9252 return FIInfoAlign; 9253 } 9254 9255 return 0; 9256 } 9257 9258 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 9259 /// which is split (or expanded) into two not necessarily identical pieces. 9260 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 9261 // Currently all types are split in half. 9262 EVT LoVT, HiVT; 9263 if (!VT.isVector()) 9264 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 9265 else 9266 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 9267 9268 return std::make_pair(LoVT, HiVT); 9269 } 9270 9271 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 9272 /// low/high part. 9273 std::pair<SDValue, SDValue> 9274 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 9275 const EVT &HiVT) { 9276 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <= 9277 N.getValueType().getVectorNumElements() && 9278 "More vector elements requested than available!"); 9279 SDValue Lo, Hi; 9280 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, 9281 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout()))); 9282 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 9283 getConstant(LoVT.getVectorNumElements(), DL, 9284 TLI->getVectorIdxTy(getDataLayout()))); 9285 return std::make_pair(Lo, Hi); 9286 } 9287 9288 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 9289 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 9290 EVT VT = N.getValueType(); 9291 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 9292 NextPowerOf2(VT.getVectorNumElements())); 9293 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 9294 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout()))); 9295 } 9296 9297 void SelectionDAG::ExtractVectorElements(SDValue Op, 9298 SmallVectorImpl<SDValue> &Args, 9299 unsigned Start, unsigned Count) { 9300 EVT VT = Op.getValueType(); 9301 if (Count == 0) 9302 Count = VT.getVectorNumElements(); 9303 9304 EVT EltVT = VT.getVectorElementType(); 9305 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout()); 9306 SDLoc SL(Op); 9307 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 9308 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9309 Op, getConstant(i, SL, IdxTy))); 9310 } 9311 } 9312 9313 // getAddressSpace - Return the address space this GlobalAddress belongs to. 9314 unsigned GlobalAddressSDNode::getAddressSpace() const { 9315 return getGlobal()->getType()->getAddressSpace(); 9316 } 9317 9318 Type *ConstantPoolSDNode::getType() const { 9319 if (isMachineConstantPoolEntry()) 9320 return Val.MachineCPVal->getType(); 9321 return Val.ConstVal->getType(); 9322 } 9323 9324 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 9325 unsigned &SplatBitSize, 9326 bool &HasAnyUndefs, 9327 unsigned MinSplatBits, 9328 bool IsBigEndian) const { 9329 EVT VT = getValueType(0); 9330 assert(VT.isVector() && "Expected a vector type"); 9331 unsigned VecWidth = VT.getSizeInBits(); 9332 if (MinSplatBits > VecWidth) 9333 return false; 9334 9335 // FIXME: The widths are based on this node's type, but build vectors can 9336 // truncate their operands. 9337 SplatValue = APInt(VecWidth, 0); 9338 SplatUndef = APInt(VecWidth, 0); 9339 9340 // Get the bits. Bits with undefined values (when the corresponding element 9341 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 9342 // in SplatValue. If any of the values are not constant, give up and return 9343 // false. 9344 unsigned int NumOps = getNumOperands(); 9345 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 9346 unsigned EltWidth = VT.getScalarSizeInBits(); 9347 9348 for (unsigned j = 0; j < NumOps; ++j) { 9349 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 9350 SDValue OpVal = getOperand(i); 9351 unsigned BitPos = j * EltWidth; 9352 9353 if (OpVal.isUndef()) 9354 SplatUndef.setBits(BitPos, BitPos + EltWidth); 9355 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 9356 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 9357 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 9358 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 9359 else 9360 return false; 9361 } 9362 9363 // The build_vector is all constants or undefs. Find the smallest element 9364 // size that splats the vector. 9365 HasAnyUndefs = (SplatUndef != 0); 9366 9367 // FIXME: This does not work for vectors with elements less than 8 bits. 9368 while (VecWidth > 8) { 9369 unsigned HalfSize = VecWidth / 2; 9370 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 9371 APInt LowValue = SplatValue.trunc(HalfSize); 9372 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 9373 APInt LowUndef = SplatUndef.trunc(HalfSize); 9374 9375 // If the two halves do not match (ignoring undef bits), stop here. 9376 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 9377 MinSplatBits > HalfSize) 9378 break; 9379 9380 SplatValue = HighValue | LowValue; 9381 SplatUndef = HighUndef & LowUndef; 9382 9383 VecWidth = HalfSize; 9384 } 9385 9386 SplatBitSize = VecWidth; 9387 return true; 9388 } 9389 9390 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 9391 BitVector *UndefElements) const { 9392 if (UndefElements) { 9393 UndefElements->clear(); 9394 UndefElements->resize(getNumOperands()); 9395 } 9396 assert(getNumOperands() == DemandedElts.getBitWidth() && 9397 "Unexpected vector size"); 9398 if (!DemandedElts) 9399 return SDValue(); 9400 SDValue Splatted; 9401 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 9402 if (!DemandedElts[i]) 9403 continue; 9404 SDValue Op = getOperand(i); 9405 if (Op.isUndef()) { 9406 if (UndefElements) 9407 (*UndefElements)[i] = true; 9408 } else if (!Splatted) { 9409 Splatted = Op; 9410 } else if (Splatted != Op) { 9411 return SDValue(); 9412 } 9413 } 9414 9415 if (!Splatted) { 9416 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 9417 assert(getOperand(FirstDemandedIdx).isUndef() && 9418 "Can only have a splat without a constant for all undefs."); 9419 return getOperand(FirstDemandedIdx); 9420 } 9421 9422 return Splatted; 9423 } 9424 9425 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 9426 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 9427 return getSplatValue(DemandedElts, UndefElements); 9428 } 9429 9430 ConstantSDNode * 9431 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 9432 BitVector *UndefElements) const { 9433 return dyn_cast_or_null<ConstantSDNode>( 9434 getSplatValue(DemandedElts, UndefElements)); 9435 } 9436 9437 ConstantSDNode * 9438 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 9439 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 9440 } 9441 9442 ConstantFPSDNode * 9443 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 9444 BitVector *UndefElements) const { 9445 return dyn_cast_or_null<ConstantFPSDNode>( 9446 getSplatValue(DemandedElts, UndefElements)); 9447 } 9448 9449 ConstantFPSDNode * 9450 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 9451 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 9452 } 9453 9454 int32_t 9455 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 9456 uint32_t BitWidth) const { 9457 if (ConstantFPSDNode *CN = 9458 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 9459 bool IsExact; 9460 APSInt IntVal(BitWidth); 9461 const APFloat &APF = CN->getValueAPF(); 9462 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 9463 APFloat::opOK || 9464 !IsExact) 9465 return -1; 9466 9467 return IntVal.exactLogBase2(); 9468 } 9469 return -1; 9470 } 9471 9472 bool BuildVectorSDNode::isConstant() const { 9473 for (const SDValue &Op : op_values()) { 9474 unsigned Opc = Op.getOpcode(); 9475 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 9476 return false; 9477 } 9478 return true; 9479 } 9480 9481 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 9482 // Find the first non-undef value in the shuffle mask. 9483 unsigned i, e; 9484 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 9485 /* search */; 9486 9487 // If all elements are undefined, this shuffle can be considered a splat 9488 // (although it should eventually get simplified away completely). 9489 if (i == e) 9490 return true; 9491 9492 // Make sure all remaining elements are either undef or the same as the first 9493 // non-undef value. 9494 for (int Idx = Mask[i]; i != e; ++i) 9495 if (Mask[i] >= 0 && Mask[i] != Idx) 9496 return false; 9497 return true; 9498 } 9499 9500 // Returns the SDNode if it is a constant integer BuildVector 9501 // or constant integer. 9502 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) { 9503 if (isa<ConstantSDNode>(N)) 9504 return N.getNode(); 9505 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 9506 return N.getNode(); 9507 // Treat a GlobalAddress supporting constant offset folding as a 9508 // constant integer. 9509 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 9510 if (GA->getOpcode() == ISD::GlobalAddress && 9511 TLI->isOffsetFoldingLegal(GA)) 9512 return GA; 9513 return nullptr; 9514 } 9515 9516 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) { 9517 if (isa<ConstantFPSDNode>(N)) 9518 return N.getNode(); 9519 9520 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 9521 return N.getNode(); 9522 9523 return nullptr; 9524 } 9525 9526 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 9527 assert(!Node->OperandList && "Node already has operands"); 9528 assert(SDNode::getMaxNumOperands() >= Vals.size() && 9529 "too many operands to fit into SDNode"); 9530 SDUse *Ops = OperandRecycler.allocate( 9531 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 9532 9533 bool IsDivergent = false; 9534 for (unsigned I = 0; I != Vals.size(); ++I) { 9535 Ops[I].setUser(Node); 9536 Ops[I].setInitial(Vals[I]); 9537 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 9538 IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent(); 9539 } 9540 Node->NumOperands = Vals.size(); 9541 Node->OperandList = Ops; 9542 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 9543 if (!TLI->isSDNodeAlwaysUniform(Node)) 9544 Node->SDNodeBits.IsDivergent = IsDivergent; 9545 checkForCycles(Node); 9546 } 9547 9548 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 9549 SmallVectorImpl<SDValue> &Vals) { 9550 size_t Limit = SDNode::getMaxNumOperands(); 9551 while (Vals.size() > Limit) { 9552 unsigned SliceIdx = Vals.size() - Limit; 9553 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 9554 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 9555 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 9556 Vals.emplace_back(NewTF); 9557 } 9558 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 9559 } 9560 9561 #ifndef NDEBUG 9562 static void checkForCyclesHelper(const SDNode *N, 9563 SmallPtrSetImpl<const SDNode*> &Visited, 9564 SmallPtrSetImpl<const SDNode*> &Checked, 9565 const llvm::SelectionDAG *DAG) { 9566 // If this node has already been checked, don't check it again. 9567 if (Checked.count(N)) 9568 return; 9569 9570 // If a node has already been visited on this depth-first walk, reject it as 9571 // a cycle. 9572 if (!Visited.insert(N).second) { 9573 errs() << "Detected cycle in SelectionDAG\n"; 9574 dbgs() << "Offending node:\n"; 9575 N->dumprFull(DAG); dbgs() << "\n"; 9576 abort(); 9577 } 9578 9579 for (const SDValue &Op : N->op_values()) 9580 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 9581 9582 Checked.insert(N); 9583 Visited.erase(N); 9584 } 9585 #endif 9586 9587 void llvm::checkForCycles(const llvm::SDNode *N, 9588 const llvm::SelectionDAG *DAG, 9589 bool force) { 9590 #ifndef NDEBUG 9591 bool check = force; 9592 #ifdef EXPENSIVE_CHECKS 9593 check = true; 9594 #endif // EXPENSIVE_CHECKS 9595 if (check) { 9596 assert(N && "Checking nonexistent SDNode"); 9597 SmallPtrSet<const SDNode*, 32> visited; 9598 SmallPtrSet<const SDNode*, 32> checked; 9599 checkForCyclesHelper(N, visited, checked, DAG); 9600 } 9601 #endif // !NDEBUG 9602 } 9603 9604 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 9605 checkForCycles(DAG->getRoot().getNode(), DAG, force); 9606 } 9607