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