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