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